Skip to content

Instantly share code, notes, and snippets.

@juliangruber
Last active November 21, 2021 21:13
Show Gist options
  • Save juliangruber/6816433 to your computer and use it in GitHub Desktop.
Save juliangruber/6816433 to your computer and use it in GitHub Desktop.
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;
}
@eugeneware
Copy link

That's freaking cool!

@mattmcmanus
Copy link

This was epically helpful. Thanks for sharing!

@maiah
Copy link

maiah commented Oct 10, 2013

Great! Thanks for sharing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment