为了尽量减少Firebase Cloud函数的冷启动时间,我如何导入一个类以在一个函数中使用?

问题描述 投票:0回答:1

如果我只有Firebase Cloud功能之一需要的模块,则此Firebase Tutorial建议将该模块仅导入需要它的功能中,以最大程度地缩短项目中所有其他功能的启动时间。

这很有意义,但是是否也可以导入一个在函数内部包含自己的一组依赖关系的类?

我只需要在两个函数中使用Bcrypt。因此,我宁愿不必为不需要的其他所有云功能加载它。

在我的应用程序中,我具有以下导入:

import BcryptTool from './classes/bcrypt'; // <--- only needed in 2 functions

这里是bcrypt.ts的内容:

import * as bcrypt from 'bcryptjs';
export default class BcryptTool {
 public static hashValue(value: string, rounds: number, callback: (error: Error, hash: string) => void) : void {
      bcrypt.hash(value, rounds, (error:any, hash:any) => {
            callback(error, hash);
      });
 }
 public static compare(value: string, dbHash: string, callback: (error: string | null, match: boolean | null) => void) {
    bcrypt.compare(value, dbHash, (err: Error, match: boolean) => {
        if(match) {
            callback(null, true);
        } else {
            callback('Invalid value match', null);
        }
    });
 }
}

最后,在我的Firebase Cloud函数index.ts中:

const express = require('express');
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const cors = require('cors')({ origin: true });
admin.initializeApp();
const util = express();
const api = express();
...
import BcryptTool from './classes/bcrypt'; // <-- when i import here, calls to its methods within my functions work as expected
...
util.use(cors);
util.post('/verify', async (request: any, response: any) => {

  // according to Doug's answer below i should be able to attempt to import here as a solution using a dynamic import expression like so:

  const BcryptTool = await import('./classes/bcrypt');

  // but the following subsequent call to .compare() fails

  BcryptTool.compare(...)

  // VS Code hinting shows an error: Property 'compare' does not exist on type 'typeof import('FULL/PATH/TO/CLASS/classes/bcrypt')'

});

api.use(cors);
api.post('/endpoint/foo', async (request: any, response: any) => {
  // I do not need Bcrypt here
});
api.post('/endpoint/bar', async (request: any, response: any) => {
  // I do not need Bcrypt here
});

这不可能吗?我只是做错了吗?

非常感谢任何帮助。

UPDATE我没有正确导入该类。 here

概述了解决方案的原因
node.js typescript firebase google-cloud-functions
1个回答
0
投票

当然,您可以在TypeScript代码中的任何位置async (dynamic) import。导入的符号将在您导入该符号的范围内可见,而在其他任何地方都不可见。模块包含什么都没有关系。

© www.soinside.com 2019 - 2024. All rights reserved.