如果在本地环境下Firestore云函数无法正常工作,可能的原因是缺少必要的配置或依赖项。以下是解决方法的代码示例:
const admin = require('firebase-admin');
admin.initializeApp({
credential: admin.credential.applicationDefault(),
databaseURL: 'https://.firebaseio.com'
});
const firestore = admin.firestore();
{
"dependencies": {
"firebase-admin": "^9.2.0"
}
}
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
admin.firestore().settings({
host: 'localhost',
port: 8080,
ssl: false
});
const firestore = admin.firestore();
exports.myFunction = functions.firestore.document('collection/{docId}').onCreate((snap, context) => {
// 在这里添加你的代码逻辑
});
const functions = require('firebase-functions');
const test = require('firebase-functions-test')();
const myFunction = require('../src/index');
describe('myFunction', () => {
beforeEach(() => {
// 在每个测试之前,模拟函数的上下文
test.firestore.makeDocumentSnapshot({ data: 'test' }, 'collection/docId');
});
afterEach(() => {
// 在每个测试之后,重置模拟函数的上下文
test.firestore.cleanup();
});
it('should do something', () => {
// 模拟函数的触发器事件
const snap = test.firestore.makeDocumentSnapshot({ data: 'test' }, 'collection/docId');
const context = { params: { docId: 'docId' } };
// 调用函数
const result = myFunction.onCreate(snap, context);
// 断言函数的返回值或行为
// ...
});
});
通过以上解决方法的代码示例,你可以重新配置和调试本地环境下的Firestore云函数,以确保其正常工作。