hash-props
v1.0.1
Published
Get a hash of an object calculated from certain properties
Downloads
7
Readme
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 = require('hash-props');
const obj1 = {greeting: 'hello', to: 'world'};
const obj2 = {greeting: 'hello', to: 'universe'};
console.log(hashProps(obj1, ['greeting']));
// 5d41402abc4b2a76b9719d911017c592
console.log(hashProps(obj2, ['greeting']));
// 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} = require('hash-props');
const db = require('some-db-without-unique-keys');
const obj1 = {greeting: 'hello', to: 'world'}
db.insert(hashId(obj1, ['greeting']));
// inserts:
// { greeting: 'hello',
// to: 'world',
// id: '5d41402abc4b2a76b9719d911017c592' }
const obj2 = {greeting: 'hello', to: 'universe'};
db.insert(hashId(obj2, ['greeting']));
// 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