Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Updating syntax for constistancy, restyling readme

  • Loading branch information...
commit acb0cd23f6a3e50e6f2b06ceecb18e42684ca9b4 1 parent 53d3bfc
@sorensen sorensen authored
View
3  Makefile
@@ -1,5 +1,4 @@
-
test:
@NODE_ENV=test ./node_modules/.bin/mocha \
--reporter spec \
@@ -13,4 +12,4 @@ clean:
./test/support/cleanup.js
-.PHONY: test
+.PHONY: test clean
View
66 README.md
@@ -3,7 +3,7 @@
A collection of handy plugins for mongoose
-### Contents
+## Contents
* <a href="#Troop.acl"> acess control list </a>
* <a href="#Troop.basicAuth"> authentication </a>
* <a href="#Troop.timestamp"> timestamps </a>
@@ -13,10 +13,11 @@ A collection of handy plugins for mongoose
* <a href="#Troop.pubsub"> pubsub </a> (message passing)
* <a href="#Troop.rest"> rest </a> (http or rpc controller)
-## acl <a name="Troop.acl" href="#Troop.acl"><small><sup>link</sup></small></a>
+
+# acl <a name="Troop.acl" href="#Troop.acl"><small><sup>link</sup></small></a>
Simple access control list
-#### Methods
+## Methods
### instance.addAccess(key)
@@ -30,17 +31,18 @@ Remove `key` access to a Model instance
Return or callback a boolean
-## basicAuth <a name="Troop.basicAuth" href="#Troop.basicAuth"><small><sup>link</sup></small></a>
+
+# basicAuth <a name="Troop.basicAuth" href="#Troop.basicAuth"><small><sup>link</sup></small></a>
Simple authentication plugin
-#### Options
+## Options
* `loginPath` schema path for username/login (optional, default `username`)
* `hashPath` schema path to hashed password (optional, default `hash`)
* `workFactor` bcrypt work factor (optional, default `10`)
-#### Methods
+## Methods
### instance.authenticate(password, callback)
@@ -58,7 +60,7 @@ Authenticate a user on the model level
Create a new user with given attributes
-#### Example
+## Example
```javascript
var mongoose = require('mongoose')
@@ -93,17 +95,19 @@ User.findOne({ username: 'foo'}, function(err, doc) {
})
})
````
-## timestamp <a name="Troop.timestamp" href="#Troop.timestamp"><small><sup>link</sup></small></a>
+
+
+# timestamp <a name="Troop.timestamp" href="#Troop.timestamp"><small><sup>link</sup></small></a>
Adds a `created` and `modified` property to the schema, updating the timestamps as expected.
-#### Options
+## Options
* `createdPath` schema path for created timestamp (optional, default `created`)
* `modifiedPath` schema path for modified timestamp (optional, default `modified`)
* `useVirtual` use a virtual path for created timestamp based on ObjectId (optional, default `true`)
-#### Example
+## Example
```javascript
var mongoose = require('mongoose')
@@ -113,19 +117,19 @@ var mongoose = require('mongoose')
FooSchema.plugin(troop.timestamp)
````
-#### Note
+## Note
Using the virtual `created` timestamp you will lose the ability to run queries against it,
as well as a loss in precision, as it will return a timestamp in seconds.
-## slugify <a name="Troop.slugify" href="#Troop.slugify"><small><sup>link</sup></small></a>
+# slugify <a name="Troop.slugify" href="#Troop.slugify"><small><sup>link</sup></small></a>
Turn a string based field into a url friendly slug
Converts `this is a title` to `this-is-a-title`
-#### Options
+## Options
* `target` schema path for slug destination (optional, default `slug`)
* `source` schema path for slug content (optional, default `title`)
@@ -134,7 +138,7 @@ Converts `this is a title` to `this-is-a-title`
* `invalidChar` invalid character replacement (optional, default ``)
* `override` override slug field on source path change (optional, default `false`)
-#### Example
+## Example
```javascript
var mongoose = require('mongoose')
@@ -149,26 +153,26 @@ console.log(instance.slug) // `well-hello-there`
````
-## keywords <a name="Troop.keywords" href="#Troop.keywords"><small><sup>link</sup></small></a>
+# keywords <a name="Troop.keywords" href="#Troop.keywords"><small><sup>link</sup></small></a>
Keyword extraction/creation plugin, can be used as a simple substitute of a full
search indexing package.
Turns `fooed bars` into `['foo', 'bar']`
-#### Options
+## Options
* `target` schema path for keyword destination (optional, default `keywords`)
* `source` schema path for extracting keywords
* `minLength` minimum string length to be used as a keyword (optional, default `2`)
-#### Methods
+## Methods
### instance.extractKeywords(str)
Manually calculate a keyword array with a given string
-#### Example
+## Example
```javascript
var mongoose = require('mongoose')
@@ -197,9 +201,10 @@ fooModel.find({ keywords: { $in: fooModel.extractKeywords(val) }}, function(docs
})
````
-## utils <a name="Troop.utils" href="#Troop.utils"><small><sup>link</sup></small></a>
-### merge
+# utils <a name="Troop.utils" href="#Troop.utils"><small><sup>link</sup></small></a>
+
+## merge
Merge JSON into your object more easily.
@@ -207,11 +212,11 @@ Merge JSON into your object more easily.
instance.merge({title:'A new title', description:'A new description'}).save()
````
-#### Options
+### Options
* `debug` verbose logging of current actions (optional, default `false`)
-### getdbrefs
+## getdbrefs
Get the dbrefs from a schema
@@ -224,23 +229,23 @@ instance.getdbrefs(function (refs) {
```
-### removeDefaults
+## removeDefaults
Remove all of the default values from your model instance.
`instance.removeDefaults().save()`
-#### Options
+### Options
* `debug` verbose logging of current actions (optional, default `false`)
-## publish <a name="Troop.publish" href="#Troop.publish"><small><sup>link</sup></small></a>
+# publish <a name="Troop.publish" href="#Troop.publish"><small><sup>link</sup></small></a>
Plugin to publish/subscribe from a model or instance level, also enabling a model
to automatically publish changes on `init`, `save`, and `remove` methods. Both models
and instances can be published/subscribed to.
-#### Options
+## Options
* `auto` attach middleware based on the `hook` for `init`, `save`, and `remove` methods (optional, default `false`)
* `hook` middleware method to attach auto middleware to (optional, default `post`)
@@ -250,7 +255,7 @@ and instances can be published/subscribed to.
* `publish` redis instance to be used for publishing
* `subscribe` redis instance to be used for subscribing
-#### Methods
+## Methods
### instance.publish(options)
@@ -262,6 +267,8 @@ and instances can be published/subscribed to.
### instance.unsubscribe()
+## Example
+
```javascript
var redis = require('redis')
, publish = redis.createClient()
@@ -310,9 +317,10 @@ You can also subscribe on the instance level
instance.subscribe() // channel: 'foo:4d6e5acebcd1b3fac9000007'
````
-## rest <a name="Troop.rest" href="#Troop.rest"><small><sup>link</sup></small></a>
-#### Options
+# rest <a name="Troop.rest" href="#Troop.rest"><small><sup>link</sup></small></a>
+
+## Options
* `debug` verbose logging of current actions (optional, default `false`)
View
30 lib/basicAuth.js
@@ -6,7 +6,7 @@
var bcrypt = require('bcrypt')
-function Auth (schema, options) {
+function auth (schema, options) {
options || (options = {})
var loginPath = (options.loginPath || 'username')
@@ -28,18 +28,18 @@ function Auth (schema, options) {
}
schema.add(fields)
- schema.method('authenticate', function(password, next) {
+ schema.method('authenticate', function (password, next) {
if (!password || !this[hashPath]) {
return next('missing parameters')
}
bcrypt.compare(password, this[hashPath], next)
})
- schema.method('setPassword', function(password, next) {
+ schema.method('setPassword', function (password, next) {
var self = this
- bcrypt.genSalt(workFactor, function(err, salt) {
+ bcrypt.genSalt(workFactor, function (err, salt) {
if (err) return next(err)
- bcrypt.hash(password, salt, function(err, hash) {
+ bcrypt.hash(password, salt, function (err, hash) {
if (err) return next(err)
self[hashPath] = hash
next(null)
@@ -47,14 +47,14 @@ function Auth (schema, options) {
})
})
- schema.static('authenticate', function(username, password, next) {
+ schema.static('authenticate', function (username, password, next) {
query[loginPath] = username
- this.findOne(query, function(err, model) {
+ this.findOne(query, function (err, model) {
if (err) return next(err)
if (!model) return next('model does not exist')
- model.authenticate(password, function(err, valid) {
+ model.authenticate(password, function (err, valid) {
if (err) return next(err)
if (valid) return next(null, model)
return next('invalid password', null)
@@ -62,8 +62,8 @@ function Auth (schema, options) {
})
})
- schema.static('register', function(attr, next) {
- this.create(attr, function(err, model) {
+ schema.static('register', function (attr, next) {
+ this.create(attr, function (err, model) {
if (err) {
if (/duplicate key/.test(err)) {
return next(loginPath + ' taken')
@@ -76,16 +76,16 @@ function Auth (schema, options) {
schema
.virtual('password')
- .get(function() {
+ .get(function () {
return this[hashPath]
})
- .set(function(password) {
+ .set(function (password) {
this._password = password
})
- schema.pre('save', function(next) {
+ schema.pre('save', function (next) {
if (this._password && !this[hashPath]) {
- this.setPassword(this._password, function() {
+ this.setPassword(this._password, function () {
next()
})
} else {
@@ -94,5 +94,5 @@ function Auth (schema, options) {
})
}
-module.exports = Auth
+module.exports = auth
View
8 lib/keywords/index.js
@@ -30,7 +30,7 @@ function keywords (schema, options) {
}
schema.add(fields)
- schema.pre('save', function(next) {
+ schema.pre('save', function (next) {
var words = []
for (var i = 0; i < source.length; i++) {
var add = this.extractKeywords(this[source[i]])
@@ -45,7 +45,7 @@ function keywords (schema, options) {
;['static'
, 'method'
].forEach(function (method) {
- schema[method]('extractKeywords', function(str) {
+ schema[method]('extractKeywords', function (str) {
if (!str) return []
str = str
.replace(/^\s+|\s+$/g, '')
@@ -58,8 +58,8 @@ function keywords (schema, options) {
.replace(/[^a-z0-9 -]/g, invalidChar)
.replace(new RegExp('['+invalidChar+']'+'+', 'g'), invalidChar)
.split(/\s+/)
- .filter(function(v) { return v.length >= minLength })
- .filter(function(v, i, a) { return a.lastIndexOf(v) === i })
+ .filter(function (v) { return v.length >= minLength })
+ .filter(function (v, i, a) { return a.lastIndexOf(v) === i })
if (naturalize) {
str.forEach(function (v, i, arr) {
View
33 lib/pubsub.js
@@ -14,7 +14,7 @@ function shim(obj) {
return obj
}
-module.exports = function(schema, options) {
+function pubsub (schema, options) {
options || (options = {})
var auto = options.auto || false
@@ -29,11 +29,11 @@ module.exports = function(schema, options) {
;['init'
, 'save'
, 'remove'
- ].forEach(function(method) {
- schema[hook](method, function(next) {
+ ].forEach(function (method) {
+ schema[hook](method, function (next) {
mongoose.model(this.constructor.modelName).publish(this, {
method: method
- }, function(err, count) {
+ }, function (err, count) {
next(err)
})
})
@@ -42,8 +42,8 @@ module.exports = function(schema, options) {
;['method'
, 'static'
- ].forEach(function(key) {
- schema[key]('publish', function(doc, opt, fn) {
+ ].forEach(function (key) {
+ schema[key]('publish', function (doc, opt, fn) {
if (arguments.length === 2) {
fn = opt
opt = {}
@@ -61,8 +61,8 @@ module.exports = function(schema, options) {
;['method'
, 'static'
- ].forEach(function(key) {
- schema[key]('getChannel', function() {
+ ].forEach(function (key) {
+ schema[key]('getChannel', function () {
var pre = (prefix) ? shim(prefix) + sep : ''
, post = (key === 'method') ? sep + this._id : ''
@@ -77,10 +77,10 @@ module.exports = function(schema, options) {
;['method'
, 'static'
- ].forEach(function(key) {
- schema[key]('on', function(event, fn) {
+ ].forEach(function (key) {
+ schema[key]('on', function (event, fn) {
var self = this
- sub.on(event, function(chan, resp) {
+ sub.on(event, function (chan, resp) {
if (chan === self.getChannel()) {
fn(chan, resp)
}
@@ -90,15 +90,18 @@ module.exports = function(schema, options) {
;['subscribe'
, 'unsubscribe'
- ].forEach(function(method) {
+ ].forEach(function (method) {
;['method'
, 'static'
- ].forEach(function(key) {
- schema[key](method, function(fn) {
- sub[method](this.getChannel(), function(err, result) {
+ ].forEach(function (key) {
+ schema[key](method, function (fn) {
+ sub[method](this.getChannel(), function (err, result) {
fn && fn(err, result)
})
})
})
})
}
+
+module.exports = pubsub
+
View
42 lib/rest.js
@@ -4,10 +4,10 @@
* MIT Licensed
*/
-var Mongoose = require('mongoose')
+var mongoose = require('mongoose')
-function mongooseRest (schema, options) {
- options = options || {};
+function rest (schema, options) {
+ options = options || {}
schema.static('get', _get)
schema.static('post', _update)
@@ -19,7 +19,8 @@ function mongooseRest (schema, options) {
function _controller () {
var modelName = schema.virtuals.modelName.getters[0]()
- , Model = Mongoose.model(modelName, schema)
+ , Model = mongoose.model(modelName, schema)
+
this.get = Model.get
this.post = Model.post
this.put = Model.put
@@ -29,23 +30,23 @@ function mongooseRest (schema, options) {
}
function _search (query, callback) {
- var Model = Mongoose.model(schema.virtuals.modelName.getters[0](), schema)
+ var Model = mongoose.model(schema.virtuals.modelName.getters[0](), schema)
, query = query || {}
, limit = query.limit || 10
, page = query.page || 1
+
delete query.limit
delete query.page
+
Model.find(query, [], { skip: (limit * (page-1)), limit: limit }, function (e, documents) {
if (e) {
if (options.debug) console.log('search', e)
callback(e, false)
return
- }
- else if (!documents) {
+ } else if (!documents) {
callback(false, false)
return
- }
- else {
+ } else {
callback(false, JSON.parse(JSON.stringify(documents)))
return
}
@@ -53,18 +54,16 @@ function mongooseRest (schema, options) {
}
function _get (id, callback) {
- var Model = Mongoose.model(schema.virtuals.modelName.getters[0](), schema)
+ var Model = mongoose.model(schema.virtuals.modelName.getters[0](), schema)
Model.find({_id:id}, function (e, documents) {
if (e) {
if (options.debug) console.log('get', e)
callback(e, false)
return
- }
- else if (!documents) {
+ } else if (!documents) {
callback(false, false)
return
- }
- else {
+ } else {
callback(false, JSON.parse(JSON.stringify(documents)))
return
}
@@ -73,7 +72,8 @@ function mongooseRest (schema, options) {
function _update (doc, callback) {
var modelName = schema.virtuals.modelName.getters[0]()
- , Model = Mongoose.model(modelName, schema)
+ , Model = mongoose.model(modelName, schema)
+
Model.findById(doc._id, function (e, document) {
if (e) {
if (options.debug) console.log('put', e)
@@ -91,8 +91,7 @@ function mongooseRest (schema, options) {
}
callback(false, true)
})
- }
- else {
+ } else {
document.merge(doc)
document.save()
callback(false, true)
@@ -102,7 +101,8 @@ function mongooseRest (schema, options) {
function _del (id, callback) {
var modelName = schema.virtuals.modelName.getters[0]()
- , Model = Mongoose.model(modelName, schema)
+ , Model = mongoose.model(modelName, schema)
+
Model.findById(id, function (e, doc) {
if (!document) {
callback(false, false)
@@ -113,9 +113,7 @@ function mongooseRest (schema, options) {
callback(false, true)
}
})
- }
-
+ }
}
-module.exports = mongooseRest
-
+module.exports = rest
View
4 lib/slugify.js
@@ -29,7 +29,7 @@ function slugify (schema, options) {
}
schema.add(fields)
- schema.method('slugify', function(str) {
+ schema.method('slugify', function (str) {
if (!str) return
str = str
.replace(/^\s+|\s+$/g, '')
@@ -45,7 +45,7 @@ function slugify (schema, options) {
.substr(0, maxLength)
})
- schema.pre('save', function(next) {
+ schema.pre('save', function (next) {
if (!this[target] || override) {
this[target] = this.slugify(this[source])
}
View
6 lib/timestamp.js
@@ -4,7 +4,7 @@
* MIT Licensed
*/
-module.exports = function(schema, options) {
+function timestamp (schema, options) {
options || (options = {})
var fields = {}
@@ -19,7 +19,7 @@ module.exports = function(schema, options) {
}
if (useVirtual) {
- schema.virtual(createdPath).get(function() {
+ schema.virtual(createdPath).get(function () {
return new Date(this._id.generationTime * 1000)
})
} else {
@@ -37,3 +37,5 @@ module.exports = function(schema, options) {
next()
})
}
+
+module.exports = timestamp
View
8 lib/utils.js
@@ -4,7 +4,7 @@
* MIT Licensed
*/
-function trooputils (schema, options) {
+function utils (schema, options) {
options = options || {}
schema.method('removeDefaults', function () {
@@ -24,7 +24,7 @@ function trooputils (schema, options) {
schema.method('merge', function (doc) {
var self = this
- self.schema.eachPath(function(path) {
+ self.schema.eachPath(function (path) {
if (path != '_id' && (typeof doc[path] != "undefined")) {
self.set(path, doc[path])
}
@@ -36,7 +36,7 @@ function trooputils (schema, options) {
var refs = {}
, self = this
- schema.eachPath(function(path) {
+ schema.eachPath(function (path) {
var caster = schema.paths[path].caster
, opt = schema.paths[path].options
@@ -51,5 +51,5 @@ function trooputils (schema, options) {
})
}
-module.exports = trooputils
+module.exports = utils
View
2  package.json
@@ -15,7 +15,7 @@
, "url": "git://github.com/tblobaum/mongoose-troop.git"
}
, "scripts": {
- "test": "mocha -R spec --ignore-leaks"
+ "test": "make test && make clean"
}
, "engines": {
"node": "0.x"
View
1  test/basicAuth.test.js
@@ -152,5 +152,4 @@ describe('BasicAuth', function() {
})
})
})
- // cleanup()
})
View
1  test/keywords.test.js
@@ -101,5 +101,4 @@ describe('Keywords', function() {
done()
})
})
- // cleanup()
})
View
1  test/pubsub.test.js
@@ -384,5 +384,4 @@ describe('Publish', function() {
})
})
})
- // cleanup()
})
View
1  test/slugify.test.js
@@ -110,5 +110,4 @@ describe('Slugify', function() {
done()
})
})
- // cleanup()
})
View
1  test/timestamp.test.js
@@ -71,5 +71,4 @@ describe('Timestamp', function() {
})
})
})
- // cleanup()
})
View
58 test/utils.test.js
@@ -1,7 +1,5 @@
// Dependencies
-delete require('mongoose')
-
var util = require('util')
, assert = require('assert')
, mongoose = require('mongoose')
@@ -12,40 +10,34 @@ var util = require('util')
, Schema = mongoose.Schema
, ObjectId = Schema.ObjectId
-
// Run tests
-describe('troop utility functions', function() {
+describe('Utils', function() {
describe('#default()', function() {
var BarSchema = new Schema({
- other: {type:mongoose.Schema.ObjectId, ref:'other'},
- arr: [{type:mongoose.Schema.ObjectId, ref:'arr'}]
+ other: {
+ type:mongoose.Schema.ObjectId
+ , ref:'other'
+ }
+ , arr: [{
+ type:mongoose.Schema.ObjectId
+ , ref:'arr'
+ }]
})
var OtherSchema = new Schema()
- var ArrSchema = new Schema()
+ , ArrSchema = new Schema()
trooputils(BarSchema)
- mongoose.model('bar', BarSchema)
- mongoose.model('other', OtherSchema)
- mongoose.model('arr', ArrSchema)
- var BarModel = mongoose.model('bar')
- var OtherModel = mongoose.model('other')
- var ArrModel = mongoose.model('arr')
- var othermodel = new OtherModel()
- var arrmodel = new ArrModel()
- var bar = new BarModel({arr: [arrmodel], other: othermodel })
+ var BarModel = mongoose.model('bar', BarSchema)
+ , OtherModel = mongoose.model('other', OtherSchema)
+ , ArrModel = mongoose.model('arr', ArrSchema)
+ , othermodel = new OtherModel()
+ , arrmodel = new ArrModel()
+ , bar = new BarModel({arr: [arrmodel], other: othermodel })
- it('should have a method called merge', function(done) {
+ it('should have custom methods', function(done) {
assert.ok(bar.merge)
- done()
- })
-
- it('should have a method called removeDefaults', function(done) {
assert.ok(bar.removeDefaults)
- done()
- })
-
- it('should have a method called getdbrefs', function(done) {
assert.ok(bar.getdbrefs)
done()
})
@@ -58,14 +50,18 @@ describe('troop utility functions', function() {
})
it('should still work with populate', function(done) {
- arrmodel.save(function (e) {
- othermodel.save(function (e) {
- bar.save(function (e) {
+ arrmodel.save(function (err) {
+ assert.strictEqual(err, null)
+ othermodel.save(function (err) {
+ assert.strictEqual(err, null)
+ bar.save(function (err) {
+ assert.strictEqual(err, null)
BarModel
.find()
.populate('arr')
.populate('other')
- .run(function (e, docs) {
+ .run(function (err, docs) {
+ assert.strictEqual(err, null)
docs[docs.length-1].getdbrefs(function (refs) {
assert.notStrictEqual(Object.keys(refs), ["other", "arr"])
done()
@@ -74,8 +70,6 @@ describe('troop utility functions', function() {
})
})
})
- })
-
+ })
})
-
})
Please sign in to comment.
Something went wrong with that request. Please try again.