【发布时间】:2020-03-12 14:19:33
【问题描述】:
在 Firebase Cloud Function 项目中...
我的src 目录的根目录下有以下打字稿文件,就在我的主要index.ts 文件旁边,该文件导入一个依赖项并导出一个包含2 个方法的类。这个文件的标题是bcrypt.class.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 文件中,我导入了这个类并在我的一个函数中调用它的“比较”方法,没有问题,这可以按预期工作:
'use strict';
const express = require('express');
const functions = require('firebase-functions');
const cors = require('cors')({ origin: true });
const admin = require('firebase-admin');
admin.initializeApp();
const api = express();
import BcryptTool from './bcrypt.class'; // <-- i import the class here
// and use it in a function
api.use(cors);
api.post('/credentials', async (request: any, response: any) => {
BcryptTool.compare(...) // <--- calls to this method succeed without issue
});
问题
我的应用程序包含许多函数,但我只需要上面提到的类在其中一个,所以为了优化我所有其他函数的冷启动时间,我尝试在需要的函数中动态导入这个类它而不是如上所述将其导入全局范围。这不起作用,我不知道为什么:
'use strict';
const express = require('express');
const functions = require('firebase-functions');
const cors = require('cors')({ origin: true });
const admin = require('firebase-admin');
admin.initializeApp();
const api = express();
api.use(cors);
api.post('/credentials', async (request: any, response: any) => {
const BcryptTool = await import('./bcrypt.class'); // <-- when i attempt to import here instead
BcryptTool.compare(...) // <--- subsequent calls to this method fail
// Additionally, VS Code hinting displays a warning: Property 'compare' does not exist on type 'typeof import('FULL/PATH/TO/MY/bcrypt.class')'
});
我的课程没有正确编写或导出吗?
我没有在我的云函数中正确导入类吗?
【问题讨论】:
标签: node.js typescript firebase google-cloud-functions