Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactoring and bug fixes #30

Closed
wants to merge 23 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 4 additions & 1 deletion .gitignore
@@ -1 +1,4 @@
**.swp
node_modules
npm-debug.log

.DS_Store
3 changes: 0 additions & 3 deletions .gitmodules

This file was deleted.

5 changes: 5 additions & 0 deletions .travis.yml
@@ -0,0 +1,5 @@
language: node_js
node_js:
- 0.8
services:
- mongodb
19 changes: 19 additions & 0 deletions LICENSE
@@ -0,0 +1,19 @@
Copyright (c) 2013 openify.it

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
22 changes: 13 additions & 9 deletions Makefile
@@ -1,11 +1,15 @@
EXPRESSO = support/expresso/bin/expresso -I lib

TESTS = tests/*.test.js
MONGODB_URL = 'mongodb://localhost:27017/test?safe=true'
REPORTER = list

test:
@$(EXPRESSO) $(TESTS) $(TEST_FLAGS)

test-cov:
@$(MAKE) TEST_FLAGS=--cov test

.PHONY: test test-cov
@NODE_ENV=test \
MONGODB_URL=$(MONGODB_URL) \
./node_modules/.bin/mocha \
--recursive \
--reporter $(REPORTER) \
--timeout 10000 \
--bail \
tests/*.test.coffee \
--require coffee-script

.PHONY: test
46 changes: 9 additions & 37 deletions README.md
@@ -1,16 +1,13 @@
mongoose-types - Useful types and type plugins for Mongoose
mongoose-types - Useful types for Mongoose
==============

[![Build Status](https://travis-ci.org/OpenifyIt/mongoose-types.png?branch=master)](https://travis-ci.org/OpenifyIt/mongoose-types)

### Types include:

- Email
- Url

### Plugins include:

- useTimestamps
Adds `createdAt` and `updatedAt` date attributes that get auto-assigned to the most recent create/update timestamp.

### Installation
npm install mongoose-types

Expand Down Expand Up @@ -53,45 +50,16 @@ Once you are setup, you can begin to use the new types.
, referer: Url
});

### Using the plugins

#### The `useTimestamps` plugin

var mongoose = require("mongoose");
var db = mongoose.createConnection("mongodb://localhost/sampledb");
var mongooseTypes = require("mongoose-types")
, useTimestamps = mongooseTypes.useTimestamps;
var UserSchema = new Schema({
username: String
});
UserSchema.plugin(useTimestamps);
mongoose.model('User', UserSchema);
var User = db.model('User', UserSchema);

var user = new User({username: 'Prince'});
user.save(function (err) {
console.log(user.createdAt); // Should be approximately now
console.log(user.createdAt === user.updatedAt); // true

// Wait 1 second and then update the user
setTimeout( function () {
user.username = 'Symbol';
user.save( function (err) {
console.log(user.updatedAt); // Should be approximately createdAt + 1 second
console.log(user.createdAt < user.updatedAt); // true
});
}, 1000);
});

## Tests

To run tests:
To run tests (you must have a running instance of mongodb):

make test

### Contributors

- [Brian Noguchi](https://github.com/bnoguchi)
- [Openify.it](https://github.com/Openify.it)

### License

Expand All @@ -101,3 +69,7 @@ MIT License
### Author

Brian Noguchi

### Rewritten by

Openify.it
1 change: 0 additions & 1 deletion index.js

This file was deleted.

17 changes: 0 additions & 17 deletions lib/index.js

This file was deleted.

10 changes: 10 additions & 0 deletions lib/mongoose_types.coffee
@@ -0,0 +1,10 @@
exports.loadTypes = () ->
mongoose = arguments[0]
types = Array.prototype.slice.call arguments, 1
if types.length
types.forEach (type) ->
require("./types/#{type}").loadType(mongoose)
else
files = require("fs").readdirSync("#{__dirname}/types")
files.forEach (filename) ->
require("./types/" + filename).loadType(mongoose)
38 changes: 0 additions & 38 deletions lib/plugins/useTimestamps.js

This file was deleted.

20 changes: 20 additions & 0 deletions lib/types/email.coffee
@@ -0,0 +1,20 @@
mongoose = require 'mongoose'

class Email extends mongoose.SchemaTypes.String
constructor: (path, options) ->
super(path, options)
@validate @validateEmail.bind(@, options.require), 'email is invalid'

cast: (email) ->
email.toLowerCase()

validateEmail: (required, email) ->
if required or email
return /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/.test email
else
return true


module.exports.loadType = (mongoose) ->
mongoose.SchemaTypes.Email = Email
mongoose.Types.Email = String
19 changes: 0 additions & 19 deletions lib/types/email.js

This file was deleted.

18 changes: 18 additions & 0 deletions lib/types/url.coffee
@@ -0,0 +1,18 @@
UrlUtility = require '../url_utility'
mongoose = require 'mongoose'

class Url extends mongoose.SchemaTypes.String
constructor: (path, options) ->
super path, options
@urlUtility = new UrlUtility()
@validate @urlUtility.validate.bind(@urlUtility, options.require), 'url is invalid'

cast: (val) =>
if val and val isnt ''
return @urlUtility.normalize val
else
return ''

module.exports.loadType = (mongoose) ->
mongoose.SchemaTypes.Url = Url
mongoose.Types.Url = String
60 changes: 0 additions & 60 deletions lib/types/url.js

This file was deleted.

51 changes: 51 additions & 0 deletions lib/url_utility.coffee
@@ -0,0 +1,51 @@
url = require 'url'

class UrlUtility
validate: (required, url) =>
if required or url
urlRegexp = /^[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/i
return urlRegexp.test url
else
return true

normalize: (uri) =>
parsedUrl = url.parse uri, true
urlstr = if parsedUrl.protocol then parsedUrl.protocol.toLowerCase() else 'http:'
urlstr += '//'
urlstr += if parsedUrl.hostname then parsedUrl.hostname.toLowerCase().replace(/^www\./, '') else ''
urlstr += if parsedUrl.pathname then parsedUrl.pathname.replace(/\/\.{1,2}\//g, '/').replace(/\/{2,}/, '/')
urlstr += if @_objectIsEmpty(parsedUrl.query) then '' else '?' + @_reorderQuery(parsedUrl.query)
urlstr += if parsedUrl.hash then parsedUrl else ''
return urlstr

_reorderQuery: (query) =>
orderedKeys = []
name = ''
i = -1
len = -1
key = ''
querystr = []
for name of query
i = 0
len = orderedKeys.length

while i < len
break if orderedKeys[i] >= name
i++
orderedKeys.splice i, 0, name
i = 0
len = orderedKeys.length

while i < len
key = orderedKeys[i]
querystr.push key + '=' + query[key]
i++
return querystr.join '&'

_objectIsEmpty: (obj) ->
for key of obj
if Object.prototype.hasOwnProperty.call(obj, key)
return false
return true

module.exports = UrlUtility
2 changes: 2 additions & 0 deletions main.js
@@ -0,0 +1,2 @@
require('coffee-script');
module.exports = require("./lib/mongoose_types");