REST架构网站改写:前端MVC - Angular.js,Web框架 - Express.js, 数据库 - MongoDB
Coenraets分享了自己开发的一个Single Page Restful网站(http://coenraets.org/blog/2012/10/nodecellar-sample-application-with-backbone-js-twitter-bootstrap-node-js-express-and-mongodb)。
他利用多种不同的前后端技术改写了这个项目,大致有以下这些:
CSS库 - Bootstrap;
前端MVC - Backbone.js,Angular.js;
Web框架 - Express.js(Node.js)、PHP、Java ;
数据库 - MongoDB、MySQL。
其中,我最感兴趣Angular + Express + MongoDB的组合,Coenraets恰好没有实现;再加之Angular新版本改进颇大,尤其是Coenraets的实现没有使用angular.modular,所以我做了些改写,核心代码如下。
Express Server部分:监听和响应客户端HTTP请求。
1 app.get('/wines', wine.findAll); 2 app.get('/wines/:id', wine.findById); //retrieve 3 app.post('/wines', wine.addWine); //create 4 app.put('/wines/:id', wine.updateWine); //update 5 app.delete('/wines/:id', wine.deleteWine); //delete
前端MVC架构:响应用户请求,完成大部分UI逻辑
controller.js
1 angular.module('controller', ['service']). 2 config(function($routeProvider) { 3 $routeProvider.when('/wines', {templateUrl:'tpl/welcome.html'}). 4 when('/addWine',{templateUrl:'tpl/wine-details.html', controller:AddWineCtrl}). 5 when('/wines/:wineId', {templateUrl:'tpl/wine-details.html', controller:WineDetailCtrl}). 6 otherwise({redirectTo:'/wines'}); 7 }); 8 9 function WineListCtrl($scope, Wine) { 10 Wine.query(function(wines) { 11 $scope.wines = wines; 12 }); 13 } 14 15 function AddWineCtrl($scope, $location, Wine) { 16 // POST /wines 17 $scope.saveWine = function() { 18 Wine.save($scope.wine, function() { 19 $location.path("/wines"); 20 }); 21 }; 22 } 23 24 function WineDetailCtrl($scope, $location, $routeParams, Wine) { 25 27 // GET /wines/id 28 Wine.get({wineId: $routeParams.wineId}, function(wine){ 29 $scope.wine = wine; 30 }); 31 32 // PUT /wines/id 33 $scope.saveWine = function () { 34 Wine.update({wineId: $routeParams.wineId}, 35 $scope.wine, function() { 36 $location.path("/wines"); 37 }); 38 }; 39 40 //DELETE /wines/id 41 $scope.deleteWine = function () { 42 Wine.delete({wineId: $routeParams.wineId}, function() { 43 $location.path("/wines"); 44 }); 45 }; 46 }
service.js
1 angular.module('service', ['ngResource']). 2 factory('Wine', function($resource) { 3 return $resource('/wines/:wineId', {}, { 4 update: {method:'PUT'} 5 }); 6 });
整个项目前后端完全隔离,通过Restful协议通信;Express框架在Node.js中的地位类似于Django之于Python或Rails之于Ruby,新版Myspace是利用它开发的;Angular.js能大幅度减轻前端MVC工作量,直接进行DOM操纵而无需jQuery。