从requestjs转换有效负载,然后再将其发送到客户端

时间:2018-11-24 15:26:43

标签: node.js json api express requestjs

兄弟姐妹,我正在构建一个Express API端点,该端点需要使用外部API,对键和值进行一些更改,并将结果返回给客户端。到目前为止,这是我所拥有的:

const external_endpoint = <external_api_end_point>;

app.get('/', function (req, res, next) {

  request({ url: external_endpoint}).pipe(res);
});

这将返回您直接击中external_endpoint会得到的确切有效载荷。

在将res发送给客户端之前,我是否可以做一些更改?我尝试了几件事,但没有任何效果。与对传入有效负载进行转换相关的任何想法或最佳做法?

为简单起见。可以说这是有效载荷obj.json

{
    "sad": {
        "userid": 5,
        "username": "jsmith",
        "isAdmin": true
    }
}

,我想将sad更改为happy

我知道在请求之外我可以做这样的事情:

obj = JSON.parse(JSON.stringify(obj).split('"sad":').join('"happy":'));

,但是将obj代替res将不起作用。我尝试分配此resres.body的值,但没有骰子。

谢谢您的帮助!

1 个答案:

答案 0 :(得分:1)

如果您使用的是request-promise,则只需做出一个新的响应并将其发送,或修改返回的响应:

app.get('/', function (req, res, next) {    
    request({ url: external_endpoint, json: true})
        .then(response => res.json({ happy: response.sad })))
        .catch(next);
});

(当然,您需要适当地处理错误)

如果要将其作为流处理(如果您有大量数据,这很有意义),则可以使用原始的request模块,并使用event-stream创建管道:

const es = require('event-stream');

const swapper = es.through(
    function write(data) {
        this.emit("data", data.replace("sad", "happy"));
    },
    function end() {
        this.emit("end");
    }
);

request({ url: external_endpoint})
    .pipe(es.stringify())
    .pipe(swapper)
    .pipe(es.parse())
    .pipe(res);

这里是一个测试数据流处理的沙箱:https://codesandbox.io/s/3wqx67pq6