Integrate Cloud Functions for Firebase with Braintree - node.js

I'm trying to see if it's possible to integrate Cloud Functions for Firebase with Braintree. I created a project for Cloud Functions according to the docs.
In the project directory I ran: npm install braintree.
I modified index.js for testing purposes to be the following:
const functions = require('firebase-functions');
var braintree = require("braintree");
var gateway = braintree.connect({
environment:
braintree.Environment.Sandbox,
merchantId: "useYourMerchantId",
publicKey: "useYourPublicKey",
privateKey: "useYourPrivateKey"
});
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-
functions
//
exports.helloWorld = functions.https.onRequest((request, response) => {
response.send("Hello from Firebase!");
//gateway.clientToken.generate({}, function (err, response) {
//response.send(response.clientToken);
//});
});
When I tried to deploy this test function I got the error
Error parsing triggers: Cannot find module 'braintree'
I'm new to Firebase, Cloud Functions, and node.js and would appreciate any input on how to import Braintree to Firebase Functions project.

It looks like Cloud Functions for Firebase is not picking up the braintree module. Like most Node.js environments, Cloud Functions reads the dependencies from package.json. When you install a module with npm you can tell it to also write it to package.json by adding --save to the command line. So:
npm install braintree --save

You have the Node.js package braintree missing.
Your Firebase project has a directory called functions.
In the terminal, go to the functions directory by $ cd {your project dir}/functions
And then npm i braintree --save.
I hope that it helps you.

change current directory to functions:- cd functions
then install braintree in that folder using npm: - npm i braintree
then import braintree : - var braintree = require('braintree');
now everything should work fine.
Note:- if you have not enabled payment in firebase, it will though 'unexpectedError' in the http response.

Related

How to run an Express API via Firebase Cloud Functions locally?

I have a standard REST API using Express, exposed via a Firebase Cloud Function.
const api = express()
api.get('/test', (req, res) => res.status(403).json({ "REASON": "UNAUTHORIZED" }))
exports.api = functions.https.onRequest(api)
Remote
When I deploy it and send GET https://<remote>/api/test via Postman I get 403 { "REASON": "UNAUTHORIZED" } as expected.
Local
When I run firebase emulators:start --only functions to serve these functions locally and test them, I do see functions: HTTP trigger initialized at http://localhost:5001/.../api in my terminal, but when I send GET http://localhost:5001/.../api/test via Postman I get 200 Not Found.
Am I missing something?
It was indeed a defect in the Firebase CLI, it seems to be fixed in the latest version (7.13.1)
Installed the latest version using: npm install -g firebase-tools#latest
Note: it did require me to update to compatible version of firebase-functions and firebase-admin as well.

firebase.database() is not a function on local node

I'm running a simple node app in my local machine and I need to connect to firebase realtime database.
I installed firebase via npm:
npm install firebase --save
Then I initialize the app:
var firebase = require("firebase");
var config = {
apiKey: "api-key",
authDomain: "my-app-database.firebaseapp.com",
databaseURL: "https://my-url.firebaseio.com",
storageBucket: "my-app-database.appspot.com",
};
firebase.initializeApp(config);
var myRef = firebase.database().ref("collection").on("value", (snap) => {
// do something with the data
});
Then I get the error that database is not a function. I check firebase.database and is undefined, also so are firebase.auth and firebase.storage.
I followed all the steps in the docs, but I don't see anything that could be causing this.
Goodness gracious... It was as simple as requiring the other packages in the file, like this:
// firebase
const firebase = require("firebase");
// get database, auth and storage
require("firebase/auth");
require("firebase/storage");
require("firebase/database");
Nowhere in the docs or reference says that. I thought about going back a version, perhaps 4.12.x, so I went to the npm page to see the previous versions and install one of those and try, when I found this:
https://www.npmjs.com/package/firebase#include-only-the-features-you-need
Just scroll down where they mention using npm packages or Typescript and you'll find the answer.
Shout out to the Firebase team, this information can't be just in the npm page and not in the docs, getting started guides or the github repo. Not a lot of people goes to the npm page of a package for information and I went there to check previous versions, so I kind of stumbled upon it.

Serverless Framework with AWS Lambda error "Cannot find module"

I'm trying to use the Serverless Framework to create a Lambda function that uses open weather NPM module. However, I'm getting the following exception, but my node_modules contain the specific library.
I have managed to run the sample, (https://github.com/serverless/examples/tree/master/aws-node-rest-api-with-dynamodb) successfully, now hacking to add node module to integrate open weather API.
Endpoint response body before transformations: {"errorMessage":"Cannot find module 'Openweather-Node'","errorType":"Error","stackTrace":["Module.require (module.js:353:17)","require (internal/module.js:12:17)","Object.<anonymous> (/var/task/todos/weather.js:4:17)","Module._compile (module.js:409:26)","Object.Module._extensions..js
My code
'use strict';
const AWS = require('aws-sdk'); // eslint-disable-line import/no-extraneous-dependencies
var weather = require('Openweather-Node');
const dynamoDb = new AWS.DynamoDB.DocumentClient();
module.exports.weather = (event, context, callback) => {
const params = {
TableName: process.env.DYNAMODB_TABLE,
Key: {
id: event.pathParameters.id,
},
};
weather.setAPPID("mykey");
//set the culture
weather.setCulture("fr");
//set the forecast type
weather.setForecastType("daily");
const response = {
statusCode: 200,
body: "{test response}",
};
callback(null, response);
};
Did you npm install in your working directory before doing your serverless deploy? The aws-sdk node module is available to all lambda functions, but for all other node dependencies you must install them so they will be packaged with your lambda when you deploy.
You may find this issue on the serverless repository helpful (https://github.com/serverless/serverless/issues/948).
I fixed this error when in package.json I moved everything from devDependencies to dependencies.
Cheers
I don't if it applies to this answer but in case someone just needs a brain refresh I forgot to export my handler and was exporting the file with was looking for a default export that didn't exist...
changed from this...
handler: foldername/exports
to this...
handler: foldername/exports.handler
I have the same problem with serverless framework to deploy multiple lambda functions. I fixed by the following steps
Whatever you keep the path at the handler like handler: foldername/exports.handler
Name the file inside the folder as exports.js(whatever you name the handler)
run serverless deploy
This should solve your problem
I went to cloud watch and looked for the missing packages
Then npm i "missing package" and do sls deploy
The missing packages are needed in the dependencies in my case there was some on the devDepencies and another missing
You need to do the package deployment in case you have external dependencies.
Please see this answer
AWS Node JS with Request
Reference
http://docs.aws.amazon.com/lambda/latest/dg/nodejs-create-deployment-pkg.html
In several cases, don't forget to check global serverless installation.
mine solved by reinstalling:
npm install -g serverless
In my case, what worked was switching to node 10 (via nvm). I was using a newer version of node (v15.14.0) than was probably supported by the packages.
My case was configuring params for creating an AWS lambda function. The right string for a handler was (last row):
Resources:
StringResourceName:
Type: 'AWS::Serverless::Function'
Properties:
Handler: myFileName.handler
Where myFileName is the name of a file that I use as the zip file.
You have issue with your ts files, as serverless-offline plugin cannot find equivalent js file it throws error module not found.
There is a work around to it to install (serverless-plugin-typescript) . Only issue with the plugin is that it creates a new .build/.dist folder with transpiled js files
I was doing some stupidity. But still wanted to put here so any beginner like me should not struggle for it. I copied the serverless.xml from example where handler value was
handler: index.handler
But my index.js was in src folder. Hence I was getting file not found. It worked after I change the handler value to
handler: src/index.handler
For anyone developing python lambda functions with serverless-offline and using a virtual environment during local development, deactivate your environment, delete it entirely, and recreate it. Install all python requirements and try again. This worked for me.
For me, the issue was that the handler file name contained a dot.
main-handler.graphql.js caused serverless "Error: Cannot find module 'main'.
when I changed the file to main-handler-graphql.js everything worked.

Firebase Node.js SDK unauthenticated access

I am trying to access Realtime Database using the new feature introduced with 3.1.0 release: "The Node.js SDK now supports unauthenticated access. If no service account is provided, Realtime Database access will be restricted just as any unauthenticated client would be."
The SDK is updated to 3.1.0:
user#ha:~/dev/project/auth/firebase$ sudo npm install -g firebase
[sudo] password for user:
/usr/local/lib
└─┬ firebase#3.1.0
Tried with no service account:
var firebase = require('firebase');
console.log('Initialise Firebasse app');
firebase.initializeApp({
// serviceAccount: "",
databaseURL: "https://some-valid-firebase.firebaseio.com"
});
The result is:
user#ha:~/dev/project/auth/firebase$ nodejs fb_anon.js
Initialise Firebasse app
/home/user/dev/project/node_modules/firebase/auth-node/auth.js:61
throw new Error('Invalid service account provided');
^
Please help, probably I am missing something obvious here. :-(
What is happening is that your application is referring to an old sdk version that is inside your node_modules. And thats because you updated the firebase sdk with the globally flag and you are referring to a local sdk.
You should be installing it locally to your application.
First make sure you added "firebase":"3.1.0" into your package.json file and then call npm install inside the same dir.
I've just tested it with the same piece of code you added and everything went as expected.
In this question you can find some additional information and tips when using npm.

Firebase reference is empty after requiring new version

The new documentation provides a straightforward method of initialising firebase, for example, this snipped comes directly from the README.md file:
Install the Firebase npm module:
$ npm init
$ npm install --save firebase
In your code, you can access Firebase using:
var firebase = require('firebase');
var app = firebase.intializeApp({ ... });
// ...
But in my installation this is not working, as in, firebase is empty ({} when console logged).
There's another section in the documentation called Include only the features you need, which provides the following snippet:
var firebase = require('firebase/app');
require('firebase/auth');
require('firebase/database');
var app = firebase.initializeApp({ ... });
// ...
This method works for me, so I'm wondering what could I be doing wrong in the first instance?
I'm using browserify, if that helps, but the docs state: The browser version is designed to be used with
a package bundler (e.g., Browserify,
Webpack).

Resources