带有 Kafka 后端的 NodeJS API
NodeJS API with Kafka back-end
我想构建一个基于 API 的 NodeJS,它以 pub-sub 范式为后盾,例如卡夫卡。这是我想要做的事情的框架。
const express = require('express')
const serverApp = express()
serverApp.get('/book/:bookId', (req, res) => {
producer.send(JSON.stringify({
action: 'get',
message: req.params.bookId
}))
consumer.on('message', (data) => {
res.status(200).send(JSON.parse(data))
})
})
使用上面的选项,第一次调用有效,但后续调用一直失败并显示 ERR_HTTP_HEADERS_SENT
。
将 consumer.on
保持在 serverApp.get
之外需要协调 req
和 res
。
如何实现这样的 API?
例如骨架
const express = require('express')
const serverApp = express()
const responses = Object.create(null);
consumer.on('message', (data) => {
const result = JSON.parse(data)
const res = responses[result.replyId]
res.status(200).send(result)
});
serverApp.get('/book/:bookId', (req, res) => {
const replyId = Math.random().toString(36).substr(2);
responses[replyId] = res;
producer.send(JSON.stringify({
action: 'get',
replyId,
message: req.params.bookId
}))
})
我想构建一个基于 API 的 NodeJS,它以 pub-sub 范式为后盾,例如卡夫卡。这是我想要做的事情的框架。
const express = require('express')
const serverApp = express()
serverApp.get('/book/:bookId', (req, res) => {
producer.send(JSON.stringify({
action: 'get',
message: req.params.bookId
}))
consumer.on('message', (data) => {
res.status(200).send(JSON.parse(data))
})
})
使用上面的选项,第一次调用有效,但后续调用一直失败并显示 ERR_HTTP_HEADERS_SENT
。
将 consumer.on
保持在 serverApp.get
之外需要协调 req
和 res
。
如何实现这样的 API?
例如骨架
const express = require('express')
const serverApp = express()
const responses = Object.create(null);
consumer.on('message', (data) => {
const result = JSON.parse(data)
const res = responses[result.replyId]
res.status(200).send(result)
});
serverApp.get('/book/:bookId', (req, res) => {
const replyId = Math.random().toString(36).substr(2);
responses[replyId] = res;
producer.send(JSON.stringify({
action: 'get',
replyId,
message: req.params.bookId
}))
})