Skip to content

Commit

Permalink
*added file-persistence
Browse files Browse the repository at this point in the history
  • Loading branch information
jspears committed Apr 9, 2012
1 parent 476b9a4 commit feffffa
Show file tree
Hide file tree
Showing 10 changed files with 145 additions and 98 deletions.
59 changes: 23 additions & 36 deletions examples/login-example/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@

var express = require('express')
, jqtpl = require('jqtpl')
, fs = require('fs')
, bobamo = require('bobamo')
, passport = require('./lib/passport')
, mongoose = require('mongoose')
, User = require('bobamo/examples/model/user')
, Employee = require('bobamo/examples/model/employee')
;

var app = module.exports = express.createServer();
Expand All @@ -27,29 +28,22 @@ app.configure(function () {
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
// app.use(bobamo.express());
app.dynamicHelpers({
isAuthenicated:function (req, res) {
return req.isAuthenticated();
}
});

loadDir('../model');

});
app.post('/', function (req, res, next) {
next();
}, passport.authenticate('local', { failureRedirect:'/check' }), function (req, res, next) {
req.method = 'GET';
req.url = '/api/user/'+req.user._id;
req.url = '/rest/user/' + req.user._id;
next();
}
);

app.get('/check', function (req, res, next) {
if (req.isAuthenticated && req.isAuthenticated()) {
req.method = 'GET';
req.url = '/api/user/'+req.user._id;
req.url = '/rest/user/' + req.user._id;
next();
} else {
res.send({status:1, message:'Not Authenticated'})
Expand All @@ -60,43 +54,36 @@ app.get('/logout', function (req, res) {
req.logOut();
res.redirect('/');
});
app.all(/\/api\/*/, function (req, res, next) {
app.all(/\/rest\/*/i, function (req, res, next) {
if (req.isAuthenticated && req.isAuthenticated())
return next();
res.redirect('/check');
});

app.configure('development', function () {
app.use(bobamo.express({mongoose:mongoose}, express))
mongoose.connection.on('open', function () {
User.find({username:'admin'}, function (err, obj) {
if (err) {
console.log('error', err);
return;
}
if (!obj) {
new User({
username:'admin',
password:'admin',
twitter:'@nowhere'
}).save(function (err, obj) {
console.log('added user', err, obj);
});
}
});
});

mongoose.connect('mongodb://localhost/bobamo_development');
app.use(express.errorHandler({ dumpExceptions:true, showStack:true }));
});

app.configure('production', function () {
app.use(bobamo.express({mongoose:mongoose}, express))
mongoose.connect('mongodb://localhost/bobamo');
app.use(express.errorHandler());
});


app.listen(3000);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
function loadDir(dir) {
var loaded = {};
var jsRe = /\.js$/;
fs.readdirSync(dir).forEach(function (file) {
var fPath = [dir, file].join('/');
var stat = fs.statSync(fPath);
if (stat.isFile() && jsRe.test(file)) {
file = file.replace(jsRe, '');
fPath = fPath.replace(jsRe, '');
console.log('loading ', fPath, 'as', file);
try {
loaded[file] = require(fPath);
} catch (e) {
console.error('Error loading [' + fPath + '] ', e);
}
}
});
return loaded;
}
2 changes: 1 addition & 1 deletion examples/login-example/public/js/views/contact/list.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
define(['Backbone', 'jquery', 'Underscore', 'text!tpl/contact.html'], function (Backbone, $, _, contactTmpl) {
define(['Backbone', 'jquery', 'underscore', 'text!tpl/contact.html'], function (Backbone, $, _, contactTmpl) {

var ContactView = Backbone.View.extend({
el:'#content',
Expand Down
2 changes: 1 addition & 1 deletion examples/login-example/public/js/views/employee/details.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
define(['Backbone', 'jquery', 'Underscore', 'collections/employee', 'views/employee/list', 'text!tpl/employee-details.html', 'text!tpl/employee-full.html'], function (Backbone, $, _, collection, EmployeeListView, detailsTmpl, fullTmpl) {
define(['Backbone', 'jquery', 'underscore', 'collections/employee', 'views/employee/list', 'text!tpl/employee-details.html', 'text!tpl/employee-full.html'], function (Backbone, $, _, collection, EmployeeListView, detailsTmpl, fullTmpl) {
var EmployeeFullView = Backbone.View.extend({

tagName:"div", // Not required since 'div' is the default if no el or tagName specified
Expand Down
2 changes: 1 addition & 1 deletion examples/login-example/public/js/views/employee/list.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
define(['Backbone', 'jquery', 'Underscore', 'collections/employee', 'text!tpl/employee-list-item.html'], function (Backbone, $, _, collection, employeeListItem) {
define(['Backbone', 'jquery', 'underscore', 'collections/employee', 'text!tpl/employee-list-item.html'], function (Backbone, $, _, collection, employeeListItem) {
var EmployeeListView = Backbone.View.extend({
// el:'#content',
tagName:'ul',
Expand Down
2 changes: 1 addition & 1 deletion examples/login-example/public/js/views/home/list.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
define(['Backbone', 'jquery', 'Underscore', 'text!tpl/home.html'], function (Backbone, $, _, homeTmpl) {
define(['Backbone', 'jquery', 'underscore', 'text!tpl/home.html'], function (Backbone, $, _, homeTmpl) {

var HomeView = Backbone.View.extend({
el:'#content',
Expand Down
33 changes: 33 additions & 0 deletions lib/file-persistence.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
var fs = require('fs'), path = require('path');


var FilePersistence = function (file) {

this.filename = file || path.join(process.cwd, 'conf', 'bobamo.json');

}
module.exports = FilePersistence;

FilePersistence.prototype.save = function (key, data, callback) {
var conf = this.read(this.filename);
if (conf) {
fs.renameSync(this.filename, this.filename + '.' + Date.now());
} else {
conf = {};
var dir = path.dirname(this.filename);
if (!path.existsSync(dir)) {
fs.mkdirSync(dir);
}
}
(conf.plugins || (conf.plugins = {}))[key] = data;
fs.writeFile(this.filename, JSON.stringify(conf), 'utf-8', callback);
}

FilePersistence.prototype.read = function (filename) {
filename = filename+'';
console.log('reading ', filename);
if (path.existsSync(filename)) {
var content = fs.readFileSync(filename);
return JSON.parse(content);
}
}
5 changes: 5 additions & 0 deletions lib/plugin-api.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,11 @@ Plugin.prototype.__defineGetter__('pluginUrl', function () {
Plugin.prototype.appModel = function () {

}

Plugin.prototype.save = function onPluginSave(conf, callback) {
this.pluginManager.save(this, conf, callback);
}

Plugin.prototype.defaultEngine = 'jqtpl';
/**
* Adds filters before routes, in gives a shot
Expand Down
33 changes: 24 additions & 9 deletions lib/plugin-manager.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,25 @@
var path = require('path'), _u = require('underscore'), DisplayModel = require('./display-model'), inflection = require('./inflection');
var path = require('path'), _u = require('underscore'), DisplayModel = require('./display-model'), PluginApi = require('./plugin-api'), FilePersistence = require('./file-persistence');
/**
*
* @param options // options to use
* @param express // an app instance.
*/
var PluginManager = function (options, express) {
this.options = _u.extend({}, options);
this.persist = options.persist || new FilePersistence();
this.plugins = this.loadPlugins(this.options, express);
this.appModel = new DisplayModel(this.options);
this.loadAppModels();
this.loadFilters();
this.loadRoutes();
}
PluginManager.prototype.save = function(plugin, data, callback){
this.persist.save(plugin.name, data, callback);
}
/**
* Default plugins to load.
*/
PluginManager.prototype.defaultPlugins = ['less', 'modeleditor', 'appeditor','generator', 'rest', 'mongoose', 'static', 'package'];
PluginManager.prototype.defaultPlugins = ['less', 'modeleditor', 'appeditor', 'generator', 'rest', 'mongoose', 'static', 'package'];
/**
*
*/
Expand Down Expand Up @@ -88,12 +92,22 @@ PluginManager.prototype.loadPlugins = function (options, express) {
var loaded = {};
var ret = [];
_u.unique(plugins).forEach(function (pdir) {
if (loaded[pdir]) {
console.warn('plugin already loaded [' + pdir + ']');
return;
}
_u.unique(dirs).forEach(function (dir) {
if (!path.existsSync(dir)){
if (_u.isFunction(pdir)) {

var plugin = (pdir instanceof PluginApi) ? new pdir(options, express, pdir, path.join(dir, pdir), this) :pdir(options, express, pdir, path.join(dir, pdir), this) ;

ret.push(plugin);
loaded[plugin.name || pdir] = true;

} else {

if (loaded[pdir]) {
console.warn('plugin already loaded [' + pdir + ']');
return;
}

_u.unique(dirs).forEach(function (dir) {
if (!path.existsSync(dir)) {
return;
}
var fpath = path.join(dir, pdir, pdir + '.js');
Expand All @@ -108,7 +122,8 @@ PluginManager.prototype.loadPlugins = function (options, express) {
console.warn('error loading plugin [' + fpath + ']', e);
}
}
}, this);
}, this);
}
}, this);

_u(plugins).difference(Object.keys(loaded)).forEach(function (v, k) {
Expand Down
91 changes: 47 additions & 44 deletions plugins/modeleditor/edit-display-model.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
var _u = require('underscore');
var _u = require('underscore'), util = require('../../lib/util');
var EditApp = function (App, options) {
this.app = App;
this.options = _u.extend({}, options);
Expand Down Expand Up @@ -56,10 +56,8 @@ var EditModel = function (k, Model, options) {
}
];
_u(this.model.paths).each(function (v, k) {
if (k.indexOf('.') > -1)
return;
fieldsets.push({
legend:'Property ' + k,
legend:'Property [' + k + ']',
fields:['paths.' + k + '.title', 'paths.' + k + '.help', 'paths.' + k + '.views', 'paths.' + k + '.type', 'paths.' + k + '.dataType', 'paths.' + k + '.required']
})
});
Expand Down Expand Up @@ -124,53 +122,58 @@ EditModel.prototype.schemaFor = function () {
_u(this.model.paths).each(function (v, k) {
// if (k.indexOf('.') > -1)
// return;

console.log('k', k, 'v', v);
obj[k] = {type:'Object'};
obj[k].subSchema = {
title:{
title:'Title',
help:'The title of the path',
type:'Text'
},
help:{
title:'Help',
help:'The help text to show next to item',
type:'Text'
},
views:{
title:'View',
help:'The views this property can be seen in.',
dataType:'Select',
options:[
{label:'List View', val:'list_view'},
{label:'Edit View', val:'edit_view'},
{label:'None', val:'no_view'}
]
},
type:{
title:'Editor',
help:'The editor to use with field',
type:'Select',
options:editors
},
dataType:{
title:'Data Type',
help:'The Data Type of the field for html5 enabled browsers',
options:'text,tel,time,url,range,number,week,month,year,date,datetime,datetime-local,email,color'.split(','),
type:'Select'
},
required:{
title:'Required',
help:'Is this a required field.',
type:'Checkbox'
}
}
obj[k].subSchema =createSubSchema(this.editors, k, v);

}, this);

return this._schema;

}
function createSubSchema(editors, k, v) {
var obj = {
title:{
title:'Title',
help:'The title of the path',
type:'Text'
},
help:{
title:'Help',
help:'The help text to show next to item',
type:'Text'
},
views:{
title:'View',
help:'The views this property can be seen in.',
dataType:'Select',
options:[
{label:'List View', val:'list_view'},
{label:'Edit View', val:'edit_view'},
{label:'None', val:'no_view'}
]
},
type:{
title:'Editor',
help:'The editor to use with field',
type:'Select',
options:editors
},
dataType:{
title:'Data Type',
help:'The Data Type of the field for html5 enabled browsers',
options:'text,tel,time,url,range,number,week,month,year,date,datetime,datetime-local,email,color'.split(','),
type:'Select'
},
required:{
title:'Required',
help:'Is this a required field.',
type:'Checkbox'
}
}

return obj;
}
var EditField = function (Field) {

}
Expand Down
14 changes: 9 additions & 5 deletions plugins/modeleditor/modeleditor.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ EditPlugin.prototype.routes = function () {
})
}.bind(this));

this.app.put(base + '/admin/model/:id', function (req, res) {
this.app.put(base + '/admin/model/:id', function (req, res, next) {

var obj = _u.extend({}, req.body);
_u.each(obj, function (v, k) {
Expand All @@ -91,10 +91,14 @@ EditPlugin.prototype.routes = function () {
}
});
console.log('edited ', obj);
res.send({
status:0,
payload:{_id:req.params.id}
})
this.save(obj, function(err, data){
if (err)
return next(err);
res.send({
status:0,
payload:data
})
});
}.bind(this));
Plugin.prototype.routes.apply(this, arguments);

Expand Down

0 comments on commit feffffa

Please sign in to comment.