在 Node.js 中,是否可以异步 运行 中间件功能?

In Node.js, is it possible to run a middleware function asynchronously?

我已经构建了一个中间件函数来验证用户访问令牌 (JWT) ...如果 JWT 已过期,我会自动从用户的刷新令牌创建一个新的访问令牌(如果它也有效,当然)。

我想在某些时候,如果我有足够的用户,授权可能会成为瓶颈。我想确保这些函数是 运行 异步的(例如通过 UV 线程池)。

这可能吗,或者我什至需要担心这个?

附录:

这是我在中间件函数中使用的解密例程。我也在使用 jsonwebtoken。

'use strict';

const cryptoAsync = require('@ronomon/crypto-async');
const crypto = require('crypto');
const util = require('util');

class AES {
    constructor(key, iv, bitSize) {
      // supported stream ciphers:
      // aes-256-ctr (keySize=32, ivSize=16)
      // aes-192-ctr (keySize=24, ivSize=16)
      // aes-128-ctr (keySize=16, ivSize=16)

      if (!bitSize) bitSize = 128;

      if (bitSize !== 256 && bitSize !== 192 && bitSize !== 128) {
        throw new Error('AES requires a bitsize of 256, 192, or 128.');
      }

      if (!key || key.length !== bitSize/8) throw new Error(`A ${bitSize/8}-byte/${bitSize}-bit key is required.`);

      if (!iv || iv.length !== 16) throw new Error('A 16-byte/128-bit initialization vector is required.');

      this.algo = `aes-${bitSize}-ctr`;
      this.key = key;
      this.iv = iv;

      console.log(`Using the ${this.algo} algorithm ...`);
    }
 
    async encrypt(dataAsUtf8) {
        const cipherText = await util.promisify(cryptoAsync.cipher)(this.algo, 1, this.key, this.iv, Buffer.from(dataAsUtf8, 'utf8'));

        return cipherText.toString('hex');
    }

    async decrypt(dataAsHex) {
    if (!Buffer.isEncoding('hex')) throw new Error('Input must be in HEX format.');

        const cipherText = await util.promisify(cryptoAsync.cipher)(this.algo, 0, this.key, this.iv, Buffer.from(dataAsHex, 'hex'));

        return cipherText.toString('utf8');
    }

    static randomBytes = async bytes => {
        const bytesAsBuffer = await util.promisify(crypto.randomBytes)(bytes);

    return bytesAsBuffer;
    }
}

module.exports = AES;

实际上很难编写在 Node 中长时间阻塞主线程的代码,除非您正在做一些非常繁重的工作,例如生成非常大的报告等。通过 JWT 令牌的授权是完全轻量级的,不会有问题,我几乎可以保证这一点。如果计划如此,您将不需要将此类工作推到单独的线程上。