UNPKG

2 kBMarkdownView Raw
1# level-model
2
3A 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```
8var level = require('level')
9var Model = require('level-model')
10var inherits = require('util').inherits
11var db = level('db')
12
13function Posts (db, opts) {
14 Model.call(this, db, opts)
15}
16
17inherits(Posts, Model)
18
19var 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
29var data = {
30 title: 'first post!',
31 content: 'this is some text.'
32}
33
34posts.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```
44var Model = require('level-model')
45var inherits = require('util').inherits
46
47function Posts (db, options) {
48 Model.call(this, db, options)
49}
50
51inherits(Posts, Model)
52```
53
54### `var posts = new Posts(db, options)`
55
56Options:
57
58```js
59{
60 modelName: 'Example',
61 indexKeys: [],
62 properties: {},
63 required: []
64}
65```
66
67The 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
83Override level-model's `beforeCreate` and `beforeUpdate` methods to format data before it is saved to the db:
84
85```
86function Posts (db, options) {
87 Model.call(this, db, options)
88}
89
90Posts.prototype.beforeCreate = function (data) {
91 data.slug = slugify(data.title)
92 return data
93}
94
95Posts.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
110MIT
\No newline at end of file