# pd-redis-base-record

> Simple ORM record model with auto-increment sid

Latest version **0.1.8** (published 2015-07-20) · MIT license · 0 weekly downloads

> **Deprecated.** This package is deprecated.

## Install

```sh
npm install pd-redis-base-record
pnpm add pd-redis-base-record
yarn add pd-redis-base-record
bun add pd-redis-base-record
```

## Health

**Score 10/100 (F)** — status: deprecated.

Negative: deprecated.

## Facts

| | |
|---|---|
| Version | 0.1.8 |
| Published | 2015-07-20 |
| First published | 2015-04-20 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 5 |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | Martin Zheng |
| Maintainers | jszhengyq |
| Keywords | ORM, redis, CRUD, record |

## Links

- npm: https://www.npmjs.com/package/pd-redis-base-record
- Repository: https://github.com/pandazy/pd-redis-base-record
- Issues: https://github.com/pandazy/pd-redis-base-record/issues
- npm.io page: https://npm.io/package/pd-redis-base-record

## Dependencies (5)

- [q](https://npm.io/package/q.md) ^1.4.1
- [underscore](https://npm.io/package/underscore.md) ^1.8.3
- [pd-node-redis](https://npm.io/package/pd-node-redis.md) ^0.1.4
- [pd-redis-lock](https://npm.io/package/pd-redis-lock.md) ^0.1.2
- [pd-api-announcer](https://npm.io/package/pd-api-announcer.md) ^0.2.2

## Alternatives

- [mobx-react](https://npm.io/package/mobx-react.md) — 2.8M weekly downloads
- [rc-tree](https://npm.io/package/rc-tree.md) — 2.6M weekly downloads
- [@react-oauth/google](https://npm.io/package/@react-oauth/google.md) — 1.3M weekly downloads
- [@wagmi/connectors](https://npm.io/package/@wagmi/connectors.md) — 877.0K weekly downloads
- [vee-validate](https://npm.io/package/vee-validate.md) — 836.4K weekly downloads

## Recent versions

- 0.1.8 (latest) — 2015-07-20
- 0.1.7 — 2015-05-07
- 0.1.6 — 2015-05-07
- 0.1.5 — 2015-04-23
- 0.1.4 — 2015-04-22
- 0.1.3 — 2015-04-21
- 0.1.2 — 2015-04-21
- 0.1.1 — 2015-04-20
- 0.1.0 — 2015-04-20

## README

# pd-redis-base-record
Simple ORM record model with auto-increment sid

## Installation
```
$ npm install -save pd-redis-base-record
```
<hr/>
## Starting
```javascript
var User = require('pd-redis-base-record')('user');
```
'user' is the code name of the model, for the code below
```javascript
var User = require('pd-redis-base-record')('USER');
```
It is equivalent to 
```javascript
require('pd-redis-base-record')('user')
```
It is converting any model name into lower-case letters.
<hr/>
## To create: Model.create(JSON)
```javascript
var profile = {
   email : 'myletter@email.com', 
   name : 'John Doe',
   password : 'abc123'
};
var creatingPromise = User.create(profile); 
```
The returning value of User.create is a [q.Promise](https://github.com/kriskowal/q)
The newly created record will have an auto-generated sequence id which is unique of the type. 
It can be fetched by using 'then' of the promise as follows
```javascript
creatingPromise.then(function(sid){
   //do something to the returned sid...
});
```
q.Promise is also used in other CRUD methods or modules as shown below

## To modify: Model.modify(JSON)
```javascript
var profileToModify = {
  'pd-sid' : '12' ,
   name : 'Jane Doe',
   gender : 'female'
};
User.modify(profileToModify).then(function(){
   //do something after modification
});
```
'pd-sid' is not a changeable field, but it has to be assigned to specify which record to be modified.

## To remove: Model.remove(sid)
```javascript
var sid = '12';
User.remove(sid).then(function(){
   //do something after removal
});
```

## To read
### To get total amount of records of a model: Model.amount()
```javascript
User.amount().then(function(amount){ 
   //do something to amount
});
```
### To get a record by specifying sid: Model.findBySid(sid)
```javascript
User.findBySid(12).then(function(record){
  //record => { email: 'myletter@email.com', name: 'Jane Doe', updatedAt : '12345678901' }
  //Because the data is modified just now, so it automatically got 'updatedAt' field
});  
```
### To get a list of records: Model.range(option)
```javascript
User.range({
  latest: (new Date()).getTime(), //* the ending time point of list
  earliest: 0 ,                   //* the starting time point of list
  limit : [0, 50],                //(optional)[start, offset] 
}).then(function(records){
  //records:
  // [
  //    {'pd-sid' : 1 ,  email : 'myletter1@email.com' ... }, 
  //    {'pd-sid' : 2,  email: 'myletter2@email.com' ...}
  //    .....
  // ]
});
```
### To decide if a record is brand new: Model.checkAbsence(sid)
```javascript
User.checkAbsence(sid).then(function(){
   //record not found
}).fail(function(err){
   var announcer = require('pd-api-announcer');
   if(announcer.isClientErrorFor(err, 'user', 'taken')) { 
       //record already existed 
   }
});
```
###To decide if a record already existed: Model.checkPresence(sid)
```javascript
User.checkPresence(sid).then(function(){
   //record found
}).fail(function(err){
   var announcer = require('pd-api-announcer');
   if(announcer.isClientErrorFor(err, 'user', 'gone')){
      //record not found
   }
});
```
## To lock
### To lock a type of records: Model.lock.sidSet(onLockCallback, expiredAfterMilliseconds)
Where the lock is used, every time the same routine visits the locked sid-set, if there is still a locked routine, 
it will wait until the previous routine is done
```javascript
var onLockCallback = function(){
    return User.create({
       email: 'myletter@email.com',
       password: 'abc123'
    }); 
};
User.lock.sidSet(onLockCallback); //by default it will expire after 15000 milliseconds
```
If asynchronous operation is to be added in onLockCallback, 
the return value of onLockCallback should be a q.Promise object, 
so that the lock will wait until all operations are over then release the lock.

The returning value of User.lock.sidSet() is also a q.Promise, 
all code in User.lock.sidSet().then() will be executed after the lock is released
```javascript
User.lock.sidSet(function(){...}).then(function(){
   //do something after the lock is released
});
```
### To lock one record: Model.lock.dataForSid(sid, onLockCallback, expiredAfterMilliseconds)
Similar to lock.sidSet(), but it only locks operations on a single record, or to be specific, 
dependent on one sid of a type of records
```javascript
var sid = '12';
var onLockCallback = function(){
    return User.modify({
       'pd-sid' : sid,
       email: 'myletter@email.com',
       password: 'abc123'
    }); 
};
User.lock.dataForSid(sid, onLockCallback);
```
### check [pd-redis-lock](https://github.com/pandazy/pd-redis-lock) for more details about lock
<hr>
## More CRUD functions
### To read
#### User.findBySid(sid, option)
It is available to get data from only specific fields with option.fields
```javascript
User.findBySid(12, {  fields: ['name', 'email']  }).then(function(record){
   //record => ['Jane Doe', 'myletter@email.com']
});
```
It is also available to show 'createdAt' by setting option.withCreatedAt to true
```javascript
User.findBySid(12, { withCreatedAt : true }).then(function(record){
  //record => { email: 'myletter@email.com', name: 'Jane Doe', updatedAt : '12345678901', createdAt : '1234567777' }
});
User.findBySid(12, {  fields: ['name', 'email'], withCreatedAt: true  }).then(function(record){
   //record => ['Jane Doe', 'myletter@email.com', '123456788888']
}); 
```
option.fields and option.withCreatedAt are also available for User.range(option);
### To create, modify or remove
#### User.create(profile, onGeneratingMultiList)
It is available to add a set of redis commands so that when the record is created, 
they run together as MULTI commands of the creating action to guarantee the atomicity of the creating operation
```javascript
var hashPwd = function(pwd){ .... }
var password = 'abc123'
var hashedPwd = hashPwd(password);
var onGeneratingMultiList = function(multi, profile){
     var sid = profile['pd-sid'];
     var newCmd = ['hmset', User.nm.dataForSid(sid), 'password', hashedPwd )];
     multi.add(newCmd);
     return multi;  //must return the MULTI list or a q.Promise that returns a MULTI list
};
User.create({
  email : 'myletter@email.com',
  password : password
}, onGeneratingMultiList);
```
The 'multi' in onGeneratingMultiList() is an array which looks like the following
```javascript
[ 
  [ 'zadd', 'pd-sids-of:user', 1430675568559, 1 ],
  [ 'hmset',
    'model:user:withsid:1',
    { email: 'myletter@email.com', password: 'abc123', 'pd-sid': 1 } ] ]
  [ 'hmset',
    'model:user:withsid:1',
    { email: 'myletter@email.com', password: '[encoded pwd]', 'pd-sid': 1 } ] 
]    
```
The record will be finally created by executing all the commands in a MULTI in Redis
#### User.modify(profile, onGeneratingMultiList)
For on GeneratingMultiList, it is similar to User.create
#### User.remove(sid, onGeneratingMultiList)
For on GeneratingMultiList, it is similar to User.create

### Check [pd-node-redis](https://github.com/pandazy/pd-node-redis) for details of Redis-client implementation

---
_Source: https://npm.io/package/pd-redis-base-record · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
