How to detect if environment is development or production with Firebase Cloud Functions?

假如想象 提交于 2020-12-08 06:53:05

问题


How can I detect if my server environment is development or production with Firebase Cloud Functions?

I need something like this:

if(process.env.NODE_ENV === 'development'){

   //DO STUFF SPECIFIC TO DEV ENVIRONMENT

}
else if(process.env.NODE_ENV === 'production'){

   //DO STUFF SPECIFIC TO PRODUCTION ENVIRONMENT

}

回答1:


process.env.FUNCTIONS_EMULATOR

At process.env, on firebase functions projects, there is a boolean variable called FUNCTIONS_EMULATOR, which indicates if the process is running on an emulator or on server.

this is enough to determine if environment is dev or production.

process.env.FUNCTIONS_EMULATOR === true

Obs: In some environments the variable might be a String 'true' instead of Boolean true




回答2:


you can rely on process.env

as of July 28, 2020 and package.json

"dependencies": {
    "firebase-admin": "^8.10.0",
    "firebase-functions": "^3.6.1"
},

if you start your app with firebase

firebase emulators:start

thenprocess.env will have properties like

"FUNCTIONS_EMULATOR": "true",
"FIRESTORE_EMULATOR_HOST": "0.0.0.0:5002",
"PUBSUB_EMULATOR_HOST": "localhost:8085"

if you start your app with firebase

firebase emulators:start --only functions

thenprocess.env will have properties like

"FUNCTIONS_EMULATOR": "true",

USECASE

based on process.env you can write firebase.function to prepopulate your firestore emulator (not production firestore)!

code sample

export const prepopulateFirestoreEmulator = functions.https.onRequest(
  (request, response) => {
    if (process.env.FUNCTIONS_EMULATOR && process.env.FIRESTORE_EMULATOR_HOST) {
      // TODO: prepopulate firestore emulator from 'yourproject/src/sample_data.json
      response.send('Prepopulated firestore with sample_data.json!');
    } else {
      response.send(
        "Do not populate production firestore with sample_data.json"
      );
    }
  }
);



回答3:


All projects are just projects, except for how you designate their purpose. Since there is no way for Cloud Functions to know the difference between dev and prod, you need to examine the name of the project, since that's the only thing that changes in the environment. Use process.env.GCLOUD_PROJECT from the automatically populated env vars.



来源:https://stackoverflow.com/questions/53185426/how-to-detect-if-environment-is-development-or-production-with-firebase-cloud-fu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!