Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloud Functions for Firebase Async Await style

Looks like Cloud Functions does not support Async-Await notation. Is there a way I could use Babel until they do or is it recommended to use promises?

My current function that sits on Node is like so:

exports.getToken = async (req, res) => {
  //1. Generate token from Braintree
  const result = await gateway.clientToken.generate();

  //2. Return the client token
  res.json(result.clientToken);
};
like image 277
Brandon Avatar asked Jun 08 '17 19:06

Brandon


3 Answers

Cloud Functions runs the LTS version of node.js, which according to the documentation is 6.14.0 at this moment in time. node 6.x supports EcmaScript 6, which does not include async/await.

However, you can write your code in TypeScript and have that transpiled down to ES5/ES6, which will effectively convert the use of async/await into promises. A web search suggests that perhaps this plugin can be used to help Babel with similar transpiling.

It's worth noting that the Firebase CLI now allow you to initialize a new Cloud Functions project with native TypeScript support, which is what the Firebase team is currently recommending to developers.

If you don't want to use TypeScript, you can now also choose node 8 (which is currently in beta, and does support async/await for plain JavaScript) as a deployment target. You can follow the documentation to edit your package.json to indicates that your functions should be deployed to node 8.

like image 116
Doug Stevenson Avatar answered Nov 13 '22 17:11

Doug Stevenson


Now you can use Node.js version 8 by adding this in your functions/package.json:

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

Example: https://github.com/firebase/functions-samples/blob/Node-8/authenticated-json-api/functions/package.json

like image 39
l2aelba Avatar answered Nov 13 '22 15:11

l2aelba


Instead of transpile TypeScript, I have transpiled my javascript after follow this very nice post and take a look at this repository

Basically you can do:

npm install -g @babel/cli @babel/core @babel/preset-env
  • UPDATE:
    I'm having troubles with version "7.0.0-beta.51" of babel. "7.0.0-beta.44" still ok.
    Switch to stable version 6

    npm install --save-dev babel-cli babel-preset-env

Create the file .babelrc inside your project folder

{
  "presets": [
    ["@babel/env", {
      "targets": {
        "node": "6.11.5"
      }
    }]
  ]
}

Move your "functions" folder to "firebaseFunctions" folder and then run

babel firebaseFunctions --out-dir functions --copy-files --ignore firebaseFunctions/node_modules

Or run this command for each files you want to transpile

babel originalfile.js --out-file transpiledfile.js
like image 7
rma Avatar answered Nov 13 '22 16:11

rma