Skip to content

Commit

Permalink
Alpha
Browse files Browse the repository at this point in the history
  • Loading branch information
Alexandru Vladutu committed Jun 14, 2012
0 parents commit 0bf0733
Show file tree
Hide file tree
Showing 1,353 changed files with 225,579 additions and 0 deletions.
135 changes: 135 additions & 0 deletions Jakefile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
/**
* Jake is a JavaScript build tool for Node.js
* http://howtonode.org/intro-to-jake
* https://github.com/mde/jake
*
* To find out the available tasks for Jake run:
* jake -T
*
* To run a task do:
* jake db:reset
*
* To run a task with params do:
* jake db:populate[20]
*/
var mongoose = require('mongoose'),
colors = require('colors'),
faker = require('faker'),
log = console.log,
ENV = process.env.NODE_ENV || 'development';
JK = {};

JK.abortIfProduction = function() {
if (ENV === 'production') {
throw new Error('Are you out of your mind? Drop the production db?!');
}
}

// desc('Initialize stuff.');
task('init', [], function() {
JK.utils = JK.utils || require('./lib/utils');
// make sure the configs are loaded only once
if (!JK.config) {
JK.utils.loadConfig(__dirname + '/config', function(config) {
JK.config = config;
complete();
});
}
}, { async: true });

namespace('db', function() {

// desc('Connect to database');
task('connect', ['init'], function() {
var _self = this;

log('- db:connect'.yellow);
if (!JK.mongoose) {
JK.mongoose = JK.utils.connectToDatabase(mongoose, JK.config.db[ENV].main, function(err) {
if (err) { throw err; }

log(' connected to database'.green);
complete.call(_self);
});
} else {
complete();
}
}, { async: true });

// desc('Load models');
task('loadModels', [], function(params) {
log('- db:loadModels'.yellow);
if (!JK.models) {
JK.models = {};
['client'].forEach(function (elem, index) {
JK.models[elem] = require('./app/models/' + elem)(JK.mongoose);
});
}
log(' loaded models'.green);
});

desc('Remove all items from the database.');
task('empty', ['db:connect', 'db:loadModels'], function(params) {
var Client, query;

log('- db:empty'.yellow);

Client = JK.models.client;
query = Client.find().remove(function(err) {
if (err) { throw err; }

log(' emptied db'.green);
complete();
});
}, { async: true });

// Run jake db:populate OR jake db:populate[<numberOfItems>]
desc('Populate db with phony data.');
task('populate', ['db:empty'], function(howMany) {
var Client;

log('- db:populate'.yellow);

Client = JK.models.client;
howMany = howMany || 50;

(function populate(nr) {
var client, _now, _pastDate;

if (nr === 0) {
log((' populated ' + ENV + ' database').green);
process.exit(0);
}

_now = JK.utils.getRandDate();
// client has to be older than 18 years -> 18 * 12 = 216
_pastDate = JK.utils.getRandDate('past', _now, {
timeUnit : 'months',
timeVal : (18 + parseInt(nr, 10)) * 12,
});

client = new Client({
name : faker.Name.findName(),
email : faker.Internet.email(),
born : _pastDate,
company : faker.Company.companyName()
});

client.save(function(err) {
if (err) {
// Faker sometimes generates bad emails
if (err.errors && err.errors.email) {
nr++;
} else {
throw err;
}
}

nr--;
process.nextTick(function() {
populate(nr);
});
});
}(howMany));
});
});
86 changes: 86 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
## Quick start

- Make sure Node.js and NPM should be installed (I prefer to do it using NVM). This project was developed on Node 0.6.x.
- Install dependencies with NPM: "npm install ." in the project root
- Configure the ports for the application (for multiple environments: dev, test, production) and also the settings for the MongoDB connection (you can either host MongoDB locally or try a free hosting provider such as MongoLab). The config data is in /config
- Run 'npm start' or 'NODE_ENV=production node app.js' to start the server

## App structure

The application has a structure similar to Rails:

- the model and controller folders are within '/app'
- the configuration stored into json files in '/config'.
- public directory for the server: '/public'
- logs are kept into their own '/logs' folder, having one file per environment
- '/lib' is where application specific files reside
- all backend test files are inside '/test', structured into: unit tests ('/unit'), functional tests ('/functional') and the fixtures
- the Jakefile: similar to make or rake, can run tasks

Frontend:

- the '/js' folder is where the 'magic' happens: '/main.js' is the starting point (stores RequireJS configuration), which calls '/app' (that deals with the initialization for the application), the rest of the foldes are self-explanatory
- '/css' and '/img' stores the static stylesheets and images needed
- '/test' has the logic for the test runner (with Mocha), and specs

## Dev gotchas with Jake

You can empty the database by running 'jake db:empty' and populate it with data by running 'jake db:populate[20]' for ex (that will empty db and insert 20 new records).

## Testing

I've chosen Mocha for all tests in this project. To run unit tests & function tests use 'npm test' in the application root (make sure things are setup properly -> the app can connect to MongoDB, can bind to the specified port).
If you're testing on Windows, install Mocha globally: 'npm install mocha@1.1.0 -g' and run 'mocha --ui bdd --recursive --reporter spec --timeout 10000 --slow 300' instead.
For client side tests, open 'http://server:port/test'.

## Small JS styleguide for the project

- 2 spaces for indentation
- Semicolons should be used
- Line length should be 80 (that's a soft limit, 82-83 for example is ok provided these are just a few exceptions)
- Braces go on the same line as the statement
- Vars should always be declared at the top
- Variables and properties should use lower camel case capitalization

## Browser compatibility

I haven't had time to properly test the app, but it should work fine in modern browsers.

## TODO / Improvements:

Client-side:

- Compress & concatenate JS & CSS (each into single file, using build script)
- Add popups after deleting / saving client
- Put each template into an element with an id, concatenate them (using a build script) into a single HTML file which is fetched at startup and export the object containing them (this way there's only 1 request instead of <number of templates> requests, they are kept out of the main html file and each into their own files during development).
- More tests

Server-side:

- Bug in IE => should send Dates using miliseconds instead of the toString() stuff
- Split contents of utils.js into multiple files (more specific categories)
- Implement content-negotiation (return 406 Not Acceptable where needed)
[this is present by default in Express 3.x, upgrade when it is stable enough]
- Implement authentication and check authorization when modifying resources
- Implement ETags properly for the /clients and /clients/:id GET routes

## Useful links that helped me while developing this app

- http://backbonetutorials.com
- http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
- https://github.com/jrburke/requirejs/wiki/Upgrading-to-RequireJS-2.0
- http://addyosmani.github.com/backbone-fundamentals/
- http://addyosmani.github.com/backbone-aura/
- http://coenraets.org/directory/

## License

(The MIT License)

Copyright (c) 2012 Alexandru Vladutu <alexandru.vladutu@gmail.com>

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.
79 changes: 79 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
var connect = require('connect'),
express = require('express'),
connectTimeout = require('connect-timeout'),
mongoose = require('mongoose'),
utils = require('./lib/utils'),
EventEmitter = require('events').EventEmitter,
AppEmitter = new EventEmitter(),
app = express.createServer(),
ENV = process.env.NODE_ENV || 'development',
log = console.log,
dbPath;

utils.loadConfig(__dirname + '/config', function(config) {
app.use(function(req, res, next) {
res.removeHeader("X-Powered-By");
next();
});
app.configure(function() {
utils.ifEnv('production', function() {
// enable gzip compression
app.use(connect.compress({
level: 9,
memLevel: 9
}));
});
app.use(express.favicon());
utils.ifEnv('production', function() {
app.use(express.staticCache());
});
app.use(express['static'](__dirname + '/public'));
app.use(express.bodyParser());
app.use(express.methodOverride());
utils.ifEnv('production', function() {
app.use(connectTimeout({
time: parseInt(config[ENV].REQ_TIMEOUT, 10)
}));
});
});

mongoose = utils.connectToDatabase(mongoose, config.db[ENV].main);

// register models
require('./app/models/client')(mongoose);

// register controllers
['clients', 'errors'].forEach(function(controller) {
require('./app/controllers/' + controller + '_controller')(app, mongoose, config);
});

app.on('error', function (e) {
if (e.code == 'EADDRINUSE') {
log('Address in use, retrying...');
setTimeout(function () {
app.close();
app.listen(config[ENV].PORT, function() {
app.serverUp = true;
});
}, 1000);
}
});

if (!module.parent) {
app.listen(config[ENV].PORT, function() {
app.serverUp = true;
});
log('Express server listening on port %d, environment: %s', app.address().port, app.settings.env);
}

AppEmitter.on('checkApp', function() {
AppEmitter.emit('getApp', app);
});

});

/**
* export AppEmitter for external services so that the callback can execute
* when the app has finished loading the configuration
*/
module.exports = AppEmitter;
Loading

0 comments on commit 0bf0733

Please sign in to comment.