我想为Firebase创建多个云功能,并从一个项目同时部署它们。我还想将每个函数分离到一个单独的文件中。目前,我可以创建多个函数,如果我把它们都放在index.js,如:

exports.foo = functions.database.ref('/foo').onWrite(event => {
    ...
});

exports.bar = functions.database.ref('/bar').onWrite(event => {
    ...
});

然而,我想把foo和酒吧在单独的文件。我试了一下:

/functions
|--index.js (blank)
|--foo.js
|--bar.js
|--package.json

foo.js在哪里

exports.foo = functions.database.ref('/foo').onWrite(event => {
    ...
});

bar.js是

exports.bar = functions.database.ref('/bar').onWrite(event => {
    ...
});

有没有一种方法可以在不把所有函数都放在index.js中的情况下实现这一点?


当前回答

更新:Typescript现在完全支持,所以不需要下面的恶作剧。只需使用firebase cli


以下是我个人是如何使用typescript的:

/functions
   |--src
      |--index.ts
      |--http-functions.ts
      |--main.js
      |--db.ts
   |--package.json
   |--tsconfig.json

在此之前,我先提出两点警告:

进口/出口的顺序在index.ts中很重要 db必须是一个单独的文件

第二点,我不知道为什么。其次,你应该完全尊重我的index, main和db的配置(至少要尝试一下)。

索引。Ts:与出口有关。我觉得让索引更干净。贸易部门负责出口。

// main must be before functions
export * from './main';
export * from "./http-functions";

主要。ts:处理初始化。

import { config } from 'firebase-functions';
import { initializeApp } from 'firebase-admin';

initializeApp(config().firebase);
export * from "firebase-functions";

db。Ts:只是重新导出数据库,所以它的名字比database()短。

import { database } from "firebase-admin";

export const db = database();

http-functions.ts

// db must be imported like this
import { db } from './db';
// you can now import everything from index. 
import { https } from './index';  
// or (both work)
// import { https } from 'firebase-functions';

export let newComment = https.onRequest(createComment);

export async function createComment(req: any, res: any){
    db.ref('comments').push(req.body.comment);
    res.send(req.body.comment);
}

其他回答

Node 8 LTS现在可以与Cloud/Firebase函数一起使用,您可以使用扩展操作符执行以下操作:

/ package.json

"engines": {
  "node": "8"
},

/ index.js

const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();

module.exports = {
  ...require("./lib/foo.js"),
  // ...require("./lib/bar.js") // add as many as you like
};

/lib/foo.js

const functions = require("firebase-functions");
const admin = require("firebase-admin");

exports.fooHandler = functions.database
  .ref("/food/{id}")
  .onCreate((snap, context) => {
    let id = context.params["id"];

    return admin
      .database()
      .ref(`/bar/${id}`)
      .set(true);
  });

我使用一个普通的JS引导加载器来自动包含我想使用的所有函数。

├── /functions
│   ├── /test/
│   │   ├── testA.js
│   │   └── testB.js
│   ├── index.js
│   └── package.json

index.js(引导)

/**
 * The bootloader reads all directories (single level, NOT recursively)
 * to include all known functions.
 */
const functions = require('firebase-functions');
const fs = require('fs')
const path = require('path')

fs.readdirSync(process.cwd()).forEach(location => {
  if (!location.startsWith('.')) {
    location = path.resolve(location)

    if (fs.statSync(location).isDirectory() && path.dirname(location).toLowerCase() !== 'node_modules') {
      fs.readdirSync(location).forEach(filepath => {
        filepath = path.join(location, filepath)

        if (fs.statSync(filepath).isFile() && path.extname(filepath).toLowerCase() === '.js') {
          Object.assign(exports, require(filepath))
        }
      })
    }
  }
})

这个例子index.js文件只在根目录中自动包含目录。它可以扩展到walk目录,honor .gitignore等。不过这对我来说已经足够了。

有了索引文件,添加新函数就很简单了。

/测试/ testA.js

const functions = require('firebase-functions');

exports.helloWorld = functions.https.onRequest((request, response) => {
 response.send("Hello from Firebase!");
});

/测试/ testB.js

const functions = require('firebase-functions');

exports.helloWorld2 = functions.https.onRequest((request, response) => {
 response.send("Hello again, from Firebase!");
});

NPM运行服务产生:

λ ~/Workspace/Ventures/Author.io/Firebase/functions/ npm run serve

> functions@ serve /Users/cbutler/Workspace/Ventures/Author.io/Firebase/functions
> firebase serve --only functions


=== Serving from '/Users/cbutler/Workspace/Ventures/Author.io/Firebase'...

i  functions: Preparing to emulate functions.
Warning: You're using Node.js v9.3.0 but Google Cloud Functions only supports v6.11.5.
✔  functions: helloWorld: http://localhost:5000/authorio-ecorventures/us-central1/helloWorld
✔  functions: helloWorld2: http://localhost:5000/authorio-ecorventures/us-central1/helloWorld2

这个工作流程基本上就是“编写并运行”,而不必在每次添加/修改/删除新函数/文件时修改index.js文件。

这种格式允许您的入口点查找其他函数文件,并自动导出每个文件中的每个函数。

主要入口脚本

找到functions文件夹中的所有.js文件,并导出从每个文件中导出的每个函数。

const fs = require('fs'); const path = require('path'); // Folder where all your individual Cloud Functions files are located. const FUNCTIONS_FOLDER = './scFunctions'; fs.readdirSync(path.resolve(__dirname, FUNCTIONS_FOLDER)).forEach(file => { // list files in the folder. if(file.endsWith('.js')) { const fileBaseName = file.slice(0, -3); // Remove the '.js' extension const thisFunction = require(`${FUNCTIONS_FOLDER}/${fileBaseName}`); for(var i in thisFunction) { exports[i] = thisFunction[i]; } } });

从一个文件导出多个函数

Const functions = require('firebase-functions'); Const query = functions.https。onRequest((req, res) => { Let query = req.query.q; res.send ({ “You searching For”:查询 }); }); const searchTest = functions.https。onRequest((req, res) => { res.send ({ "searchTest": "你好!" }); }); 模块。出口= { 查询 searchTest }

HTTP可访问端点有适当的命名

✔功能:查询:http://localhost:5001/PROJECT-NAME/us-central1/query function: helloWorlds: http://localhost:5001/PROJECT-NAME/us-central1/helloWorlds ✔功能:searchTest: http://localhost:5001/PROJECT-NAME/us-central1/searchTest

一个文件

如果你只有几个额外的文件(例如只有一个),你可以使用:

Const your_functions = require('./path_to_your_functions'); For (var I in your_functions) { export [i] = your_functions[i]; }

以上的答案为我指明了正确的方向,只是没有一个真正适合我。下面是一个工作原型,一个onCall, onRequest和数据库触发器的例子

foo.js - 随叫随到,随叫随到。

exports.handler = async function(data, context, admin) {
    // const database = admin.database();
    // const firestore = admin.firestore();
    //...
};

bar.js - onRequest

exports.handler = async function(req, res, admin) {
    // const database = admin.database();
    // const firestore = admin.firestore();
    //...
};

jar.js - trigger/document/onCreate .js

exports.handler = async function(snapshot, context, admin) {
    // const database = admin.database();
    // const firestore = admin.firestore();
    //...
};

index.js

//导入firebase管理SDK依赖项

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase); 

// import functions
const foo = require("./foo");
const bar = require("./bar");
const jar = require("./jar");

// onCall for foo.js
exports.foo = functions.https.onCall((data, context) => {
    return foo.handler(data, context, admin);
});

// onRequest for bar.js
exports.bar = functions.https.onRequest((req, res) => {
    return bar.handler(req, res, admin);
});

// document trigger for jar.js
exports.jar = functions.firestore
  .document("parentCollection/{parentCollectionId}")
  .onCreate((snapshot, context) => {
    return jar.handler(snapshot, context, admin);
});

注意:你也可以创建一个子文件夹来存放你的各个函数

在我努力实现@zaidfazil的解决方案时,我想出了以下方法(使用JavaScript,而不是TypeScript)。

multi.js

exports.onQuestionMultiCreate = functions.database
  .ref("/questions-multi/{questionId}")
  .onCreate(async (snapshot, context) => {
   ...
    }
  });

trueFalse.js

exports.onQuestionTrueFalseCreate = functions.database
  .ref("/questions-truefalse/{questionId}")
  .onCreate(async (snapshot, context) => {
   ...
    }
  });

index.js


const multi = require("./multi");
const trueFalse = require("./trueFalse");

module.exports = {
  ...multi,
  ...trueFalse