【问题标题】:Creating a Mockup REST API创建模型 REST API
【发布时间】:2013-09-07 06:22:24
【问题描述】:

我目前正在尝试创建 NodeJS 服务器或类似于模拟 REST API 的东西,该 API 读取 JSON 文件并使用该数据响应请求。我真的只需要支持 GET 请求。解决这个问题的最佳方法是什么?

这是我目前所拥有的:

/**
 * Sample items REST API
 */
function ItemsRepository() {
    this.items = [];
}

ItemsRepository.prototype.find = function (id) {
    var item = this.items.filter(function(item) {
        return item.itemId == id;
    })[0];
    if (null == item) {
        throw new Error('item not found');
    }
    return item;
}

/**
 * Retrieve all items
 * items: array of items
 */
ItemsRepository.prototype.findAll = function () {
    return this.items;
}

/**
 * API
 */
var express = require('express');
var app = express();
var itemRepository = new ItemsRepository();
app.configure(function () {
    // used to parse JSON object given in the body request
    app.use(express.bodyParser());
});
/**
 * HTTP GET /items
 * items: the list of items in JSON format
 */
app.get('/items', function (request, response) {
    response.json({items: itemRepository.findAll()});
});
/**
 * HTTP GET /items/:id
 * Param: :id is the unique identifier of the item you want to retrieve
 * items: the item with the specified :id in a JSON format
 * Error: 404 HTTP code if the item doesn't exists
 */
app.get('/items/:id', function (request, response) {
    var itemId = request.params.id;
    try {
        response.json(itemRepository.find(itemId));
    } catch (exception) {
        response.send(404);
    }

});


app.listen(8080); //to port on which the express server listen

我知道我会使用以下内容来包含文件,我只是不知道如何将数据填充到项目中。

var responseItemsData = require('./items-list.json');

【问题讨论】:

    标签: javascript json node.js rest


    【解决方案1】:

    这在节点中是微不足道的。您可以通过直接请求.json 文件来加载数据

    var responseData = require('./my-json-file'); //.json extension optional
    //Do this during your startup code, not during the request handler
    

    然后发送:

    res.write(JSON.stringify(responseData));
    

    您需要的其余代码在网络上几乎每个 node.js 教程中都很容易获得。

    【讨论】:

    • 那么我如何只返回请求中的一些数据,如上面的代码所示的“/items/:id”?
    • 您上面的代码看起来应该可以工作。您正在绕过节点的整个异步部分,这是了解您在做什么的重要部分,以及使用带有错误而不是异常的回调,但是对于同步代码,您上面的 sn-p 至少是连贯的。
    • 如何用我用 var responseData = require('./my-json-file') 读入的文件的内容填充我的项目?
    • function ItemsRepository() { this.items = require('./my-items-json-file'); }
    • 我需要将我的 JSON 包装在任何东西中还是可以是原始的?我遇到各种语法错误,我认为我的 JSON 不正确。
    【解决方案2】:

    你可以使用茉莉+诗农:

    var Episode = Backbone.Model.extend({
          url: function() {
            return "/episode/" + this.id;
          }
    });
    
      beforeEach(function() {
        this.server = sinon.fakeServer.create();
      });
    
      afterEach(function() {
        this.server.restore();
      });
    
      it("should fire the change event", function() {
        var callback = sinon.spy();
    
        this.server.respondWith("GET", "/episode/123",
          [200, {"Content-Type": "application/json"},'{"id":123,"title":"Hollywood - Part 2"}']);
    
        var episode = new Episode({id: 123});
    
        // Bind to the change event on the model
        episode.bind('change', callback);
    
        // makes an ajax request to the server
        episode.fetch(); 
    
        // Fake server responds to the request
        this.server.respond(); 
    
        // Expect that the spy was called with the new model
        expect(callback.called).toBeTruthy();
        expect(callback.getCall(0).args[0].attributes)
          .toEqual({id: 123,
                    title: "Hollywood - Part 2"});
    
      });
    

    更多详情请见:https://github.com/cld-santos/simplologia/tree/master/javascript-lessons/src/test/javascript/Sinon

    【讨论】:

      【解决方案3】:

      最简单的方法是简单地使用静态中间件。

      var express = require('express');
      var app = express();
      app.use('/api', express.static(__dirname + '/data'));
      app.use('.*', express.static(__dirname + '/assets'));
      

      这假设您最终会将 REST api 放在 /api 中,但是当您测试时,您的数据将位于 data 目录中,并且您的 CSS/JS/HTML 位于 assets 文件夹中.实际上你可以把它放在任何你想要的地方,但是你现在可以把你所有的开发 json 和你的代码分开。

      【讨论】:

        【解决方案4】:

        我为此创建了一个工具 https://github.com/homerquan/kakuen

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-10-09
          • 1970-01-01
          • 1970-01-01
          • 2017-10-31
          • 1970-01-01
          相关资源
          最近更新 更多