Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Cloud Functions include private library

I'm looking to write a custom library in node and I'd like to include that with my Cloud Functions. Since this is shared code, I'd like to be able to use it across all my Cloud Functions.

What's the best way to write a library of shared code and have that accessed by multiple Cloud Functions.

For example, say I have two Cloud Functions, functionA and functionB.

I have a node javascript file called "common.js" that has a javascript function that I'd like to expose to both functionA and functionB.

exports.common = {
    log: function(message) {
        console.log('COMMON: ' + message);
    }
};

So in functionA I'd like to require this file and call "common.log('test');".

I see this as the most basic of questions but I honestly can't find an answer anywhere.

Any help would be most appreciated. This is literally the ONLY thing preventing me from using GCF as the way I develop code now and into the future!

like image 802
Encoder Avatar asked Mar 02 '17 08:03

Encoder


People also ask

What is the difference between cloud run and cloud function?

Cloud Functions lets you deploy snippets of code (functions) written in a limited set of programming languages, while Cloud Run lets you deploy container images using the programming language of your choice.

Are Firebase Cloud Functions public?

By default, functions are deployed as private, and require such a credential, although it is possible to deploy a function as public, that is, not requiring one.

What is Google Cloud functions used for?

Google Cloud Functions is a serverless execution environment for building and connecting cloud services. With Cloud Functions you write simple, single-purpose functions that are attached to events emitted from your cloud infrastructure and services. Your function is triggered when an event being watched is fired.


1 Answers

If you use the gcloud command line tool to deploy your function it will upload all1 the files in your local directory, so any normal Node.js way of doing an include/require should work.

In Node.js, writing require('./lib/common') will include the common.js file in the lib subdirectory. Since your file exports an object named common you can reference it directly off the returned object from require. See below.

File layout

./
../
index.js
lib/common.js

index.js

// common.js exports a 'common' object, so reference that directly.
var common = require('./lib/common').common;

exports.helloWorld = function helloWorld(req, res) {
  common.log('An HTTP request has been made!');
  res.status(200);
}

Deploy

$ gcloud functions deploy helloWorld --trigger-http

Note

1 Currently gcloud won't upload npm_modules/ directory unless you specify --include-ignored-files (see gcloud docs)

like image 173
Bret McGowen Avatar answered Oct 12 '22 09:10

Bret McGowen