【发布时间】:2020-06-30 20:30:01
【问题描述】:
NodeJS + Express。我正在努力实现以下目标:
- 客户端使用以下 JSON 文档
data={text: "I love Stackoverflow", shouldPreprocess: <true or false>}发送 post 请求; - 我需要调用外部 WebSocket 服务对文本进行情感分析并将结果返回为 JSON,例如{sentiment: '正面'};
- 但是,如果 shouldPreprocess 为 true,我应该先调用另一个预处理服务;
问题:
- 我不确定执行此操作的正确方法是什么,但这里有两次尝试。我觉得他们俩都很老套。
- 我不确定如何处理来自客户端的无效输入。详情如下。
router.post('/analyse', function (req, res, next) {
const data = req.body;
if (typeof data.text === 'undefined' || typeof data.shouldPreprocess === 'undefined') {
return next(new Error('Please provide text and flag'));
}
analyseSentiment(data.text, data.shouldPreprocess)
.then(doc => res.json(doc))
.catch(err => next(err));
});
function analyseSentiment(text, shouldPreprocess) {
let promise;
if (shouldPreprocess === true) {
textP = preprocess(text);
} else promise = new Promise((res, req) => res(text));
return textP
.then(text => axios.post(<URL to sentiment analyser>, text))
function preprocess(text) {
const ws = WebSocket(<URL of preprocessor>);
// But what if I wanted to check for some property of text here and throw an error
// that gets sent to the client, just as I do in the main function, i.e. in router.post above?
ws.on('open', () => ws.send(text));
return new Promise((res, rej) => ws.on('message', preprocText => res(preprocText)));
}
所以这是第一种方式。感觉很奇怪,因为我在 analyseSentiment 中创建了一个只返回文本的无用承诺,这样我就有了一种统一的方式来处理预处理和非预处理场景。另请参阅上面函数preprocess 中的评论中的问题。
第二种方法是在router.post 中做所有事情,例如:
router.post('/analyse', function (req, res, next) {
const data = req.body;
if (typeof data.text === 'undefined' || typeof data.shouldPreprocess === 'undefined') {
return next(new Error('Please provide text and flag'));
}
if (data.shouldPreprocess) {
preprocess(data.text)
.then(text => axios.post(<URL to sentiment analyser>, text)))
.then(doc => res.json(doc))
.catch(err => next(err));
} else {
axios.post(<URL to sentiment analyser>, text)
.then(doc => res.json(doc))
.catch(err => next(err));
}
});
但是当然有重复的代码片段。
谢谢!
【问题讨论】:
标签: javascript node.js express websocket promise