conancat/mongoose-redis-cache — pull request #7 by lbeschastny (2013-08-07 15:53:40+00:00)
Title: Redis key serialization

JSON.stringify is not a good way to build redis key. It have several problems:

1. It's ugly.
2. It's long.
3. JSON.stringify is unable to serialize objects like `RegExp`.
4. It serializes query regardless of the collection it's querying. So, two identical queries for two different collections will create a collision.
5. It's sensitive to the order of Object's properties, making `{q: 1, w: 2}` and `{w:2, q:1}` two different queries.

I solved first four problems with this fix.

`RegExp` is the only js object without JSON representation which will make sense in mongodb queries, so I simply added `RegExp::toJSON` prototype. Thanks to node.js isolation it'll newer be visible outside of `mongoose-redis-cache`.

I added `collectionName` to the redis key prevent cache collisions.

I also added special `prefix` option. So, now it's possible two run two separate caches on a single redis server.

I also added `md5` hashing to make keys shorter. `md5` is just as unreadable for humans as JSON is, but it's much shorter. And `md5` hashing is so fast that it won't create any overhead.

I left the last problem unsolved, because I thought current solution mire suitable for cache. The possibility of having two equivalent queries with different properties order is very small. Yet, sorting object keys is a heavy task which requires a lot of resources, especially written in node.js (comparing to C++). So, I thought it'll be best to leave it as it is.