diff --git a/Gruntfile.js b/Gruntfile.js index 53cd298..8b61c14 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -1,5 +1,7 @@ /* jshint camelcase:false */ var fs = require('fs'); +var express = require('express'); +var cmsRouter = require('./routes/cms-router.js'); 'use strict'; // # Globbing @@ -11,13 +13,18 @@ var fs = require('fs'); * @TODO - Externalize configuration for server and proxy, mongodb */ +var startNodeServer = function(options, app){ + var app = express(); + var config = JSON.parse(fs.readFileSync('./config/config.json')); + var server = new cmsRouter.mount(config, app); +}; + var serverEndpoint = 'http://localhost:8181'; var proxyConfig = { proxy: { forward: { '/socket.io/*': serverEndpoint, '/socket.io': serverEndpoint, - '/cms-content': serverEndpoint, '/api': serverEndpoint } } @@ -60,7 +67,7 @@ module.exports = function (grunt) { tasks: ['newer:copy:styles', 'autoprefixer'] }, scripts: { - files: ['<%= yeoman.app %>/scripts/{,**/}*.js'], + files: ['<%= yeoman.app %>/scripts/{,** /}*.js'], tasks: ['jshint:app'] }, gruntfile: { @@ -96,12 +103,7 @@ module.exports = function (grunt) { open: true, base: ['.tmp', '<%= yeoman.app %>'], middleware: function (connect, options) { - var express = require('express'); - var fs = require('fs'); - var cmsRouter = require('./routes/cms-router.js'); - var app = express(); - var config = JSON.parse(fs.readFileSync('./config/config.json')); - var server = new cmsRouter.mount(config, app); + startNodeServer(options, connect); return [ require('json-proxy').initialize(proxyConfig), mountFolder(connect, '.grunt'), diff --git a/app/index.html b/app/index.html index fbc37f0..c5f0f8b 100755 --- a/app/index.html +++ b/app/index.html @@ -118,7 +118,8 @@ - + + @@ -138,19 +139,22 @@ - - - - - - + + + + + + + + - - - - - + + + + + + diff --git a/app/scripts/app.js b/app/scripts/app.js index 63a8618..a8cce99 100644 --- a/app/scripts/app.js +++ b/app/scripts/app.js @@ -10,86 +10,83 @@ * Resize textarea automatically to the size of its text content. * * @example - - - -
{{text}}
-
-
+ + + +
{{text}}
+
+
*/ -var app; - Parse.initialize('fYHs4Flnj7vgVHm9vaFiFTSKt5Mj2Bxf9e93mTOB', 'QPFGBNHs0QQHFS54atV71oKppd3gTgaFfQIHP2VW'); - -app = angular.module('angularCmsApp', ['ngCookies', 'ngResource', 'ngSanitize', 'ngRoute', 'ngAnimate', 'mgcrea.ngStrap', 'fg']).config(function($routeProvider) { - var routeResolver; - routeResolver = { - delay: function($q, $timeout) { - var delay; - delay = $q.defer(); - $timeout(delay.resolve, 1000); - return delay.promise; - } - }; - return $routeProvider.when('/', { - templateUrl: 'views/main.html', - controller: 'MainCtrl' - }).when('/docs', { - templateUrl: 'views/docs.html', - controller: 'DocsCtrl' - }).when('/admin', { - templateUrl: 'views/admin.html', - controller: 'AdminCtrl' - }).when('/plugins', { - templateUrl: 'views/plugins.html', - controller: 'PluginsCtrl' - }).when('/themes', { - templateUrl: 'views/themes.html', - controller: 'ThemesCtrl' - }).when('/widgets', { - templateUrl: 'views/widgets.html', - controller: 'WidgetsCtrl' - }).when('/media', { - templateUrl: 'views/media.html', - controller: 'MediaCtrl' - }).when('/settings', { - templateUrl: 'views/settings.html', - controller: 'SettingsCtrl' - }).when('/users', { - templateUrl: 'views/users.html', - controller: 'UsersCtrl' - }).when('/login', { - templateUrl: 'views/login.html', - controller: 'LoginCtrl' - }).when('/register', { - templateUrl: 'views/register.html', - controller: 'RegisterCtrl' - }).when('/dashboard', { - templateUrl: 'views/dashboard.html', - controller: 'DashboardCtrl' - }).when('/profile', { - templateUrl: 'views/profile.html', - controller: 'ProfileCtrl' - }).when('/pages', { - templateUrl: 'views/pages.html', - controller: 'PagesCtrl', - resolve: { - pages: function(DataService) { - return DataService.fetch('pages').then(function(res) { - return res.data; - }); - } - } - }).when('/help', { - templateUrl: 'views/help.html', - controller: 'HelpCtrl' - }).when('/forgot-password', { - templateUrl: 'views/forgot-password.html', - controller: 'ForgotPasswordCtrl' - }).when('/register', { - templateUrl: 'views/register.html', - controller: 'RegisterCtrl' - }).otherwise({ - redirectTo: '/' - }); +var app = angular.module('angularCmsApp', ['ngCookies', 'ngResource', 'ngSanitize', 'ngRoute', 'ngAnimate', 'mgcrea.ngStrap', 'fg']).config(function ($routeProvider) { + var routeResolver; + routeResolver = { + delay: function ($q, $timeout) { + var delay; + delay = $q.defer(); + $timeout(delay.resolve, 1000); + delay.promise; + } + }; + $routeProvider.when('/', { + templateUrl: 'views/main.html', + controller: 'MainCtrl' + }).when('/docs', { + templateUrl: 'views/docs.html', + controller: 'DocsCtrl' + }).when('/admin', { + templateUrl: 'views/admin.html', + controller: 'AdminCtrl' + }).when('/plugins', { + templateUrl: 'views/plugins.html', + controller: 'PluginsCtrl' + }).when('/themes', { + templateUrl: 'views/themes.html', + controller: 'ThemesCtrl' + }).when('/widgets', { + templateUrl: 'views/widgets.html', + controller: 'WidgetsCtrl' + }).when('/media', { + templateUrl: 'views/media.html', + controller: 'MediaCtrl' + }).when('/settings', { + templateUrl: 'views/settings.html', + controller: 'SettingsCtrl' + }).when('/users', { + templateUrl: 'views/users.html', + controller: 'UsersCtrl' + }).when('/login', { + templateUrl: 'views/login.html', + controller: 'LoginCtrl' + }).when('/register', { + templateUrl: 'views/register.html', + controller: 'RegisterCtrl' + }).when('/dashboard', { + templateUrl: 'views/dashboard.html', + controller: 'DashboardCtrl' + }).when('/profile', { + templateUrl: 'views/profile.html', + controller: 'ProfileCtrl' + }).when('/pages', { + templateUrl: 'views/pages.html', + controller: 'PagesCtrl', + resolve: { + pages: function (DataService) { + return DataService.fetch('pages').then(function (res) { + return res.data; + }); + } + } + }).when('/help', { + templateUrl: 'views/help.html', + controller: 'HelpCtrl' + }).when('/forgot-password', { + templateUrl: 'views/forgot-password.html', + controller: 'ForgotPasswordCtrl' + }).when('/register', { + templateUrl: 'views/register.html', + controller: 'RegisterCtrl' + }).otherwise({ + redirectTo: '/' + }); }); diff --git a/app/scripts/controllers/app.js b/app/scripts/controllers/app.js index 12892cf..eae40ee 100644 --- a/app/scripts/controllers/app.js +++ b/app/scripts/controllers/app.js @@ -1,20 +1,28 @@ 'use strict'; -angular.module('angularCmsApp').controller('AppCtrl', function($scope, $rootScope, $http, $log, $route, $location, $routeParams, $cookieStore, cmsSessionService, DataService) { - var App; - App = Config; - App.ds = DataService; - App.route = $routeParams; - App.session = cmsSessionService.getSession(); - App.theme = $cookieStore.get('App.theme'); - App.route = $route; - App.location = $location; - App.routeParams = $routeParams; - App.roles = ['guest', 'user', 'admin']; - $scope.name = 'AppCtrl'; - window.App = $scope.App = $rootScope.App = App; - return angular.element(document).ready(function() { - return angular.element('.nav').bind('click', 'a', function(e) { - return $log.info(e); - }); - }); +angular.module('angularCmsApp').controller('AppCtrl', function ($scope, $rootScope, $http, $log, $route, $location, $routeParams, $cookieStore, cmsSessionService, DataService, cmsSocketService) { + var App; + App = angular.copy(Config); + App.ds = DataService; + App.socket = cmsSocketService; + + + App.route = $routeParams; + App.session = cmsSessionService.getSession(); + App.theme = $cookieStore.get('App.theme'); + App.route = $route; + App.location = $location; + App.routeParams = $routeParams; + App.roles = ['guest', 'user', 'admin']; + + + $scope.name = 'AppCtrl'; + + window.App = $scope.App = $rootScope.App = App; + + + angular.element(document).ready(function () { + angular.element('.nav').bind('click', 'a', function (e) { + $log.info(e); + }); + }); }); diff --git a/app/scripts/filters/markdown.js b/app/scripts/filters/markdown.js index a0b2614..68d0621 100644 --- a/app/scripts/filters/markdown.js +++ b/app/scripts/filters/markdown.js @@ -1,15 +1,16 @@ - /** -@ngdoc filter -@name angularCmsApp.filter:markdown -@function - -@description + @ngdoc filter + @name angularCmsApp.filter:markdown + @function + + @description This is a Markdown to HTML filter. */ 'use strict'; -angular.module('angularCmsApp').filter('markdown', function() { - return function(input) { - return markdown.toHTML(input); - }; +angular.module('angularCmsApp').filter('markdown', function () { + return function (input) { + if(input){ + return markdown.toHTML(input); + } + }; }); diff --git a/app/scripts/services/cmsauthservice.js b/app/scripts/services/cmsauthservice.js deleted file mode 100644 index 9c1c2c0..0000000 --- a/app/scripts/services/cmsauthservice.js +++ /dev/null @@ -1,80 +0,0 @@ -'use strict'; - -/** -@module AuthService -@description -This service will take care of authentication of a user, common methods include: -* authorize -* logout -* register -* forgot -* currentUser - */ -angular.module('angularCmsApp').service('cmsAuthService', function($q, $http, $log, $rootScope, $cookieStore, $location, cmsSessionService, cmsNotify) { - var cmsAuthService; - return cmsAuthService = { - endpoint: '/api/v2', - - /** - authorize - I handle authorizing a user. - */ - authorize: function(user) { - return $http.post(this.endpoint + "/login", user); - }, - - /** - session - I handle getting a session. - */ - session: function() { - return $http.get(this.endpoint + "/session"); - }, - - /** - register - I handle register a user. - */ - register: function(user) { - $log.info('trying to register', user); - return $http.post(this.endpoint + "/register", user).then((function(_this) { - return function(res) { - $log.info(res); - return _this.authorize(res.data); - }; - })(this), function(err) { - $log.error(err); - return cmsNotify('.message', 'danger', 'Error!', err.data.message, 4000); - }); - }, - - /** - Logout method to clear the session. - @param {Object} user - A user model containing remember - */ - logout: function(user) { - cmsSessionService.setUserAuthenticated(null); - return $rootScope.apply(function() { - return $location.reload(); - }); - }, - - /** - Login - */ - login: function(user) { - return this.authorize(user).then(function(res) { - var session; - cmsNotify('.login-message', 'success', 'Success!', "Welcome back.", 5000); - session = { - user: res.data, - authorized: true - }; - cmsSessionService.setSession(session); - $rootScope.App.session = session; - $log.info('login-result', res); - return $rootScope.App.location.path('/dashboard'); - }, function(err) { - $log.error(err); - return cmsNotify('.login-message', 'danger', 'Error!', err.data.message); - }); - } - }; -}); diff --git a/app/scripts/services/cmsdataservicefactory.js b/app/scripts/services/cmsdataservicefactory.js deleted file mode 100644 index 39c1cd9..0000000 --- a/app/scripts/services/cmsdataservicefactory.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; -angular.module('angularCmsApp').factory('cmsDataServiceFactory', function() { - var meaningOfLife; - meaningOfLife = 42; - return { - someMethod: function() { - return meaningOfLife; - } - }; -}); diff --git a/app/scripts/services/cmsdataserviceprovider.js b/app/scripts/services/cmsdataserviceprovider.js deleted file mode 100644 index 560439d..0000000 --- a/app/scripts/services/cmsdataserviceprovider.js +++ /dev/null @@ -1,15 +0,0 @@ -var DataServiceProvider; - -angular.module("angularCmsApp").provider("cmsDataServiceProvider", DataServiceProvider = function() { - var DataServiceFactory, options; - DataServiceFactory = void 0; - options = void 0; - this.options = function(value) { - return options = !!value; - }; - this.$get = [ - "options", DataServiceFactory = function(options) { - return new cmsDataService(options); - } - ]; -}); diff --git a/app/scripts/services/cmsnotify.js b/app/scripts/services/cmsnotify.js deleted file mode 100644 index dc2517e..0000000 --- a/app/scripts/services/cmsnotify.js +++ /dev/null @@ -1,27 +0,0 @@ -'use strict'; -angular.module('angularCmsApp').factory('cmsNotify', [ - '$timeout', '$q', function($timeout, $q) { - var notices, notify; - notices = []; - notify = function(el, type, title, msg, timeout) { - var alert; - notices.push({ - type: type, - title: title, - msg: msg - }); - alert = "
\n \n " + title + " " + msg + "\n
"; - if (el) { - angular.element(el).prepend(alert); - } else { - angular.element('.container').prepend(alert); - } - if (timeout) { - return $timeout(function() { - return angular.element('.alert').fadeOut().remove(); - }, timeout); - } - }; - return notify; - } -]); diff --git a/app/scripts/services/cmssessionservice.js b/app/scripts/services/cmssessionservice.js deleted file mode 100644 index dea9b60..0000000 --- a/app/scripts/services/cmssessionservice.js +++ /dev/null @@ -1,79 +0,0 @@ -angular.module('angularCmsApp').service('cmsSessionService', [ - '$q', '$rootScope', '$cookieStore', '$location', '$log', function($q, $rootScope, $cookieStore, $location, $log) { - var SessionService, getUserAuthenticated, setUserAuthenticated, userIsAuthenticated; - userIsAuthenticated = $cookieStore.get('App.session'); - setUserAuthenticated = function(value) { - window.sessionStorage.setItem('userIsAuthenticated', value); - $cookieStore.put('App.session', value); - userIsAuthenticated = value; - return $log.info("user is authorized: " + userIsAuthenticated.authorized); - }; - getUserAuthenticated = function() { - window.sessionStorage.getItem('userIsAuthenticated'); - $log.info("user is authorized: " + userIsAuthenticated.authorized); - return userIsAuthenticated.authorized; - }; - $rootScope.$on("$locationChangeStart", function(event, next, current) { - var i, msg, _results; - $rootScope.$emit('session:route:start', { - event: event, - next: next, - current: current - }); - angular.element('.active').removeClass('active'); - _results = []; - for (i in window.routes) { - if (next.indexOf(i) !== -1) { - if (window.routes[i].requireLogin && !getUserAuthenticated()) { - msg = "You need to be authenticated to see this page!"; - $log.warn(msg); - event.preventDefault(); - $rootScope.$emit('session:unauthorized', event); - _results.push($location.path('/')); - } else { - angular.element('a[href="#' + $location.path() + '"]').addClass('active'); - _results.push($rootScope.$emit('session:authorized', event)); - } - } else { - _results.push(void 0); - } - } - return _results; - }); - SessionService = { - adapter: null, - session: $cookieStore.get('App.session'), - isAuthenticated: false, - getUserAuthenticated: getUserAuthenticated, - setUserAuthenticated: setUserAuthenticated, - getSession: function() { - if ($cookieStore.get('App.session')) { - return $cookieStore.get('App.session'); - } else { - return {}; - } - }, - setSession: function(value) { - return $cookieStore.put('App.session', value); - }, - login: function(user) { - var _ref; - $rootScope.$emit('session:login', user); - return (_ref = SessionService.adapter) != null ? typeof _ref.login === "function" ? _ref.login(user) : void 0 : void 0; - }, - logout: function(user) { - var _ref; - $rootScope.$emit('session:logout', user); - SessionService.setUserAuthenticated(user); - return (_ref = SessionService.adapter) != null ? typeof _ref.logout === "function" ? _ref.logout(user) : void 0 : void 0; - }, - register: function(user) { - var _ref; - $rootScope.$emit('session:register', user); - return (_ref = SessionService.adapter) != null ? typeof _ref.register === "function" ? _ref.register(user) : void 0 : void 0; - }, - routeResolver: function() {} - }; - return SessionService; - } -]); diff --git a/app/scripts/services/cmssocketservice.js b/app/scripts/services/cmssocketservice.js deleted file mode 100644 index 3c322e3..0000000 --- a/app/scripts/services/cmssocketservice.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -/** - * @ngdoc service - * @name angularCmsApp.cmsSocketService - * @description - * # cmsSocketService - * Service in the angularCmsApp. - */ -angular.module('angularCmsApp').service('cmsSocketService', function() { - var WebSocketClient; - WebSocketClient = function(options) { - var _ws; - _ws = void 0; - _ws = new WebSocket(options.endpoint, options.protocol); - _ws.onmessage = function(e) { - return console.log(e.data); - }; - _ws.onerror = function(e) { - return console.log(e); - }; - _ws.onclose = function(e) { - return console.log(e); - }; - _ws.onopen = function(e) { - _ws.send('update'); - }; - return { - instance: _ws, - close: function() { - return _ws.close(); - }, - send: function(obj) { - var err; - try { - _ws.send(obj); - } catch (_error) { - err = _error; - throw err; - } - } - }; - }; - return WebSocketClient; -}); diff --git a/app/scripts/services/cmsusersfactory.js b/app/scripts/services/cmsusersfactory.js deleted file mode 100644 index b7892e4..0000000 --- a/app/scripts/services/cmsusersfactory.js +++ /dev/null @@ -1,19 +0,0 @@ - -/** -@ngdoc service -@name angularCmsApp.service:cmsUsersFactory -@function - -@description - This is the UsersFactory. - */ -'use strict'; -angular.module('angularCmsApp').factory('cmsUsersFactory', function() { - var meaningOfLife; - meaningOfLife = 42; - return { - someMethod: function() { - return meaningOfLife; - } - }; -}); diff --git a/app/scripts/services/dataservice.js b/app/scripts/services/dataservice.js index 3c255c0..2ee4fa4 100644 --- a/app/scripts/services/dataservice.js +++ b/app/scripts/services/dataservice.js @@ -1,44 +1,41 @@ 'use strict'; -angular.module('angularCmsApp').service('DataService', [ - '$http', '$q', '$resource', function($http) { - var DataService; - DataService = { - endpoint: '/api/v2/angular-cms', - request: function(path, method, params, data) { - var defaults; - defaults = { - method: method, - url: this.endpoint + path, - cache: false, - data: data, - params: params - }; - console.log(path, defaults); - return $http(defaults); - }, - fetch: function(collection, params) { - return this.request('/' + collection, 'GET', params); - }, - get: function(collection, id, params) { - return this.request('/' + collection + '/' + id, 'GET', params); - }, - save: function(collection, data) { - if (data._id) { - return this._update(collection, data); - } else { - return this._create(collection, data); - } - }, - destroy: function(collection, data) { - return this.request('/' + collection + '/' + data._id, 'DELETE'); - }, - _create: function(collection, data) { - return this.request('/' + collection, 'POST', null, data); - }, - _update: function(collection, data) { - return this.request('/' + collection + '/' + data._id, 'PUT', null, data); - } - }; - return DataService; - } +angular.module('angularCmsApp').service('DataService', ['$http', function ($http) { + var DataService = { + endpoint: '/api/v2/angular-cms', + request: function (path, method, params, data) { + var defaults; + defaults = { + method: method, + url: this.endpoint + path, + cache: false, + data: data, + params: params + }; + return $http(defaults); + }, + fetch: function (collection, params) { + return this.request('/' + collection, 'GET', params); + }, + get: function (collection, id, params) { + return this.request('/' + collection + '/' + id, 'GET', params); + }, + save: function (collection, data) { + if (data && data._id) { + return this._update(collection, data); + } else { + return this._create(collection, data); + } + }, + destroy: function (collection, data) { + return this.request('/' + collection + '/' + data._id, 'DELETE'); + }, + _create: function (collection, data) { + return this.request('/' + collection, 'POST', null, data); + }, + _update: function (collection, data) { + return this.request('/' + collection + '/' + data._id, 'PUT', null, data); + } + }; + return DataService; + } ]); diff --git a/config/config.json b/config/config.json index 2f4153a..60183df 100644 --- a/config/config.json +++ b/config/config.json @@ -24,7 +24,7 @@ "password":"fred", "host":"localhost", "port":27017, - "url":"angularcms:angularcms@paulo.mongohq.com:10089/app19632340" + "url":"localhost/angular-cms" }, "email":{ "username":"angular.cms@gmail.com", diff --git a/routes/cms-sockets.js b/routes/cms-sockets.js index bc2c29d..b1aa2f2 100644 --- a/routes/cms-sockets.js +++ b/routes/cms-sockets.js @@ -1,9 +1,9 @@ +var events = require('events'), + util = require('util'), + q = require('q'), + WebSocketServer = require('websocket').server, + WebSocketRouter = require('websocket').router; -const events = require('events'), util = require('util'); - -var q = require( 'q' ), -WebSocketServer = require('websocket').server, -WebSocketRouter = require('websocket').router; //////////////////////////// //## Socket Server //This is a socket server implementation for 'real' time analytics and other data. @@ -23,52 +23,52 @@ WebSocketRouter = require('websocket').router; module.exports = function (config, app) { 'use strict'; events.EventEmitter.call(this); - console.warn( 'cms-sockts initialized' ); + console.warn('cms-socket initialized'); //Start the websocket server //SocketServer.init(proxyServer); var cmsSockets = {}, - connections, wsserver, wsclient, router, self = cmsSockets; + connections, wsserver, wsclient, router, self = cmsSockets; var delay = function (fn, time) { var defer = q.defer(); - setTimeout( function () { + setTimeout(function () { fn(); defer.resolve(); - }, time ); + }, time); return defer.promise; }; - var delayedSocketPush = function(socket, time){ - return delay( function (msg) { - socket.emit( 'msg', { + var delayedSocketPush = function (socket, time) { + return delay(function (msg) { + socket.emit('msg', { datetime: new Date(), message: msg, id: 'Server' - } ); - }, time ); + }); + }, time); }; //Hold the names of events that this socket server listens for and emits self.events = { - session: { - pageView: 'cms:session:pageView', - hashChange: 'cms:session:hashChange', - login: 'cms:session:login', - logout: 'cms:session:logout' - }, - server: { - message: 'cms:server:message', - connected: 'cms:server:connect', - disconnected: 'cms:server:disconnect' - }, - client: { - message: 'cms:client:message', - connected: 'cms:client:connect', - disconnected: 'cms:client:disconnect' - } - }; + session: { + pageView: 'cms:session:pageView', + hashChange: 'cms:session:hashChange', + login: 'cms:session:login', + logout: 'cms:session:logout' + }, + server: { + message: 'cms:server:message', + connected: 'cms:server:connect', + disconnected: 'cms:server:disconnect' + }, + client: { + message: 'cms:client:message', + connected: 'cms:client:connect', + disconnected: 'cms:client:disconnect' + } + }; //Store a list of the connected clients @@ -84,21 +84,30 @@ module.exports = function (config, app) { router = new WebSocketRouter(); router.attachServer(wsserver); - router.mount('*', 'echo-protocol', function(request) { + /** + * Echo Protocol + */ + router.mount('*', 'echo-protocol', function (request) { console.log('mounted to echo protocol'); + var conn = request.accept(request.origin); - conn.on('message', function(message) { - console.log('routed message', message); + + conn.on('message', function (message) { + console.log('routed message', util.inspect(message, {colors: true})); }); conn.send('hey'); }); - router.mount('*', 'update-protocol', function(request) { + /** + * Update Protocol + */ + router.mount('*', 'update-protocol', function (request) { console.log('mounted to update protocol'); var conn = request.accept(request.origin); - conn.on('message', function(message) { + conn.on('message', function (message) { console.log('update all the things', message); - }); }); + }); + }); util.inherits(cmsSockets, events.EventEmitter); diff --git a/routes/generic.js b/routes/generic.js index 4298d87..9774124 100644 --- a/routes/generic.js +++ b/routes/generic.js @@ -11,17 +11,18 @@ var mongo = require('mongodb'); var mongoose = require('mongoose'); var Server = mongo.Server; var Db = mongo.Db; +var Resource; //Connect to the database -mongoose.connect('mongodb://localhost:27017/myappmatrix'); +//mongoose.connect('mongodb://localhost:27017/myappmatrix'); /* ======================[ @TODO: Modal Schema ]====================== */ var Post = mongoose.model('post', new mongoose.Schema({ - text : String, - done : Boolean, - order : Number + text: String, + done: Boolean, + order: Number })); @@ -38,306 +39,233 @@ var Post = mongoose.model('post', new mongoose.Schema({ * PUT update http://localhost:3000/accounts/:id * DELETE destroy http://localhost:3000/accounts/:id */ -var Resource = { - host : 'localhost', - port : 27017, - /** - * I enable logging or not. - */ - debug : true, - /** - * I am the interal logger. - */ - log : function(obj) { - if (Resource.debug) { - console.log(obj); - } - }, - /** - * I am the name of the database. - */ - databaseName : 'accounts_db', - /** - * I am the name of this collection. - */ - name : 'accounts', - mongo : mongo, - server : null, - db : null, - mongoServer : mongo.Server, - mongoDb : mongo.Db, - bson : mongo.BSONPure, - /** - * I am the example schema for this resources. - */ - schema : { - id : '', - ns : 'com.domain.app', - title : '', - body : '', - address1 : '', - address2 : '', - city : '', - state : '', - zip : '', - type : '', - active : '0', - created : '', - modified : '', - website : '', - apple_url : '', - android_url : '', - user_id : '', - application_id : '', - appcellerator_url : '', - settings : '', - plan : '', - exp_date : '', - upfront_cost : '', - monthly_cost : '', - service_term : '12', - service_value : '', - total_value : '', - sla_number : '', - contract_in : '', - app_submitted : '' - }, - routes : { - 'status' : 'dbStatus' - }, - /** - * I create a new instance of the database. - */ - initDb : function() { - - Resource.server = new Server(Resource.host, Resource.port, { - auto_reconnect : true, - safe : false - }); - Resource.db = new Db(Resource.databaseName, Resource.server); - - /** - * Open the database and check for collection, if none - * then create it with the schema. - */ - Resource.db.open(function(err, db) { - if (!err) { - Resource.log('Connected to ' + Resource.databaseName); - db.collection(Resource.name, { - safe : true - }, function(err, collection) { - if (err) { - Resource.log('The collection doesnt exist. creating it with sample data...'); - Resource.populateDb(); - } - }); - } - }); - - }, - - /** - * I populate the document db with the schema. - */ - populateDb : function() { - Resource.db.collection(Resource.name, function(err, collection) { - collection.insert(Resource.schema, { - safe : true - }, function(err, result) { - Resource.log(result); - }); - }); - }, - - dbStatus: function(){ - console.log('get db status'); - }, - - /** - * I find all of the records - * @param {Object} req - * @param {Object} res - */ - findAll : function(req, res) { - Resource.db.collection(Resource.name, function(err, collection) { - collection.find().toArray(function(err, items) { - Resource.log(Resource.name + ':findAll - ' + JSON.stringify(items)); - res.send(items); - }); - }); - }, - /** - * I find one of the records by id. - * @param {Object} req - * @param {Object} res - */ - findById : function(req, res) { - - var id = req.params.id; - - Resource.log(Resource.name + ':findById - ' + id); - - Resource.db.collection(Resource.name, function(err, collection) { - collection.findOne({ - '_id' : new Resource.BSON.ObjectID(id) - }, function(err, item) { - res.send(item); - }); - }); - - - }, - /** - * I add a record to the collection - * @param {Object} req - * @param {Object} res - */ - add : function(req, res) { - var data = req.body; - - Resource.log(Resource.name + ':add - ' + JSON.stringify(data)); - Resource.db.collection(Resource.name, function(err, collection) { - collection.insert(data, { - safe : true - }, function(err, result) { - if (err) { - res.send({ - 'error' : 'An error has occurred' - }); - } else { - Resource.log('Success: ' + JSON.stringify(result[0])); - res.send(result[0]); - } - }); - }); - }, - /** - * I update a record in the collection - * @param {Object} req - * @param {Object} res - */ - update : function(req, res) { - var id = req.params.id; - var data = req.body; - Resource.log(Resource.name + ':destroy -' + id + ' - ' + JSON.stringify(data)); - Resource.db.collection(Resource.name, function(err, collection) { - collection.update({ - '_id' : new Resource.BSON.ObjectID(id) - }, data, { - safe : true - }, function(err, result) { - if (err) { - res.send({ - 'error' : 'An error has occurred' - }); - console.log('Error updating ' + Resource.name + ': ' + err); - } else { - console.log('' + result + 'document(s) updated'); - - res.send(data); - } - }); - }); - }, - /** - * I delete a record in the collection. - * @param {Object} req - * @param {Object} res - - return Todo.findById(req.params.id, function(err, todo) { - return todo.remove(function(err) { - if (!err) { - console.log("removed"); - return res.send('') - } - }); - }); - */ - destroy : function(req, res) { - var id = req.params.id; - Resource.log(Resource.name + ':destroy -' + id); - Resource.db.collection(Resource.name, function(err, collection) { - collection.remove({ - '_id' : new Resource.BSON.ObjectID(id) - }, { - safe : true - }, function(err, result) { - if (err) { - res.send({ - 'error' : 'An error has occurred' - }); - Resource.log('Error updating ' + Resource.name + ': ' + err); - } else { - res.send(req.body); - } - }); - }); - } -}; - -//Export to public api -exports.Resource = Resource; - - - - - - -var express = require('express'); -var app = express(); - app.configure(function() { - app.use(express.logger('dev')); - app.use(express.bodyParser()); - app.use(function(err, req, res, next){ - console.error(err.stack); - res.send(500, 'Something broke!'); +var database = null, server = null; +Resource = { + host: 'localhost', + port: 27017, + /** + * I enable logging or not. + */ + debug: true, + /** + * I am the interal logger. + */ + log: function (obj) { + if (Resource.debug) { + console.log(obj); + } + }, + /** + * I am the name of the database. + */ + databaseName: 'angular-cms', + /** + * I am the name of this collection. + */ + name: 'accounts', + mongo: mongo, + server: null, + db: null, + mongoServer: mongo.Server, + mongoDb: mongo.Db, + bson: mongo.BSONPure, + /** + * I am the example schema for this resources. + */ + schema: { + id: '', + ns: 'com.domain.app', + title: '', + body: '', + address1: '', + address2: '', + city: '', + state: '', + zip: '', + type: '', + active: '0', + created: '', + modified: '', + website: '', + apple_url: '', + android_url: '', + user_id: '', + application_id: '', + appcellerator_url: '', + settings: '', + plan: '', + exp_date: '', + upfront_cost: '', + monthly_cost: '', + service_term: '12', + service_value: '', + total_value: '', + sla_number: '', + contract_in: '', + app_submitted: '' + }, + routes: { + 'status': 'dbStatus' + }, + /** + * I create a new instance of the database. + */ + init: function () { + server = new Server(Resource.host, Resource.port); + database = new Db(Resource.databaseName, Resource.server, { + auto_reconnect: true, + safe: false }); - - // simple logger - app.use(function(req, res, next){ - console.log('%s %s', req.method, req.url); - next(); - }); - -}); - - - -/* @TODO: Base Route */ -app.get('/', function(req, res) { - res.send('Generic Mongo REST Server'); -}); - - - - -/* @TODO: Insert */ -app.post('/:db/:collection', function(req, res) { - if(req.body) { - var db = new mongo.Db(req.params.db, new mongo.Server(Resource.host, Resource.port, {'auto_reconnect':true, 'safe' : true})); - db.open(function(err, db) { - //set the collection - db.collection(req.params.collection, function(err, collection) { - // We only support inserting one document at a time - collection.insert(Array.isArray(req.body) ? req.body[0] : req.body, function(err, docs) { - // res.header('Location', '/'+req.params.db+'/'+req.params.collection+'/'+docs[0]._id.toHexString()); - res.header('Content-Type', 'application/json');'' - res.send('{"ok":1}', 201); - db.close(); - }); - }); - - }); - //else return false - } else { - res.header('Content-Type', 'application/json'); - res.send('{"ok":0}',200); - } -}); + database.open(function (err, db) { + if (!err) { + Resource.log('Connected to ' + Resource.databaseName); + db.collection(Resource.name, { + safe: true + }, function (err, collection) { + if (err) { + Resource.log('The collection doesnt exist. creating it with sample data...'); + Resource.populateDb(); + } + }); + } + }); + return this; + }, + /** + * I populate the document db with the schema. + */ + populateDb: function () { + database.collection(Resource.name, function (err, collection) { + collection.insert(Resource.schema, { + safe: true + }, function (err, result) { + Resource.log(result); + }); + }); + }, + + dbStatus: function () { + console.log('get db status'); + }, + + /** + * I find all of the records + * @param {Object} req + * @param {Object} res + */ + findAll: function (col) { + database.collection(col, function (err, collection) { + collection.find().toArray(function (err, items) { + if (err) { + throw err; + } + if (items) { + Resource.log(col + ':findAll - ' + JSON.stringify(items)); + return items; + } + }); + }); + }, + /** + * I find one of the records by id. + * @param {Object} req + * @param {Object} res + */ + findById: function (req, res) { + + var id = req.params.id; + + Resource.log(Resource.name + ':findById - ' + id); + + db.collection(Resource.name, function (err, collection) { + collection.findOne({ + '_id': new Resource.BSON.ObjectID(id) + }, function (err, item) { + res.send(item); + }); + }); + }, + /** + * I add a record to the collection + * @param {Object} req + * @param {Object} res + */ + add: function (req, res) { + var data = req.body; + + Resource.log(Resource.name + ':add - ' + JSON.stringify(data)); + Resource.db.collection(Resource.name, function (err, collection) { + collection.insert(data, { + safe: true + }, function (err, result) { + if (err) { + res.send({ + 'error': 'An error has occurred' + }); + } else { + Resource.log('Success: ' + JSON.stringify(result[0])); + res.send(result[0]); + } + }); + }); + }, + /** + * I update a record in the collection + * @param {Object} req + * @param {Object} res + */ + update: function (id, data) { + Resource.log(Resource.name + ':destroy -' + id + ' - ' + JSON.stringify(data)); + Resource.db.collection(Resource.name, function (err, collection) { + collection.update({ + '_id': new Resource.BSON.ObjectID(id) + }, data, { + safe: true + }, function (err, result) { + if (err) { + res.send({ + 'error': 'An error has occurred' + }); + console.log('Error updating ' + Resource.name + ': ' + err); + } else { + console.log('' + result + 'document(s) updated'); + + res.send(data); + } + }); + }); + }, + /** + * I delete a record in the collection. + * @param {Object} req + * @param {Object} res + */ + destroy: function (req, res) { + var id = req.params.id; + Resource.log(Resource.name + ':destroy -' + id); + Resource.db.collection(Resource.name, function (err, collection) { + collection.remove({ + '_id': new Resource.BSON.ObjectID(id) + }, { + safe: true + }, function (err, result) { + if (err) { + res.send({ + 'error': 'An error has occurred' + }); + Resource.log('Error updating ' + Resource.name + ': ' + err); + } else { + res.send(req.body); + } + }); + }); + } +}; +module.exports = Resource; \ No newline at end of file diff --git a/server.js b/server.js index 67ea21f..2b1271d 100755 --- a/server.js +++ b/server.js @@ -4,8 +4,18 @@ */ var express = require('express'); var fs = require('fs'); -var cmsRouter = require('./routes/cms-router.js'); +//var cmsRouter = require('./routes/cms-router.js'); var app = express(); -var config = JSON.parse(fs.readFileSync('./config/config.json')); -var server = new cmsRouter.mount(config, app); -console.log(server); +//var config = JSON.parse(fs.readFileSync('./config/config.json')); +//var server = new cmsRouter.mount(config, app); +//console.log(server); + + +var Resource = require('./routes/generic.js'); + + + + +var r = Resource.init(); + +console.log(r.findAll('users')); diff --git a/test/protractor/spec/register-spec.js b/test/protractor/spec/register-spec.js index 51d1903..0386f44 100644 --- a/test/protractor/spec/register-spec.js +++ b/test/protractor/spec/register-spec.js @@ -1,20 +1,15 @@ var registerPage, testEmail; - registerPage = require('../pages/register-page'); - - /** -Register - The user registration implementation + Register - The user registration implementation */ - testEmail = Date.now() + '-test@email.com'; - -describe('Register: ', function() { - return it('should allow a user to register', function() { - registerPage.get(); - expect(browser.getCurrentUrl()).toContain('register'); - return registerPage.register(testEmail, 'test').then(function() { - return expect(browser.getCurrentUrl()).toContain('dashboard'); - }); - }); +describe('Register: ', function () { + return it('should allow a user to register', function () { + registerPage.get(); + expect(browser.getCurrentUrl()).toContain('register'); + return registerPage.register(testEmail, 'test').then(function () { + return expect(browser.getCurrentUrl()).toContain('dashboard'); + }); + }); }); diff --git a/test/spec/services/cmssocketservice.js b/test/spec/services/cmssocketservice.js index d7f790b..afe1988 100644 --- a/test/spec/services/cmssocketservice.js +++ b/test/spec/services/cmssocketservice.js @@ -1,12 +1,12 @@ 'use strict'; -describe('Service: cmsSocketService', function() { - var cmsSocketService; - beforeEach(module('angularCmsApp')); - cmsSocketService = {}; - beforeEach(inject(function(_cmsSocketService_) { - return cmsSocketService = _cmsSocketService_; - })); - return it('should do something', function() { - return expect(!!cmsSocketService).toBe(true); - }); +describe('Service: cmsSocketService', function () { + var cmsSocketService; + beforeEach(module('angularCmsApp')); + cmsSocketService = {}; + beforeEach(inject(function (_cmsSocketService_) { + cmsSocketService = _cmsSocketService_; + })); + it('should do something', function () { + expect(!!cmsSocketService).toBe(true); + }); }); diff --git a/test/spec/services/dataservice.js b/test/spec/services/dataservice.js index 3d5a407..d0ff372 100644 --- a/test/spec/services/dataservice.js +++ b/test/spec/services/dataservice.js @@ -1,113 +1,114 @@ 'use strict'; -describe('Service: DataService', function() { - var $httpBackend, $q, $rootScope, baseUrl, ds, errorCallback, successCallback, testObject; - beforeEach(module('angularCmsApp')); - baseUrl = '/api/v2/angular-cms'; - ds = null; - $httpBackend = null; - $q = null; - $rootScope = null; - successCallback = null; - errorCallback = null; - testObject = { - _id: 1, - title: 'Test Object', - body: 'This is a sample object for testing.' - }; - beforeEach(inject(function(_$rootScope_, _DataService_, _$httpBackend_, _$q_) { - ds = _DataService_; - $httpBackend = _$httpBackend_; - $q = _$q_; - $rootScope = _$rootScope_; - successCallback = jasmine.createSpy('success'); - return errorCallback = jasmine.createSpy('error'); - })); - it('should have DataService defined', function() { - return expect(!!ds).toBe(true); - }); - it('should have a fetch method', function() { - return expect(ds.fetch).toBeDefined(); - }); - it('should have a save method', function() { - return expect(ds.save).toBeDefined(); - }); - it('should have a destroy method', function() { - return expect(ds.destroy).toBeDefined(); - }); - xit('should invoke create method if _id is not on object', function() { - $httpBackend.expectPOST("" + baseUrl + "/posts").respond(200, [{}, {}]); - spyOn(ds, '_create'); - spyOn(ds, '_update'); - ds.save('posts', { - title: 'New Post' - }).then(successCallback, errorCallback); - $httpBackend.flush(); - expect(successCallback).toHaveBeenCalled(); - expect(errorCallback).not.toHaveBeenCalled(); - expect(ds._create).toHaveBeenCalled(); - return expect(ds._update).not.toHaveBeenCalled(); - }); - xit('should invoke update method if _id is on object', function() { - $httpBackend.expectPUT("" + baseUrl + "/posts/1").respond(200, { - message: 'Success updating object' - }); - spyOn(ds, '_create'); - spyOn(ds, '_update'); - ds.save('posts', testObject).then(successCallback, errorCallback); - $httpBackend.flush(); - expect(successCallback).toHaveBeenCalled(); - expect(errorCallback).not.toHaveBeenCalled(); - expect(ds._create).not.toHaveBeenCalled(); - return expect(ds._update).toHaveBeenCalled(); - }); - it('GET - /collection - should reject promise on error', function() { - $httpBackend.expectGET("" + baseUrl + "/posts").respond(404, { - message: 'Data not found' - }); - ds.fetch('posts').then(successCallback, errorCallback); - $httpBackend.flush(); - expect(successCallback).not.toHaveBeenCalled(); - return expect(errorCallback).toHaveBeenCalled(); - }); - it('GET - /collection - should resolve promise on success', function() { - $httpBackend.expectGET("" + baseUrl + "/posts").respond(200, [{}, {}]); - ds.fetch('posts').then(successCallback, errorCallback); - $httpBackend.flush(); - expect(successCallback).toHaveBeenCalled(); - return expect(errorCallback).not.toHaveBeenCalled(); - }); - it('GET - /collection/id - should reject promise on error', function() { - $httpBackend.expectGET("" + baseUrl + "/posts/1").respond(404, { - message: 'Data not found' - }); - ds.get('posts', 1).then(successCallback, errorCallback); - $httpBackend.flush(); - expect(successCallback).not.toHaveBeenCalled(); - return expect(errorCallback).toHaveBeenCalled(); - }); - it('GET - /collection/id - should resolve promise on success', function() { - $httpBackend.expectGET("" + baseUrl + "/posts/1").respond(200, testObject); - ds.get('posts', 1).then(successCallback, errorCallback); - $httpBackend.flush(); - expect(successCallback).toHaveBeenCalled(); - return expect(errorCallback).not.toHaveBeenCalled(); - }); - it('DELETE - /collection/id - should resolve promise on success', function() { - $httpBackend.expectDELETE("" + baseUrl + "/posts/1").respond(200, { - message: 'Success deleting object' - }); - ds.destroy('posts', testObject).then(successCallback, errorCallback); - $httpBackend.flush(); - expect(successCallback).toHaveBeenCalled(); - return expect(errorCallback).not.toHaveBeenCalled(); - }); - it('DELETE - /collection/id - should reject promise on error', function() { - $httpBackend.expectDELETE("" + baseUrl + "/posts/1").respond(404, { - message: 'Error deleting object' - }); - ds.destroy('posts', testObject).then(successCallback, errorCallback); - $httpBackend.flush(); - expect(successCallback).not.toHaveBeenCalled(); - return expect(errorCallback).toHaveBeenCalled(); - }); +describe('Service: DataService', function () { + var $httpBackend, $q, $rootScope, baseUrl, ds, errorCallback, successCallback, testObject; + beforeEach(module('angularCmsApp')); + baseUrl = '/api/v2/angular-cms'; + ds = null; + $httpBackend = null; + $q = null; + $rootScope = null; + successCallback = null; + errorCallback = null; + testObject = { + _id: 1, + title: 'Test Object', + body: 'This is a sample object for testing.' + }; + beforeEach(inject(function (_$rootScope_, _DataService_, _$httpBackend_, _$q_) { + ds = _DataService_; + $httpBackend = _$httpBackend_; + $q = _$q_; + $rootScope = _$rootScope_; + successCallback = jasmine.createSpy('success'); + errorCallback = jasmine.createSpy('error'); + })); + it('should have DataService defined', function () { + expect(!!ds).toBe(true); + }); + it('should have a fetch method', function () { + expect(ds.fetch).toBeDefined(); + }); + it('should have a save method', function () { + expect(ds.save).toBeDefined(); + }); + it('should have a destroy method', function () { + expect(ds.destroy).toBeDefined(); + }); + it('should invoke create method if _id is not on object', function () { + $httpBackend.expectPOST('' + baseUrl + '/posts').respond(200, [{}, {}]); + //ds = jasmine.createSpy('ds', ['_create', '_update', 'save']); + spyOn(ds, '_create').and.callThrough(); + spyOn(ds, '_update').and.callThrough(); + + ds.save('posts', {title: 'New Post'}).then(successCallback, errorCallback); + $httpBackend.flush(); + + expect(successCallback).toHaveBeenCalled(); + expect(errorCallback).not.toHaveBeenCalled(); + expect(ds._create).toHaveBeenCalled(); + expect(ds._update).not.toHaveBeenCalled(); + }); + it('should invoke update method if _id is on object', function () { + $httpBackend.expectPUT('' + baseUrl + '/posts/1').respond(200, { + message: 'Success updating object' + }); + spyOn(ds, '_create').and.callThrough(); + spyOn(ds, '_update').and.callThrough(); + ds.save('posts', testObject).then(successCallback, errorCallback); + $httpBackend.flush(); + expect(successCallback).toHaveBeenCalled(); + expect(errorCallback).not.toHaveBeenCalled(); + expect(ds._create).not.toHaveBeenCalled(); + expect(ds._update).toHaveBeenCalled(); + }); + it('GET - /collection - should reject promise on error', function () { + $httpBackend.expectGET('' + baseUrl + '/posts').respond(404, { + message: 'Data not found' + }); + ds.fetch('posts').then(successCallback, errorCallback); + $httpBackend.flush(); + expect(successCallback).not.toHaveBeenCalled(); + expect(errorCallback).toHaveBeenCalled(); + }); + it('GET - /collection - should resolve promise on success', function () { + $httpBackend.expectGET('' + baseUrl + '/posts').respond(200, [{}, {}]); + ds.fetch('posts').then(successCallback, errorCallback); + $httpBackend.flush(); + expect(successCallback).toHaveBeenCalled(); + expect(errorCallback).not.toHaveBeenCalled(); + }); + it('GET - /collection/id - should reject promise on error', function () { + $httpBackend.expectGET('' + baseUrl + '/posts/1').respond(404, { + message: 'Data not found' + }); + ds.get('posts', 1).then(successCallback, errorCallback); + $httpBackend.flush(); + expect(successCallback).not.toHaveBeenCalled(); + expect(errorCallback).toHaveBeenCalled(); + }); + it('GET - /collection/id - should resolve promise on success', function () { + $httpBackend.expectGET('' + baseUrl + '/posts/1').respond(200, testObject); + ds.get('posts', 1).then(successCallback, errorCallback); + $httpBackend.flush(); + expect(successCallback).toHaveBeenCalled(); + expect(errorCallback).not.toHaveBeenCalled(); + }); + it('DELETE - /collection/id - should resolve promise on success', function () { + $httpBackend.expectDELETE('' + baseUrl + '/posts/1').respond(200, { + message: 'Success deleting object' + }); + ds.destroy('posts', testObject).then(successCallback, errorCallback); + $httpBackend.flush(); + expect(successCallback).toHaveBeenCalled(); + expect(errorCallback).not.toHaveBeenCalled(); + }); + it('DELETE - /collection/id - should reject promise on error', function () { + $httpBackend.expectDELETE('' + baseUrl + '/posts/1').respond(404, { + message: 'Error deleting object' + }); + ds.destroy('posts', testObject).then(successCallback, errorCallback); + $httpBackend.flush(); + expect(successCallback).not.toHaveBeenCalled(); + expect(errorCallback).toHaveBeenCalled(); + }); });