hash-props
Get a hash of an object calculated from certain properties
Why?
This is useful for generating an id/key for an object to be used as the object's primary key in databases not supporting unique indexes/keys, e.g. RethinkDB.
Usage
Basic Module usage
const hashProps = ; const obj1 = greeting: 'hello' to: 'world';const obj2 = greeting: 'hello' to: 'universe'; console;// 5d41402abc4b2a76b9719d911017c592console;// 5d41402abc4b2a76b9719d911017c592
Generating id's to use in db's without unique keys
Some databases does not support unique keys/indexes, for instance RethinkDB.
By generating a hash id, based on the properties you want a unique key for, and using it as the object's primary key we can simulate the behavior of a unique key.
const hashId = ;const db = ; const obj1 = greeting: 'hello' to: 'world'db;// inserts:// { greeting: 'hello',// to: 'world',// id: '5d41402abc4b2a76b9719d911017c592' }const obj2 = greeting: 'hello' to: 'universe';db;// does not insert the following, because of already existing primary key:// { greeting: 'hello',// to: 'universe',// id: '5d41402abc4b2a76b9719d911017c592' }
API
hashProps(obj [, props])
Name | Type | Description |
---|---|---|
obj | Object |
The object to get a hash for |
props | Array<String> |
The properties from obj to use for hash generation (optional) |
Returns: String
an md5 hash based on given props
property values in obj
, if props
is omitted a hash of the objects all properties will be generated.
hashId(obj [, props])
Name | Type | Description |
---|---|---|
obj | Object |
The object to generate a hash id for |
props | Array<String> |
The properties from obj to use for hash generation (optional) |
Returns: Object
, a clone of obj
with an id
property containing an md5 hash, generated by hashProps
above.
hashStr(str)
Name | Type | Description |
---|---|---|
str | String |
A string to generate an md5 hash for |
Returns: String
, the md5 hash for given str
.
Installation
Install hash-props
using npm:
npm install --save hash-props
License
MIT © Joakim Carlstein