pd-redis-model
To facilitate database operation in Redis
Installation
npm install -save pd-redis-model
Tutorial
Create a model
var User = require('pd-redis-model')('user');
'user' is the saved name of the model, all capital letters are converted into lower-case letters
C.R.U.D
To create:
var profile = {
email : 'myletter@email.com',
password : 'abc123'
};
var creatingPromise = User.create(profile);
The returning value of User.create is a q.Promise
The newly created record will have a sequence id which is unique of the type. It can be fetched by using 'then' of the promise as follows
creatingPromise.then(function(sid){
});
To read:
To find one record
var readingPromise = User.findBySid('1')
Again the returning value of User.findBySid is a q.Promise. The record information can be read by using 'then' as follows
readingPromise.then(function(rec){
});
To find a list of records
var option = {
latest: (new Date()).getTime(),
earliest : 0
}
var listPromise = User.range(option);
It will return all available records in a list in descending order of time. They can be reached as follows
listPromise.then(function(list){
});
To get total amount of a model
var amountPromise = User.amount();
amountPromise.then(function(amount){
});
To update:
var profile = {
'pd-sid' : 1
password : '123abc',
status : 'online'
};
var updatePromise = User.modify(profile);
The 'pd-sid' which is the auto-increase id field can never be updated but it should be assigned value to specify which record is to be updated.
To remove:
var removePromise = User.remove('1')
More about CRUD
For more details, check Base Record
Set model fields
Set unique fields
User.setUniqueDef('account-name', ['email']);
var readPromise = User.withUnique('account-name').findBy('myhost@email.com');
check Set unique fields for more details
Set non-empty fields
User.needInputOf(['email', 'password'])
User.eachInputOf('email').mustMatch(function(val){
return require('validator').isEmail(val);
})
User.eachInputOf('password').mustMatch(/^\w{6,30}$/);
check Set non-empty fields for more details
Set relationship
var Posts = require('pd-redis-model')('post');
User.mother(Posts);
var userSid = '1';
var postProfile = {
content : 'Hello'
};
User.PostOwner(userSid).bear(postProfile);
var postSid = '12';
User.PostOwner(userSid).hasKid(postSid);
User.PostOwner(userSid).findKids({
latest: (new Date()).getTime(),
earliest: 0
});
Posts.UserKid(postSid).getParent();
check Set parenthood for more details