在NodeJS Express框架中处理批处理REST API请求 [英] Processing Batch REST API requests in NodeJS Express framework

查看:74
本文介绍了在NodeJS Express框架中处理批处理REST API请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的应用程序实现批处理API,客户端可以向服务器发送一组发送请求,并期望返回单个响应.

I am trying to implement batch API for my application, and the client can send a send a set of request to server and expects a single response back.

在我的MEAN堆栈应用中使用Express框架.我创建了一个批处理API资源,该资源从客户端接收该资源,并应按照请求各部分中提到的URL进行操作.

Using Express framework in my MEAN stack app. I have created a batch API resource that receives this from client and should act as per the URL mentioned in each part of the request.

样品申请正文:

{
    "batchID": "abc123",
    "batchReq": [{
        "id": "1",
        "url": "/api/schoolm/students",
        "method": "GET",
        "value": null
    }, {
        "id": "2",
        "url": "/api/schoolm/teachers",
        "method": "POST",
        "value": {
            "name": "Teacher1",
            "age": 34
        }
    }]
}

这被发送到/api/schoolm/batch

This is sent to /api/schoolm/batch

如何将每个请求从批处理控制器内部重定向到各自的API?

How can I redirect the requests each from inside the batch controller to their respective API?

推荐答案

我的答案是从 clay's 一个>回应.我只是添加我在案例中使用的所有细节.再次谢谢你黏土!

My answer is heavily borrowed/inspired/taken from clay's response. And I am just adding all the details that I have used in my case. Thank you again clay!

首先,这是我的API的结构:

First here's how my API is structured:

/api/schoolm 是父api

然后从那里将请求重定向到子API:

And from there requests are redirected to child APIs:

/api/schoolm/students/
/api/schoolm/teachers/
/api/schoolm/subjects/
...

现在,为了支持批处理操作,我添加了另一个API,该API负责处理所有批处理事务.

Now, to support batch opertaions, I added another API which would be responsible to handle all batch transactions.

/api/schoolm/batch/

典型的批处理请求如下:

A typical batch request would look like:

{
"batchReq":[
  {
    "id":"1",
    "uri": "/api/schoolm/students/",
    "httpMethod": "GET"
  },
  {
    "id":"2",
    "uri": "/api/schoolm/teachers/",
    "httpMethod": "GET"
  }
]
}

位于/api/schoolm/batch 的控制器会验证请求(业务逻辑)并使用参考ID进行响应.

The controller at /api/schoolm/batch validates the request (business logic) and responds back with a reference ID.

var async = require('async');
var httpMocks = require('node-mocks-http');
var shortid = require('shortid');

exports.processBatch = function(batchRequests, callback){


  var batchRes = {};
  var result = {};

  var batchID = shortid.generate();
  result.batchID = batchID;

  async.setImmediate(function () {
    async.eachSeries(batchRequests, function(batchReq, callback){
      var mockRes = httpMocks.createResponse({
        eventEmitter: require('events').EventEmitter
      });

      var reqDetails = _processSubRequest(batchReq);

      _fetchResponse(reqDetails, mockRes);
      mockRes.on('end',function(){
        result[batchReq.id] = mockRes._getData();
        callback(null);
      });

    },function(err){
      console.log(result);
    });
  });

  callback("Your batch request has been accepted. Request ID - "+batchID);
}

function _processSubRequest(batchReq){
  var retValue = {};
  var request = {};
  var uriComp = batchReq.uri.split('/');
  retValue.controller = uriComp[3];

  request.method = batchReq.httpMethod;
  request.url = batchReq.uri;
  request.body = batchReq.body || {};
  request.params = batchReq.params || {};

  if(batchReq.httpMethod == 'GET'){
      if(uriComp.length > 5){
        request.params.id = uriComp[4];
      }
  }else if(batchReq.httpMethod == 'POST'){

  }else{

  }
  retValue.request = request;
  return retValue;
}

function _fetchResponse(reqDetails, mockRes){
   var mockReq  = httpMocks.createRequest(reqDetails.request);
   // proceed to fetch answer from respective controller methods.
   .......................
}

function _prepResponse(result, err, res){
  var data = {};

  if(err) {
    data["error"] = err;
    data["response"] = null;
    return data;
  }else{
    data["error"] = null;
    data["response"] = result;
    return data;
  }
}

批处理完成后,可以将其作为实时通知的一部分发送给用户,也可以存储在DB中以供以后读取.

After the batch processing completes, it can be sent to the user as part of live notification or stored in DB to be read from later.

这篇关于在NodeJS Express框架中处理批处理REST API请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆