├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE.md ├── README.md ├── examples ├── README.md ├── basic-usage.js └── browser.js ├── index.js ├── package.json └── tests ├── README.md └── index.js /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules 3 | npm-debug.log -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - '6' 4 | - '8' 5 | - '10' 6 | sudo: false 7 | cache: 8 | directories: 9 | - node_modules 10 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # level-model change log 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). 6 | 7 | ## 3.0.0 8 | 9 | ### Changed 10 | 11 | - Now uses a functional API rather than inheriting a prototype. See README for changes. 12 | 13 | ## 2.0.4 14 | 15 | ### Added 16 | - examples directory 17 | - browser example 18 | - basic usage example 19 | - use standard 20 | 21 | ### Changed 22 | - moved tests to tests/index.js 23 | - using memdb 24 | 25 | ## 2.0.3 - 2015-10-19 26 | 27 | ### Added 28 | - add CONDUCT.md 29 | - add CONTRIBUTING.md 30 | - add CHANGELOG.md 31 | - add LICENSE.md 32 | - add .travis.yml 33 | 34 | ### Changed 35 | - updated README.md 36 | - updated deps 37 | 38 | ## 2.0.2 - 2015-10-19 39 | 40 | ### Fixed 41 | - fix timestamps bug when trying to turn them off 42 | 43 | ## 2.0.0 44 | 45 | ### Changed 46 | - v2.0.0 call beforeCreate method before applying defaults 47 | 48 | ## 1.5.3 49 | ### Changed 50 | - allow specifying the key 51 | 52 | ## 1.5.2 53 | 54 | ### Added 55 | - add key to schema properties 56 | 57 | ## 1.5.1 58 | 59 | ### Changed 60 | - error if not found in findOne() method 61 | - run beforeCreate before validation, add validation to update method, improve validation error message 62 | 63 | ## 1.4.0 64 | 65 | ### Changed 66 | - ensure default values are created 67 | - only concat key if not already required 68 | 69 | ## 1.3.0 70 | ### Added 71 | - beforeCreate and beforeUpdate methods 72 | 73 | ### Fixed 74 | - fix required property error 75 | 76 | ## 1.2.1 77 | ### Changed 78 | - update level-simple-indexes 79 | 80 | ## 1.2.0 81 | ### Added 82 | – add findOne method 83 | 84 | ## 1.1.2 85 | ### Fixed 86 | - fix filter stream 87 | 88 | ## 1.1.1 89 | ### Changed 90 | - simplify schema setup code in constructor 91 | 92 | ## 1.1.0 93 | ### Changed 94 | – refactor to make options object more flexible 95 | 96 | ## 1.0.0 97 | ### Added 98 | - initial implementation! 99 | -------------------------------------------------------------------------------- /CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of experience, 9 | nationality, personal appearance, race, religion, or sexual identity and 10 | orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at sethvincent@gmail.com. The project team 59 | will review and investigate all complaints, and will respond in a way that it deems 60 | appropriate to the circumstances. The project team is obligated to maintain 61 | confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at [http://contributor-covenant.org/version/1/4][version] 72 | 73 | [homepage]: http://contributor-covenant.org 74 | [version]: http://contributor-covenant.org/version/1/4/ 75 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to contribute to level-model 2 | 3 | ## Prerequisites: 4 | 5 | - Familiarity with [GitHub pull requests](https://help.github.com/articles/using-pull-requests) and issues. 6 | - Knowledge of [markdown](https://help.github.com/articles/markdown-basics/) for editing `.md` documents. 7 | - Understanding of JavaScript. 8 | 9 | ## Types of contributions 10 | 11 | Here are a few of the types of contributions that we're looking for. Have an idea but it doesn't fit into this list? Make an issue for it in the issues queue of the project. 12 | 13 | ### Ideas 14 | 15 | Participate in an issues thread or start your own to have your voice heard. 16 | 17 | ### Code 18 | 19 | Fix issues or contribute new features to this or any related projects. 20 | 21 | ### Writing 22 | 23 | Contribute your expertise in an area by helping us expand the text in the application, README.md file, and other content. 24 | 25 | ### Copy editing 26 | 27 | Fix typos, clarify language, and generally improve the quality of the content. 28 | 29 | ## Steps to contributing 30 | 31 | - Fork the repository 32 | - Create a branch for your changes 33 | - Make the changes you'd like to contribute. See the "types of contributions" list above to learn more about what we're looking for 34 | - Submit a pull request 35 | 36 | ## Conduct 37 | 38 | We are committed to providing a friendly, safe, and welcoming environment for 39 | all, regardless of gender, sexual orientation, disability, ethnicity, religion, 40 | or similar personal characteristic. 41 | 42 | Be kind and courteous. There's no need to be mean or rude. 43 | Respect that people have differences of opinion and that every design or 44 | implementation choice carries a trade-off and numerous costs. There is seldom 45 | a right answer, merely an optimal answer given a set of values and 46 | circumstances. 47 | 48 | Keep unstructured critique to a minimum. If you have solid ideas you 49 | want to experiment with, make a fork and see how it works. 50 | 51 | Avoid using overtly sexual nicknames or other nicknames that 52 | might detract from a friendly, safe and welcoming environment for all. 53 | 54 | We will exclude you from interaction if you insult, demean or harass anyone. 55 | That is not welcome behavior. We interpret the term "harassment" as 56 | including the definition in the 57 | [Citizen Code of Conduct](CONDUCT.md); 58 | if you have any lack of clarity about what might be included in that concept, 59 | please read their definition. In particular, we don't tolerate behavior that 60 | excludes people in socially marginalized groups. 61 | 62 | Private harassment is also unacceptable. No matter who you are, if you feel 63 | you have been or are being harassed or made uncomfortable by a community 64 | member, please contact one of the channel ops or any of the core team 65 | immediately. Whether you're a regular contributor or a newcomer, we care about 66 | making this community a safe place for you and we've got your back. 67 | 68 | Likewise any spamming, trolling, flaming, baiting or other attention-stealing 69 | behavior is not welcome. 70 | 71 | 72 | ## Communication 73 | 74 | See the [README](README.md#contact) for detailed communication and maintainer contact information. 75 | 76 | Please follow the conduct guidelines above in all communication about this project. Language issues 77 | are often contentious and we'd like to keep discussion brief, civil and focused 78 | on what we're actually doing, not wandering off into too much imaginary stuff. 79 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | # [ISC License](https://spdx.org/licenses/ISC) 2 | 3 | Copyright (c) 2016, Seth Vincent 4 | 5 | Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # level-model 2 | 3 | A higher-level module for creating content models using [leveldb](http://npmjs.org/level). 4 | 5 | [![npm][npm-image]][npm-url] 6 | [![travis][travis-image]][travis-url] 7 | [![standard][standard-image]][standard-url] 8 | [![conduct][conduct]][conduct-url] 9 | 10 | [npm-image]: https://img.shields.io/npm/v/level-model.svg?style=flat-square 11 | [npm-url]: https://www.npmjs.com/package/level-model 12 | [travis-image]: https://img.shields.io/travis/sethvincent/level-model.svg?style=flat-square 13 | [travis-url]: https://travis-ci.org/sethvincent/level-model 14 | [standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat-square 15 | [standard-url]: http://npm.im/standard 16 | [conduct]: https://img.shields.io/badge/code%20of%20conduct-contributor%20covenant-green.svg?style=flat-square 17 | [conduct-url]: CONDUCT.md 18 | 19 | ## About 20 | 21 | level-model is a wrapper around [leveldb](https://npmjs.org/level) that provides validation and indexing. 22 | 23 | Validation is provided using the [is-my-json-valid](http://npmjs.org/is-my-json-valid) module. 24 | 25 | Indexing is achieved using the [level-simple-indexes](https://npmjs.org/level-simple-indexes) module, which in turn relies on [level-indexer](https://www.npmjs.com/package/level-indexer). 26 | 27 | ## Install 28 | 29 | ```sh 30 | npm install --save level-model 31 | ``` 32 | 33 | ## Usage 34 | 35 | ```js 36 | var level = require('level') 37 | var Model = require('level-model') 38 | var db = level('db') 39 | 40 | var posts = Model(db, { 41 | modelName: 'example', 42 | indexKeys: ['test', 'ok'], 43 | properties: { 44 | title: { type: 'string' }, 45 | content: { type: 'string' }, 46 | }, 47 | required: ['title'] 48 | }) 49 | 50 | var data = { 51 | title: 'first post!', 52 | content: 'this is some text.' 53 | } 54 | 55 | posts.create(data, function (err, post) { 56 | console.log(err, post) 57 | }) 58 | ``` 59 | 60 | ## Contributing 61 | 62 | Contributions are welcome! Please read the [contributing guidelines](CONTRIBUTING.md) first. 63 | 64 | ## Conduct 65 | 66 | It is important that this project contributes to a friendly, safe, and welcoming environment for all. Read this project's [code of conduct](CONDUCT.md) 67 | 68 | ## Changelog 69 | 70 | Read about the changes to this project in [CHANGELOG.md](CHANGELOG.md). The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). 71 | 72 | # API 73 | 74 | ### Create a model by calling the function exported from `level-model` 75 | 76 | ### `var posts = Model(db, options)` 77 | 78 | Options: 79 | 80 | ```js 81 | { 82 | modelName: 'Example', 83 | indexKeys: [], 84 | properties: {}, 85 | required: [] 86 | } 87 | ``` 88 | 89 | The options object can accept anything that [json-schema](http://json-schema.org) accepts. 90 | 91 | ### `posts.create(data, callback)` 92 | 93 | ### `posts.get(key, options, callback)` 94 | 95 | ### `posts.update(key, data, callback)` 96 | 97 | ### `posts.delete(key, callback)` 98 | 99 | ### `posts.createReadStream(options)` 100 | 101 | ### `posts.find(index, options)` 102 | 103 | ## Format data before create & update 104 | 105 | Add `beforeCreate` and `beforeUpdate` methods to `options.hooks` to format data before it is saved to the db: 106 | 107 | ``` 108 | var posts = Model(db, { 109 | modelName: 'posts', 110 | hooks: { 111 | beforeCreate: function (data) { 112 | data.slug = slugify(data.title) 113 | return data 114 | }, 115 | beforeUpdate: function (data) { 116 | return data 117 | } 118 | } 119 | }) 120 | ``` 121 | 122 | ## Events 123 | 124 | ### `example.on('create', function (model) {})` 125 | 126 | ### `example.on('update', function (model) {})` 127 | 128 | ### `example.on('delete', function () {})` 129 | 130 | ## Contact 131 | 132 | - **issues** – Please open issues in the [issues queue](https://github.com/sethvincent/level-model/issues) 133 | - **twitter** – Have a question? [@sethdvincent](https://twitter.com/sethdvincent) 134 | - **email** – Need in-depth support via paid contract? Send an email to sethvincent@gmail.com 135 | 136 | ## License 137 | 138 | [ISC](LICENSE.md) 139 | -------------------------------------------------------------------------------- /examples/README.md: -------------------------------------------------------------------------------- 1 | # Examples 2 | 3 | - [Basic usage](basic-usage.js) 4 | - [Browser example](browser.jd) 5 | -------------------------------------------------------------------------------- /examples/basic-usage.js: -------------------------------------------------------------------------------- 1 | var level = require('memdb') 2 | var Model = require('../index') 3 | 4 | var db = level() 5 | 6 | var posts = Model(db, { 7 | modelName: 'example', 8 | indexKeys: ['test', 'ok'], 9 | properties: { 10 | title: { type: 'string' }, 11 | content: { type: 'string' } 12 | }, 13 | required: ['title'] 14 | }) 15 | 16 | var data = { 17 | title: 'first post!', 18 | content: 'this is some text.' 19 | } 20 | 21 | posts.create(data, function (err, post) { 22 | console.log(err, post) 23 | }) 24 | -------------------------------------------------------------------------------- /examples/browser.js: -------------------------------------------------------------------------------- 1 | var level = require('level-browserify') 2 | var Model = require('../index') 3 | var db = level('example-db') 4 | 5 | var posts = Model(db, { 6 | modelName: 'example', 7 | indexKeys: ['test', 'ok'], 8 | properties: { 9 | title: { type: 'string' }, 10 | content: { type: 'string' } 11 | }, 12 | required: ['title'] 13 | }) 14 | 15 | var data = { 16 | title: 'first post!', 17 | content: 'this is some text.' 18 | } 19 | 20 | posts.create(data, function (err, post) { 21 | console.log(err, post) 22 | }) 23 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | var Emitter = require('component-emitter') 2 | var filter = require('filter-object-stream') 3 | var filterObject = require('filter-object') 4 | var validator = require('is-my-json-valid') 5 | var indexer = require('level-simple-indexes') 6 | var defaults = require('json-schema-defaults') 7 | var sublevel = require('subleveldown') 8 | var createLock = require('level-lock') 9 | var through = require('through2') 10 | var extend = require('extend') 11 | var cuid = require('cuid') 12 | var partial = require('ap').partial 13 | 14 | function identity (n) { return n } 15 | 16 | module.exports = LevelModel 17 | 18 | function LevelModel (db, opts) { 19 | opts.hooks = opts.hooks || {} 20 | 21 | var emitter = new Emitter() 22 | var self = {} 23 | 24 | self.on = emitter.on.bind(emitter) 25 | self.emit = emitter.emit.bind(emitter) 26 | self.modelName = opts.modelName 27 | self.db = sublevel(db, self.modelName, { valueEncoding: 'json' }) 28 | self.timestamps = opts.timestamps === undefined ? true : opts.timestamps 29 | self.timestamp = opts.timestamp || function () { return new Date(Date.now()).toISOString() } 30 | self.indexKeys = opts.indexKeys || [] 31 | self.validateOpts = opts.validateOpts 32 | self.hooks = { 33 | beforeCreate: opts.hooks.beforeCreate || identity, 34 | beforeUpdate: opts.hooks.beforeUpdate || identity 35 | } 36 | 37 | self.schema = createSchema() 38 | self.validate = validator(self.schema, opts.validateOpts) 39 | self.indexDB = sublevel(db, self.modelName + '-index') 40 | self.indexer = indexer(self.indexDB, opts.indexOpts || { 41 | properties: self.indexKeys, 42 | keys: true, 43 | values: true, 44 | map: function map (key, callback) { 45 | self.get(key, function (err, val) { 46 | callback(err, val) 47 | }) 48 | } 49 | }) 50 | 51 | self.create = partial(create, self) 52 | self.get = partial(get, self) 53 | self.put = self.save = partial(put, self) 54 | self.update = partial(update, self) 55 | self.del = self.delete = partial(del, self) 56 | self.find = self.createFindStream = partial(find, self) 57 | self.findOne = partial(findOne, self) 58 | self.createReadStream = partial(createReadStream, self) 59 | self.createFilterStream = partial(createFilterStream, self) 60 | self.lock = partial(lock, self) 61 | 62 | return self 63 | 64 | function createSchema () { 65 | var schema = filterObject(opts, ['*', '!modelName', '!timestamp', '!indexKeys', '!validateOpts', '!prefix']) 66 | 67 | schema = extend({ 68 | title: self.modelName, 69 | type: 'object' 70 | }, schema) 71 | 72 | schema.properties.key = { 73 | type: 'string' 74 | } 75 | 76 | if (self.timestamps) { 77 | schema.properties.created = { 78 | type: ['string', 'null'], 79 | default: null 80 | } 81 | schema.properties.updated = { 82 | type: ['string', 'null'], 83 | default: null 84 | } 85 | } 86 | 87 | schema.required = schema.required || [] 88 | if (schema.required.indexOf('key') < 0) { 89 | schema.required = schema.required.concat('key') 90 | } 91 | 92 | return schema 93 | } 94 | } 95 | 96 | function create (self, data, callback) { 97 | var key = data.key ? data.key : cuid() 98 | if (!data.key) data.key = key 99 | data = self.hooks.beforeCreate(data) 100 | data = extend(defaults(self.schema), data) 101 | var validated = self.validate(data) 102 | if (!validated) return callback(new Error(JSON.stringify(self.validate.errors))) 103 | 104 | if (self.timestamps) { 105 | data.created = self.timestamp() 106 | data.updated = null 107 | } 108 | 109 | var unlock = this.lock(key) 110 | if (!unlock) return callback(new Error(key + ' is locked')) 111 | 112 | self.db.get(key, function (err, model) { 113 | if (!err || model) { 114 | unlock() 115 | return callback(new Error(self.modelName + ' with key ' + key + ' already exists')) 116 | } 117 | 118 | self.db.put(key, data, function (err) { 119 | if (err) { 120 | unlock() 121 | return callback(err) 122 | } 123 | 124 | self.indexer.addIndexes(data, function () { 125 | self.emit('create', data) 126 | unlock() 127 | callback(null, data) 128 | }) 129 | }) 130 | }) 131 | } 132 | 133 | function get (self, key, options, callback) { 134 | self.db.get(key, options, callback) 135 | } 136 | 137 | function put (self, key, data, callback) { 138 | if (typeof key === 'object') { 139 | callback = data 140 | data = key 141 | key = data.key 142 | } 143 | 144 | if (!key) return create(data, callback) 145 | return update(key, data, callback) 146 | } 147 | 148 | function update (self, key, data, callback) { 149 | if (typeof key === 'object') { 150 | callback = data 151 | data = key 152 | key = data.key 153 | } 154 | 155 | var unlock = this.lock(key) 156 | if (!unlock) return callback(new Error(key + ' is locked')) 157 | 158 | self.get(key, function (err, model) { 159 | if (err || !model) { 160 | unlock() 161 | return callback(new Error(self.modelName + ' not found with key ' + key)) 162 | } 163 | 164 | model = extend(model, data) 165 | if (self.timestamps) model.updated = self.timestamp() 166 | model = self.hooks.beforeUpdate(model) 167 | 168 | var validated = self.validate(model) 169 | if (!validated) return callback(new Error(JSON.stringify(self.validate.errors))) 170 | 171 | self.indexer.updateIndexes(model, function () { 172 | self.db.put(key, model, function (err) { 173 | unlock() 174 | 175 | if (err) { 176 | return callback(err) 177 | } 178 | 179 | self.emit('update', model) 180 | callback(null, model) 181 | }) 182 | }) 183 | }) 184 | } 185 | 186 | function del (self, key, callback) { 187 | var unlock = this.lock(key) 188 | if (!unlock) return callback(new Error(key + ' is locked')) 189 | 190 | self.get(key, function (err, data) { 191 | if (err || !data) { 192 | unlock() 193 | return callback(err) 194 | } 195 | 196 | self.db.del(key, function (err) { 197 | unlock() 198 | 199 | if (err) { 200 | return callback(err) 201 | } 202 | 203 | self.indexer.removeIndexes(data, function () { 204 | self.emit('delete', data) 205 | callback(null, data) 206 | }) 207 | }) 208 | }) 209 | } 210 | 211 | function createReadStream (self, options) { 212 | return self.db.createReadStream(options) 213 | } 214 | 215 | function find (self, index, options, callback) { 216 | return self.indexer.find(index, options, callback) 217 | } 218 | 219 | function findOne (self, index, options, callback) { 220 | self.indexer.findOne(index, options, function (err, model) { 221 | if (err) return callback(err) 222 | if (!model) return callback(new Error('[NotFoundError: model not found with ' + index + ' ' + options + ']')) 223 | return callback(null, model) 224 | }) 225 | } 226 | 227 | function createFilterStream (self, options) { 228 | options = options || {} 229 | if (!options.query) options = { query: options } 230 | return createReadStream(options).pipe(through.obj(filter(options.query))) 231 | } 232 | 233 | function lock (self, key, mode) { 234 | return createLock(self.db, key, mode) 235 | } 236 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "level-model", 3 | "description": "A higher-level module for creating content models using levelup as db and is-my-json-valid for validation", 4 | "version": "3.1.1", 5 | "repository": { 6 | "url": "git://github.com/sethvincent/level-model.git" 7 | }, 8 | "main": "index.js", 9 | "scripts": { 10 | "deps": "dependency-check . && dependency-check . --unused --no-dev && ncu", 11 | "lint": "standard", 12 | "test:no-lint": "node tests/*.js | tap-spec", 13 | "test": "npm run lint && npm run test:no-lint" 14 | }, 15 | "dependencies": { 16 | "ap": "^0.2.0", 17 | "component-emitter": "^1.2.1", 18 | "cuid": "^2.1.4", 19 | "extend": "^3.0.2", 20 | "filter-object": "^3.0.0", 21 | "filter-object-stream": "0.0.1", 22 | "is-my-json-valid": "^2.19.0", 23 | "json-schema-defaults": "^0.4.0", 24 | "level-lock": "^1.0.1", 25 | "level-simple-indexes": "^2.2.0", 26 | "subleveldown": "^3.0.1", 27 | "through2": "^2.0.3" 28 | }, 29 | "devDependencies": { 30 | "inherits": "^2.0.3", 31 | "level-browserify": "^2.0.0", 32 | "memdb": "^1.3.1", 33 | "standard": "^12.0.1", 34 | "tap-spec": "^5.0.0", 35 | "tape": "^4.9.1", 36 | "through2": "^2.0.3" 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /tests/README.md: -------------------------------------------------------------------------------- 1 | # Tests 2 | 3 | Tests are run using [tape](https://npmjs.com/tape). 4 | 5 | Linting is performed using [standard](https://npmjs.com/standard) 6 | 7 | ## Running tests 8 | 9 | ```sh 10 | git clone {this repo} 11 | cd {this repo} 12 | npm install 13 | npm test 14 | ``` 15 | 16 | `npm test` runs both the linter and the tests. 17 | 18 | ### Just run the linter 19 | 20 | ```sh 21 | npm run lint 22 | ``` 23 | 24 | ### Only run the tests 25 | 26 | ```sh 27 | npm run test:no-lint 28 | ``` 29 | -------------------------------------------------------------------------------- /tests/index.js: -------------------------------------------------------------------------------- 1 | var test = require('tape') 2 | var through = require('through2') 3 | var Model = require('../') 4 | 5 | var db = require('memdb')() 6 | 7 | var example = Model(db, { 8 | modelName: 'example', 9 | properties: { 10 | key: { type: 'string' }, 11 | test: { type: 'string' }, 12 | ok: { type: 'integer' } 13 | }, 14 | indexKeys: ['test', 'ok'], 15 | required: ['test'] 16 | }) 17 | 18 | test('model exists', function (t) { 19 | t.ok(example, 'example model exists') 20 | t.ok(example.schema, 'schema of example model exists') 21 | t.end() 22 | }) 23 | 24 | test('create a model', function (t) { 25 | var data = { 26 | test: 'first instance!', 27 | ok: 1 28 | } 29 | 30 | example.create(data, function (err, instance) { 31 | t.ifError(err, 'no error') 32 | t.ok(instance, 'instance of model exists') 33 | t.ok(instance.key, 'has a key') 34 | t.end() 35 | }) 36 | }) 37 | 38 | test('get a model', function (t) { 39 | var data = { 40 | test: 'second instance!', 41 | ok: 2 42 | } 43 | 44 | example.create(data, function (err, instance) { 45 | t.notOk(err) 46 | 47 | example.get(instance.key, function (err, retrieved) { 48 | t.ifError(err, 'no error') 49 | t.ok(retrieved, 'instance of model exists') 50 | t.ok(retrieved.key, 'has a key') 51 | t.end() 52 | }) 53 | }) 54 | }) 55 | 56 | test('update a model', function (t) { 57 | var data = { 58 | test: 'third instance!', 59 | ok: 3 60 | } 61 | 62 | example.create(data, function (err, instance) { 63 | t.notOk(err) 64 | instance.ok = 2 65 | 66 | example.update(instance, function (err, updated) { 67 | t.ifError(err, 'no error') 68 | t.equals(updated.ok, 2) 69 | t.end() 70 | }) 71 | }) 72 | }) 73 | 74 | test('update a model with partial data', function (t) { 75 | var data = { 76 | test: 'another instance!', 77 | ok: 5 78 | } 79 | 80 | example.create(data, function (err, instance) { 81 | t.notOk(err) 82 | 83 | example.update(instance.key, { ok: 6 }, function (err, updated) { 84 | t.notOk(err) 85 | t.equal(updated.ok, 6) 86 | t.end() 87 | }) 88 | }) 89 | }) 90 | 91 | test('reject model creation if it doesnt fit the schema', function (t) { 92 | var data = { 93 | test: 'huh', 94 | ok: 'oops' // should be an integer 95 | } 96 | 97 | example.create(data, function (err, instance) { 98 | t.ok(err, 'error saying the object does not match the schema') 99 | t.notOk(instance, 'instance of model not created') 100 | t.end() 101 | }) 102 | }) 103 | 104 | test('list models', function (t) { 105 | var count = 0 106 | 107 | function iterator (item, enc, next) { 108 | count++ 109 | next() 110 | } 111 | 112 | function end () { 113 | t.equals(count, 4) 114 | t.end() 115 | } 116 | 117 | example.createReadStream().pipe(through.obj(iterator, end)) 118 | }) 119 | 120 | test('find models by indexed key', function (t) { 121 | t.plan(3) 122 | var count = 0 123 | 124 | function iterator (item, enc, next) { 125 | t.ok(item) 126 | count++ 127 | next() 128 | } 129 | 130 | function end () { 131 | t.equal(count, 2) 132 | } 133 | 134 | example.find('ok', 2).pipe(through.obj(iterator, end)) 135 | }) 136 | 137 | test('create, update, delete events', function (t) { 138 | var data = { 139 | test: 'fourth instance!', 140 | ok: 4 141 | } 142 | 143 | example.on('create', function (model) { 144 | t.ok(model) 145 | }) 146 | 147 | example.on('update', function (model) { 148 | t.ok('model') 149 | }) 150 | 151 | example.on('delete', function () { 152 | t.ok(true) 153 | }) 154 | 155 | example.create(data, function (err, instance) { 156 | t.notOk(err) 157 | instance.ok = 2 158 | 159 | example.update(instance, function (err, updated) { 160 | t.ifError(err, 'no error') 161 | t.equals(updated.ok, 2) 162 | t.end() 163 | }) 164 | }) 165 | }) 166 | 167 | test('delete models', function (t) { 168 | example.createReadStream() 169 | .on('data', function (data) { 170 | example.delete(data.key, function (err) { 171 | t.ifError(err, 'no error') 172 | }) 173 | }) 174 | .on('end', function () { 175 | t.end() 176 | }) 177 | }) 178 | 179 | test('create lock', function (t) { 180 | t.plan(6) 181 | example.create({ key: 'create', test: '1' }, (err, model) => { 182 | t.notOk(err) 183 | t.ok(model) 184 | }) 185 | 186 | example.create({ key: 'create', test: '2' }, (err, model) => { 187 | t.ok(err) 188 | t.notOk(model) 189 | }) 190 | 191 | example.create({ key: 'create', test: '3' }, (err, model) => { 192 | t.ok(err) 193 | t.notOk(model) 194 | }) 195 | }) 196 | 197 | test('update lock', function (t) { 198 | t.plan(10) 199 | example.create({ key: 'update', test: '1' }, (err, model) => { 200 | t.notOk(err) 201 | t.ok(model) 202 | 203 | example.update({ key: 'update', test: '4' }, (err, model) => { 204 | t.notOk(err) 205 | t.ok(model) 206 | t.ok(model.test === '4') 207 | t.ok(model.updated) 208 | }) 209 | }) 210 | 211 | example.update({ key: 'update', test: '2' }, (err, model) => { 212 | t.ok(err) 213 | t.notOk(model) 214 | }) 215 | 216 | example.update({ key: 'update', test: '3' }, (err, model) => { 217 | t.ok(err) 218 | t.notOk(model) 219 | }) 220 | }) 221 | 222 | test('delete lock', function (t) { 223 | t.plan(7) 224 | 225 | example.create({ key: 'delete', test: '1' }, (err, model) => { 226 | t.notOk(err) 227 | t.ok(model) 228 | 229 | example.delete('delete', (err) => { 230 | t.notOk(err) 231 | }) 232 | 233 | example.create({ key: 'delete', test: '2' }, (err, model) => { 234 | t.ok(err) 235 | t.notOk(model) 236 | }) 237 | 238 | example.update({ key: 'delete', test: '3' }, (err, model) => { 239 | t.ok(err) 240 | t.notOk(model) 241 | }) 242 | }) 243 | }) 244 | --------------------------------------------------------------------------------