使用restify快速开发rest api,并使用angular resource 快速使用api

1.CORS的解决

server.use(restify.CORS());
server.use(restify.fullResponse());
restify.CORS.ALLOW_HEADERS.push('authorization');

2. 快速生成REST API

var Kpi = require('../models/Kpi');
var restifyMongoose = require('restify-mongoose');

module.exports = function(server) {
        restifyMongoose(Kpi).serve('/api/kpi/:id', server);
};    

3. 路由如下

* GET '/api/kpi' to `query` function
* GET '/api/kpi/:id' to `detail` function
* POST '/api/kpi' to `insert` function
* DELETE '/api/kpi/:id' to `remove` function
* PATCH '/api/kpi/:id' to `update` function

4. angular resource的使用

   angular resource default设置

   {
      'get':    {method:'GET'},
      'save':   {method:'POST'},
      'query':  {method:'GET', isArray:true},
      'remove': {method:'DELETE'},
      'delete': {method:'DELETE'} 
};

  由于restify-mongoose 的更新使用的是:PATCH,

  所以要设置一下,更新的method为PATCH

angular.module('app.data.services', ['ngResource'])
    .factory('Kpi', function($resource) {
        var server = CONFIG.APISERVER;
        return $resource(server + '/api/kpi/:id',{ id: '@_id' },{update:{method:'PATCH'}});
    });

   这样就可以很方便的使用

   Kpi.query,Kpi.update,Kpi.save

   注意: 对于$resource返回的数组数据要使用angular.forEach来访问

        kqi.query(function(response) {
            angular.forEach(response, function(item) {
                kqi[item.code] = kpi.doKqiScore(item);
            });
        });

 

posted @ 2015-03-12 10:51  witwave  阅读(306)  评论(0)    收藏  举报