using level-sublevel, level-sec and validimir to have
- validations
- schema documentation
- schema enforcement
- index definitions
of all your data in one file.
using level-sublevel, level-sec and validimir to have
of all your data in one file.
| var level = require('level'); | |
| var sub = require('level-sublevel'); | |
| var avg = require('level-average'); | |
| var index = require('level-sec'); | |
| var v = require('validimir'); | |
| var emailRegExp = require('./email-regexp'); | |
| /** | |
| * Database. | |
| */ | |
| var db = sub(level(__dirname + '/../../db', { | |
| valueEncoding: 'json' | |
| })); | |
| module.exports = db; | |
| /** | |
| * Ratings. | |
| */ | |
| db.ratings = avg(db.sublevel('ratings')); | |
| validate(db.sublevel('ratings'), v.rules({ | |
| key: v.string().match(/^[^!]+![^!]+$/), | |
| value: v.number().equal({ gte: 0, lte: 5 }) | |
| })); | |
| /** | |
| * Blog posts. | |
| */ | |
| db.posts = index(db.sublevel('posts')) | |
| .by('Slug', ['slug']) | |
| .by('Creator', ['creator', 'createdAt']) | |
| .by('Published', ['published', 'createdAt']) | |
| .db; | |
| validate(db.posts, v.rules({ | |
| 'key': v.string().match(/[0-9a-f]{32}/), | |
| 'value': v.rules({ | |
| 'title': v.string().len({ gte: 3 }), | |
| 'createdAt': v.number(), | |
| 'creator': v.string(), | |
| 'id': v.string().equal(v.value('../key')), | |
| 'categories': v.optional().array().each(v.string().match(/[0-9a-f]{32}/)) | |
| }) | |
| })); | |
| /** | |
| * Published. | |
| */ | |
| db.published = index(db.sublevel('published')) | |
| .by('Slug', ['slug']) | |
| .db; | |
| validate(db.published, v.rules({ | |
| 'key': v.string().equal(v.value('value.id')), | |
| 'value': v.object().rules({ | |
| 'id': v.string().match(/[0-9a-f]{32}/), | |
| 'title': v.string().len({ gte: 3 }), | |
| 'creator': v.string(), | |
| 'slug': v.string() | |
| }) | |
| })); | |
| /** | |
| * Users. | |
| */ | |
| db.users = db.sublevel('users'); | |
| validate(db.users, v.rules({ | |
| 'key': v.string().equal(v.value('value.name')), | |
| 'value': v.object().rules({ | |
| 'email': v.string().match(emailRegExp), | |
| 'name': v.string() | |
| }) | |
| })); | |
| /** | |
| * Sessions. | |
| */ | |
| db.sessions = db.sublevel('sessions'); | |
| validate(db.sessions, v.rules({ | |
| 'key': v.string(), | |
| 'value': v.string().match(emailRegExp) | |
| })); | |
| /** | |
| * Emails. | |
| */ | |
| db.emails = db.sublevel('emails'); | |
| validate(db.emails, v.rules({ | |
| 'key': v.string().match(emailRegExp), | |
| 'value': v.string() | |
| })); | |
| /** | |
| * Validation helper. | |
| */ | |
| function validate(db, fn) { | |
| db.pre(function(ch) { | |
| if (ch.type == 'put') fn(ch); | |
| }); | |
| return db; | |
| } |
This was epically helpful. Thanks for sharing!
Great! Thanks for sharing
That's freaking cool!