NodeJS中间件:返回响应后如何继续逻辑?

问题描述

我正在使用一个基于SFTP的古老系统,该系统将上载到SFTP服务器的TXT文件替换为收据文件。因此,我正在使用Hapissh2-sftp-client模块在​​NodeJS中创建一个中间件。该流应该像这样工作:

  1. 有人用请求有效载荷调用中间件终结点
  2. 中间件进行一些验证,将有效负载保存为TXT文件,然后返回响应以确认它已收到有效负载
  3. 中间件将TXT文件传递到SFTP服务器上
  4. 中间件休眠了几分钟
  5. 中间件检查SFTP中的收据文件并根据其内容进行操作。

我设法使步骤1和3-5正常工作,但是我不知道如何执行步骤2,因此,中间件的原始调用在整个过程中一直处于活动状态,直到在步骤4中不可避免地超时

如何让代码在步骤2中返回HTTP 200,然后在中间件上继续本地逻辑?目前,我将PromisesetTimeout()一起使用,但是它与临时CronJob一起使用会更好吗?

中间件端点路由本质上是这样的(删除了不相关的部分):

module.exports = {
  method: 'POST',path: '/api/{method}/{deliveryID}',options: {
    auth: 'simple',description: 'Receive file',notes: 'Store a file based on method in first url parameter.',tags: ['api'],payload: {
      maxBytes: 1000 * 1000 * 100,// 100mb
    },validate: {
      // Only accept `text/plain`.
      headers: Joi.object()
        .keys({
          'content-type': Joi.string()
            .required()
            .valid('text/plain')
            .default('text/plain'),})
        .unkNown(),// Body cannot be empty.
      payload: Joi.any().required(),},handler: async (request,h) => {
    if (!request.payload) {
      return Boom.badRequest('Body is required');
    }

    const { deliveryID } = request.params;

    const filename = `${method}-${deliveryID}_${date.getTime()}.txt`;
    const file = `${RootPath}/backup/${method}/${date.getFullYear()}/${month}/${date.getDate()}/${filename}`;
    const uploadFolder = process.env.SFTP_HOST_FOLDER + filename;
    // eslint-disable-next-line
    const buf = new Buffer.from(request.payload,"binary");
    const payload = {
      method,filepath: file,deliveryID,};

    try {
      fs.outputFile(file,buf,'binary',function(err) {
        if (err) throw Boom.badRequest(`File saving Failed ${err}`);
      });

// Essentially,THIS is where I want the middleware to return a HTTP 200 Response to the original call,as by this point I kNow the call was valid and saved

      await sftp.connect(sftpConfig);
      const uploadPromise = await sftp.put(file,uploadFolder);

      /*
       * Now we sleep for 2 minutes and then re-connect to look for receipt files
       */
      await new Promise(r => setTimeout(r,120000));

// Currently,the original call times out while waiting here.

      // Time to re-connect
      // Re-connecting logic goes here

      // This essentially returns 200 to the original request
      return true;
    } catch (error) {
      // error handling
    } finally {
      await sftp.end();
    }
  },};

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)