gpt4 book ai didi

json - 通过 Hapi 将响应从 MongoDB 流式传输到客户端

转载 作者:可可西里 更新时间:2023-11-01 09:17:43 24 4
gpt4 key购买 nike

通过 Hapi 将 MongoDB 查询响应流式传输到客户端的最佳方法是什么?我见过一些带有 http 或请求的示例,但没有看到 hapi。

问题是我在客户端获得了串联和字符串化的 JSON 对象,但我无法对结果调用 JSON.parse,因为它一起不是有效的 JSON。

我见过的一些解决方案建议在发送到客户端之前在服务器端进行连接,但这似乎违背了流的值(value)。

例如:

const Hapi = require('hapi'),
MongoClient = require('mongodb').MongoClient,
Readable = require('stream').Readable;

// Connection url
const url = 'mongodb://localhost:27017/test';

// Create a server with a host and port
const server = new Hapi.Server();
server.connection({
host: 'localhost',
port: 8000
});

// Add the route
server.route({
method: 'GET',
path: '/stream',
handler: function (request, reply) {

let docs = [{ a: 1, b: 1 }, { a: 2, b: 2 }, { a: 3, b: 3 }, { a: 4, b: 4 }];

// Connect using MongoClient
MongoClient.connect(url, (err, db) => {
// Create a collection we want to drop later
const col = db.collection('stream_example');

// Insert documents into collection
col.insertMany(docs, { w: 1 }, function (err) {
if (err) return console.log(err);

// Peform a find to get a cursor
const stream = col.find()
.stream({
transform: function (doc) {
return JSON.stringify(doc);
}
});

reply(new Readable().wrap(stream));
});
});
}
});

// Start the server
server.start(err => {
if (err) {
throw err;
}
console.log('Server running at:', server.info.uri);
});

返回以下内容的响应结果:

"{"_id":"57b0b99d681bb97a9321f03e","a":1,"b":1}{"_id":"57b0b99d681bb97a9321f03f","a":2,"b":2}{"_id":"57b0b99d681bb97a9321f040","a":3,"b":3}{"_id":"57b0b99d681bb97a9321f041","a":4,"b":4}"

这不是有效的 JSON,无法解析。

我已经尝试将此流通过管道传输到事件流模块的 .join('\n') 流中以添加换行符,同时还在前后推送字符串“[”和“]”以构建字符串化的 JSON 数组,但尚未成功。无论如何,这感觉太hacky了。

有没有更好的办法?

最佳答案

必须使用流转换发送有效的 JSON。

基本上你必须:

  1. '['开始流

  2. 然后附加字符串化的JSON对象

  3. 在每个对象后添加','

  4. ']'结束流

因此在流中接收到的最终结果将是有效的 JSON,例如

[
{'key': 'value'},
{'key': 'value'},
]

一些解决方案:

http://andyfiedler.com/2017/01/mongodb-stream-to-hapi

https://github.com/nlindley/hapi-mongo-stream

https://github.com/dominictarr/JSONStream

关于json - 通过 Hapi 将响应从 MongoDB 流式传输到客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38945436/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com