1 | # level-model
|
2 |
|
3 | A higher-level module for creating content models using [levelup](http://npmjs.org/levelup) as db and [is-my-json-valid](http://npmjs.org/is-my-json-valid) for validation.
|
4 |
|
5 | ## Example
|
6 |
|
7 | ```
|
8 | var level = require('level')
|
9 | var Model = require('level-model')
|
10 | var inherits = require('util').inherits
|
11 | var db = level('db')
|
12 |
|
13 | function Posts (db, opts) {
|
14 | Model.call(this, db, opts)
|
15 | }
|
16 |
|
17 | inherits(Posts, Model)
|
18 |
|
19 | var posts = new Posts(db, {
|
20 | modelName: 'example',
|
21 | indexKeys: ['test', 'ok'],
|
22 | properties: {
|
23 | title: { type: 'string' },
|
24 | content: { type: 'string' },
|
25 | },
|
26 | required: ['title']
|
27 | })
|
28 |
|
29 | var data = {
|
30 | title: 'first post!',
|
31 | content: 'this is some text.'
|
32 | }
|
33 |
|
34 | posts.create(data, function (err, post) {
|
35 | console.log(err, post)
|
36 | })
|
37 | ```
|
38 |
|
39 | ## API
|
40 |
|
41 | ### Create a model that inherits from level-model
|
42 |
|
43 | ```
|
44 | var Model = require('level-model')
|
45 | var inherits = require('util').inherits
|
46 |
|
47 | function Posts (db, options) {
|
48 | Model.call(this, db, options)
|
49 | }
|
50 |
|
51 | inherits(Posts, Model)
|
52 | ```
|
53 |
|
54 | ### `var posts = new Posts(db, options)`
|
55 |
|
56 | Options:
|
57 |
|
58 | ```js
|
59 | {
|
60 | modelName: 'Example',
|
61 | indexKeys: [],
|
62 | properties: {},
|
63 | required: []
|
64 | }
|
65 | ```
|
66 |
|
67 | The options object can accept anything that [json-schema](http://json-schema.org) accepts.
|
68 |
|
69 | ### `posts.create(data, callback)`
|
70 |
|
71 | ### `posts.get(key, options, callback)`
|
72 |
|
73 | ### `posts.update(key, data, callback)`
|
74 |
|
75 | ### `posts.delete(key, callback)`
|
76 |
|
77 | ### `posts.createReadStream(options)`
|
78 |
|
79 | ### `posts.find(index, options)`
|
80 |
|
81 | ## Format data before create & update
|
82 |
|
83 | Override level-model's `beforeCreate` and `beforeUpdate` methods to format data before it is saved to the db:
|
84 |
|
85 | ```
|
86 | function Posts (db, options) {
|
87 | Model.call(this, db, options)
|
88 | }
|
89 |
|
90 | Posts.prototype.beforeCreate = function (data) {
|
91 | data.slug = slugify(data.title)
|
92 | return data
|
93 | }
|
94 |
|
95 | Posts.prototype.beforeUpdate = function (data) {
|
96 | return data
|
97 | }
|
98 | ```
|
99 |
|
100 | ## Events
|
101 |
|
102 | ### `example.on('create', function (model) {})`
|
103 |
|
104 | ### `example.on('update', function (model) {})`
|
105 |
|
106 | ### `example.on('delete', function () {})`
|
107 |
|
108 | ## License
|
109 |
|
110 | MIT |
\ | No newline at end of file |