Google Cloud Functions, Node JS 8.9.x (LTS) and KOA library - node.js

How can I use Koa library, the express replacement, in Cloud Functions?
I know KOA use all great ES2017 and make more use of Async use of JavaScript.
or it might not be needed at all working with Cloud Functions because the Firebase system won't send multiple calls to the same Cloud Function until it ends the previous one?
it unclear to me.
it know demands Node 8.x and I know the NodeJs 8.9.x, has now LTS.

Reading from cloud functions doc:
Base Image Cloud Functions uses a Debian-based execution environment
and includes contents of the gcr.io/google-appengine/nodejs Docker
image, with the Node.js runtime installed in the version, specified
above:
FROM gcr.io/google-appengine/nodejs
RUN install_node v6.14.0
To see what is included in the image, you can check its GitHub
project, or pull and inspect the image itself. Updates to the language
runtime (Node.js) are generally done automatically (unless otherwise
notified), and include any changes in the definition of the base
image.
And I saw a pull request back in November 2017, adding Nodejs v8. Here's hoping it can finally land in Google Cloud Functions 🤞🏻
UPDATE: Google Cloud Functions now support Node.js 8 and even Python!

Referring to the release notes from Google... Cloud Functions Release Notes
Node version supported is still at v6, same for firebase. You need to wait awhile before they release it in v8. Am pretty sure they will move to v8 when v6 no longer supported, but hopefully earlier...

Use babel:
index.js:
----------=
'use strict';
require('#babel/register')
require('babel-polyfill')
const http = require('http')
const createApp = require('./app/app.js')
const handle = createApp().callback()
if (process.env.IS_LOCAL_DEPLOYMENT) {
// to use same code in local server
http.createServer(handle).listen(3000)
} else {
module.exports.http = (request, response) => {
handle(request, response)
};
}
app.js:
--------
'use strict';
const Koa = require('koa')
module.exports = () => {
const app = new Koa()
app.use(......)
return app
}
package.json
------------
"scripts": {
.
.
"start": "export IS_LOCAL_DEPLOYMENT=true && node index"
.
.
}

I just saw in Cloud Functions Console editor for one of my functions that Node 8 is now a runtime option. See screenshot:

Related

can i run a node function on a react app directly

I am making a react app where I need to fetch some data using an API.
I want to deploy this app with Netlify so I cannot use a backend. So, I wrote a Firebase Cloud Function to handle the fetching. However, Google wouldn't allow third-party API requests on the free plan.
So either I have to learn using AWS or I will write a backend and deploy using another service.
Honestly, I don't want to do either. So, my question is, can I call this node function directly inside my react app if so how and is it advisable, if not are there any other alternatives?
The function is something like this:
const functions = require("firebase-functions");
const League = require("leagueapiwrapper");
require("dotenv").config();
exports.getFavorites = functions.https.onCall(async (data, context) => {
try {
const LeagueAPI = new League(process.env.API_KEY, Region.TR);
...
The only thing that actually requires node is the leagueapiwrapper package. (Obviously I will get rid of firebase related stuff).

What is the difference between Firebase SDK and Firebase SDK for cloud functions?

I don't understand the difference between Firebase SDK and Firebase SDK for cloud functions. I mean, when you run in command line "firebase init" in node.js, node modules will be downloaded to initialize a new project. But if i run "npm install firebase" different node modules appears, with similar names and different contents. So the question is: which SDK should I use to run functions and authentication in the same code? (I got a lot of require error from importing similar things and I don't know how to solve the problem).
Here is the code:
const functions = require('firebase-functions');
var firebase = require('firebase');
firebase.initializeApp();
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
} else {
// No user is signed in.
}
});
exports.delete = functions.https.onRequest((request, response) => {
console.log("delete");
});
The error says firebase.auth() is not a function, maybe for bad import and I don't know which package I need to import
npm install firebase installs modules to be used in client code that accesses Firebase products such as Firebase Authentication, Realtime Database, Firestore, and Cloud Storage.
npm install firebase-functions install modules to be used when writing backend code to deploy to Cloud Functions.
You're trying to use the Firebase Authentication client side library to listen to auth state changes in Cloud Functions. This isn't going to work, since that auth library only works on web clients.

Can't use eventbrite javascript sdk installed via npm (node js)

Eventbrite has an official sdk for their API.
According to docs, installing and using should be easy:
const eventbrite = require('eventbrite');
// Create configured Eventbrite SDK
const sdk = eventbrite({token: 'OATH_TOKEN_HERE'});
sdk.request('/users/me').then(res => {
// handle response data
});
However this does not work, I get an error "eventbrite is not a function" when trying to crate the sdk object.
In fact, if I log what's in require('eventbrite') this is all I get:
const eventbrite = require('eventbrite');
console.log(JSON.stringify(eventbrite));
// {
// "PAGE_KEY": "page",
// "CONTINUATION_KEY": "continuation"
// }
I have probably got something really wrong here, is there an extra step I need to take after installing via npm?
I figured it out, for this to work you gotta do:
const eventbrite = require('eventbrite').default;
I figure this has something to do with the way Node is managing requires in later versions (10, in my case).

Firebase Node.js admin SDK timeouts when trying to access Realtime DB

Using the Node.js admin SDK with Firebase Functions I get a timeout whenever I try to access the Realtime Database. This occurs only when testing a function locally (firebase serve --only functions,hosting) and when the default app is initialized using the functions.config().firebase.
This is a new behavior that started just a couple a days ago. However, if I try to initialize the default app with the serviceAccount.json file everything works as expected.
I'm using firebase-admin version 4.2.1 and firebase-functions version 0.5.9.
I wrote a straight forward http triggered function that fails due to timeout:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const db = admin.database();
exports.testDbConnection = functions.https.onRequest((req, res) => {
return admin.database().ref().once('value')
.then(function(snapshot) {
res.json(snapshot);
}).catch(function(error) {
res.json(error);
});
});
from the documentation
Always end an HTTP function with send(), redirect(), or end(). Otherwise, your function might to continue to run and be forcibly terminated by the system
see https://firebase.google.com/docs/functions/http-events#terminate_http_functions
This might depend on the firebase-tools version that you are using, but looks familiar to this Github issue
The solution for it is to either upgrade to the latest version of the CLI or use the workaround solution:
Go to https://cloud.google.com/console/iam-admin/serviceaccounts
Click “Create service account”, give it a name (e.g. emulator), give it the Project>Owner role.Check “Furnish a new private key”, pick “JSON”.
Save the file somewhere on your computer
Run export GOOGLE_APPLICATION_CREDENTIALS="absolute/path/to/file.json"
Run firebase serve --only functions

Async function not supported in NodeJS app deployed to Heroku

I'm trying to implement asynchronous functionality in one of my routes in a NodeJS app. It works when I run it on localhost but when deployed to heroku, an error unexpected token ( is thrown in the first line of the following code:
router.post('/post', async(req,res) => {
const data = await getData();
//do stuff
})
I'm a little confused as to why this works in one environment and not the other. Are there heroku configurations I'm missing? Do I need to explicitly add support for ES2016/2017 in Heroku?
Heroku defaults to the latest Long Term Support version of Node (which, as of writing, is v6.11.1) if you don't set a specific version.
async/await has been available in Node since v7.6, so you'll need to explicitly specify at least that version in your package.json, as documented here: https://devcenter.heroku.com/articles/nodejs-support#specifying-a-node-js-version
you can refer this link
Es6_hrku
You need to convert your ES6 to ES5 in order to make it happen on heroku.
Changes required in package.json.

Resources