Save data to firestore from google cloud function - google-cloud-firestore

I am new to IOT and firestore.
I am trying to save data to firestore using cloud function (MQTT).
Following is the code:
exports.helloPubSub = (event, callback) => {
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firestore);
const db = admin.firestore()
//admin.initializeApp();
console.log("Start");
var docRef = db.collection('users').doc('alovelace');
var setAda = docRef.set({
first: 'Ada',
last: 'Lovelace',
born: 1815
});
};
I am getting following errors in view logs :
"Function execution took 22 ms, finished with status: 'error'"
Any suggestion
Also after some changes I am getting error - Error: Firebase config variables are not available. Please use the latest version of the Firebase CLI to deploy this function
My package.json is
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"dependencies": {
"#google-cloud/vision": "^0.12.0",
"async": "^2.5.0",
"consolidate": "^0.14.5",
"express": "^4.15.4",
"firebase-admin": "^5.4.0",
"firebase-functions": "^0.7.0",
"firebase-tools": "3.15.4",
"handlebars": "^4.0.10",
"jquery": "^3.2.1",
"js-levenshtein": "^1.1.3",
"json-query": "^2.2.2"
},
"private": true
}

As you are getting following error message
Error: Firebase config variables are not available. Please use the
latest version of the Firebase CLI to deploy this function
You need to update firebase CLI to deploy cloud function
npm i --save firebase-functions#latest
There was a breaking change introduced in firebase-tools#3.17.x which requires your project to upgrade firebase-functions to the latest version.
However, firebase-functions#latest also requires firebase-admin#latest (at the time of writing this answer firebase-admin#5.11.0. Once all packages are upgraded, this problem should be solved.
Another alternative is to downgrade your global firebase-tools to 3.16.0, which lets you use older firebase-functions and firebase-admin packages.

Related

ERR_REQUIRE_ESM require of of ES Module not supported how can I fix this? on file-type package

I've a outdated app that uses very older few packages those doesn't support ES Module as an example file-type package. So if you setup babel and node HTTP server with and then install file-type package then start building and running will throw error message like below:
Error [ERR_REQUIRE_ESM]: require() of ES Module E:\test\testbabel\node_modules\file-
type\index.js from E:\test\testbabel\dist\index.js not supported.
Instead change the require of E:\test\testbabel\node_modules\file-type\index.js in
E:\test\testbabel\dist\index.js to a dynamic import() which is available in all CommonJS
modules.
at Object.<anonymous> (E:\test\testbabel\dist\index.js:10:17) {
code: 'ERR_REQUIRE_ESM'
}
I tried this on a fresh project though my old project has an outdated config or so, It still throwing this error
Here are my index.js codes
import http from 'http';
import { fileTypeFromFile } from 'file-type';
const server = http.createServer((req, res) => {
res.end('Hello from the server');
}).listen(4001);
console.log('Server is up and running');
export default server;
file package.json.
{
"name": "testbabel",
"version": "1.0.0",
"description": "test babel with http or express",
"main": "index.js",
"scripts": {
"build": "babel index.js -d dist",
"start": "npm run build && node dist/index.js"
},
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/cli": "^7.17.10",
"#babel/core": "^7.18.2",
"#babel/plugin-transform-modules-commonjs": "^7.18.2",
"#babel/preset-env": "^7.18.2"
},
"dependencies": {
"file-type": "^17.1.1"
}
}
I just tried to import the package and got the errors above.
attempt:
I thought a converter might help so used #babel/plugin-transform-modules-commonjs but still didn't help, and seems no effect on including that package
I'm not sure but added some tweaks on package.json like "type": "module" "type": "commonjs" didn't help at all.
what is the easiest solution for this issue and how do we fix it?
Note: I saw people were going back to the supported package instead of new one which doesn't make sense to me as a solution.
Option1(babel with mocha): Rename "index.js" to "index.mjs" and modify file-type's pacakage.json ("index.js" to "index.mjs"), then leave Babel to transpile for you.
// babel-register.js
const babel_register = require("#babel/register").default;
babel_register({
ignore: [
// Only work on Project-wide configuration
// overrides ignore can transpile packages(modules) from node_modules (https://babeljs.io/docs/en/babel-register/#ignores-node_modules-by-default)
],
});
Use babel.config instead of .babelrc
//.mocharc.js
require("./babel-register");
module.exports = {
// https://github.com/mochajs/mocha/blob/v8.4.0/example/config/.mocharc.js
ui: "bdd",
timeout: 5000,
recursive: true,
};
Option2(babel only): Using dynamic import expression
async function doSomething() {
const {fileTypeFromStream} = await import("file-type");
}
and
["#babel/preset-env", {
exclude: ["proposal-dynamic-import"]
}]
Avoiding Babel tanspile dynamic import expression

Google Actions: Testing Library complains about Firebase Terms

I'm trying to implement tests for my Google Action with Assistant Conversation Testing Library.
The problem is that the execution is complaining about: "Firebase Terms of Service is not accepted". I can't find any way to accept these terms - neither in the Actions Console or in the Cloud Platform.
It was working ~two weeks ago and suddenly it stoped working with this error. As far as I know I haven't changed anything related. I also tried creating a new service_account.json, but this didn't help.
Error message/stacktrace:
Starting writePreview From Draft
Error: 9 FAILED_PRECONDITION: Firebase Terms of Service is not accepted. Navigate to your project's overview page on the Actions Console to accept the Terms of Service.
at Object.callErrorFromStatus (test/node_modules/#grpc/grpc-js/build/src/call.js:31:26)
at Object.onReceiveStatus (test/node_modules/#grpc/grpc-js/build/src/client.js:244:52)
at Object.onReceiveStatus (test/node_modules/#grpc/grpc-js/build/src/client-interceptors.js:334:141)
at Object.onReceiveStatus (test/node_modules/#grpc/grpc-js/build/src/client-interceptors.js:297:181)
at test/node_modules/#grpc/grpc-js/build/src/call-stream.js:130:78
at processTicksAndRejections (internal/process/task_queues.js:75:11) {
code: 9,
details: "Firebase Terms of Service is not accepted. Navigate to your project's overview page on the Actions Console to accept the Terms of Service.",
metadata: Metadata {
internalRepr: Map(2) {
'google.rpc.preconditionfailure-bin' => [Array],
'grpc-status-details-bin' => [Array]
},
options: {}
}
}
Source Code:
const { ActionsOnGoogleTestManager } = require('#assistant/conversation-testing');
async function openAction(projectId, invocationName) {
const testManager = new ActionsOnGoogleTestManager({ projectId: projectId });
testManager.setTestSurface('SMART_DISPLAY');
testManager.setSuiteLocale("en-US")
await testManager.writePreviewFromDraft();
await testManager.sendQuery(`Talk to ${invocationName}`);
testManager.assertText("Hello World")
testManager.assertIntent('actions.intent.MAIN');
}

"Unexpected token stripe" when trying to deploy Firebase Functions

I'm trying to incorporate Stripe into an iOS app using Firebase Functions. I'm following the Stripe documentation for "Accepting a payment" in Swift with Node backend. I first did npm install --save stripe. That finished with no errors. Then I did npm install. My index.js looks like this so far:
// // 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!");
// });
const functions = require('firebase-functions');
const stripe = require('stripe')('sk_test_...');
const paymentIntent = await stripe.paymentIntents.create({
amount: 1099,
currency: 'usd',
});
const clientSecret = paymentIntent.client_secret
When running firebase deploy I get: 11:29 error Parsing error: Unexpected token stripe. Line 11 char 29 in my file is the stripe.paymentIntents...
This is my first time using Firebase Functions or Stripe, so I'm at a loss here. I appreciate any help.
EDIT:
Here's the contents of my package.json file.
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"lint": "eslint .",
"serve": "firebase emulators:start --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "8"
},
"dependencies": {
"firebase-admin": "^8.10.0",
"firebase-functions": "^3.6.1",
"stripe": "^8.55.0"
},
"devDependencies": {
"eslint": "^5.12.0",
"eslint-plugin-promise": "^4.0.1",
"firebase-functions-test": "^0.2.0"
},
"private": true
}
This error is because on the cloud environment the stripe library is not installed before you require it.
npm install does install the dependencies but in your local environment, to install them on the Cloud Functions envirornment you need to edit the package.json file from the Cloud Function.
This to add the dependencies that it will be required by the function.
This is done by adding the dependency section to the package.json file
It will lok something like:
{
"name": "sample-name",
"version": "0.0.1",
"dependencies": {
"escape-html": "^1.0.3",
"stripe": "^8.24.0"
}
}
EDIT
With this code it works on Cloud functions:
const stripe = require('stripe')('<My Secret Key>');
exports.helloWorld = (req, res) => {
let paymentIntent = null;
paymentIntent = stripe.paymentIntents.create({
amount: 2000,
currency: 'usd',
description: 'My first payment',
});
let message = req.query.message || req.body.message || 'Hello World!';
res.status(200).send(message);
};
Apparently the issue was the await because HTTP Cloud Functions work on a Synchronous way
I see this question is old but I ran into this exact issue and couldn't find an answer.
I had my backend functions folder nested within my overall app and I had let firebase generate some files for me, including a lint configuration. So, I ended up with two lint config files in my project total. The firebase generated one tried to enforce double quotes and the one I created tried to enforce single quotes. I ended up just deleting the generated lint config and it works fine now.

Trying to write a vuepress plugin

(The doc on writing a plugin is pretty sparse...)
THE GOAL
Create a plugin to add headers to a page.
THE ATTEMPT
Created a plugin following guidelines and an example plugin (that presumably works...) to do something similar.
THE ISSUE
Plugin won't load.
config.js
plugins: [
[
'vuepress-plugin-headertags',
{ headerTags: ["<script src='https://cdn.jsdelivr.net/npm/netlify-identity-widget#1.5.2/build/netlify-identity-widget.min.js'></script>"]}
]
],
(the <script> tag is what I'm trying to insert, in this instance.
PLUGIN index.js
const { path } = require('path')
// was: const { path } = require('#vuepress/shared-utils')
// dunno. No documentation on this...
// got the current version from the 'default-theme' code
module.exports = (options) => ({
define () {
return {
headerTags: options.headerTags || []
}
},
enhanceAppFiles () {
return [path.resolve(__dirname, 'enhanceAppFile.js')]
},
globalUIComponents: ['HeaderTags']
})
PLUGIN INSTALLATION
I published it to npm as vuepress-plugin-headertags, and then installed it with:
yarn add -D vuepress-plugin-headertags
Here's the relevant package.json content:
{
"name": "vuepress-netlifycms",
"version": "0.0.0",
"scripts": {
"dev": "vuepress dev",
"build": "vuepress build",
"debug": "node --nolazy --inspect=9229 /home/rickb/.yarn/bin/vuepress build"
},
"devDependencies": {
"vuepress": "^0.14.8",
"vuepress-plugin-headertags": "^1.0.3"
},
"dependencies": {}
}
VUEPRESS INSTALLATION
I cloned the vuepress repo from git and did a yarn link, which makes it globally available. With that, I can trace it in the debugger via the 'debug' script.
TRACING
I've followed the VP source code in the debugger and get to resolvePathPackage() in moduleResolver.js. The incoming path is not correct:
/home/(...)/VuePress-NetlifyCMS/vuepress-plugin-headertags
It should be:
/home/(...)/VuePress-NetlifyCMS/node_modules/vuepress-plugin-headertags
At any rate, it doesn't resolve, even after the 'normalization' process.
MORE EYES
I need more eyes on this to help me figure it out. The project is already up on github as 'rickbsgu/VuePress-NetlifyCMS.git'. If you do an install, the plugin will be in the project directory under 'node_modules/vuepress-plugin-headertags'
Any thoughts appreciated
And it works, now. Two problems:
Version I was running/debugging was not the same as the version in package.json. There is the vuepress executable and the vuepress libraries the plugin requires. The library was always the older version at runtime.
I needed to change the path import in index.html from const { path } = require('path') to const { path } = require('#vuepress/shared-utils'). That's my doc issue - I don't see that documented anywhere.
Thanks #Sun Haoran for getting me to look in the right place.

MEAN - Node - Mongoose - Error

trying create simple API using MEAN.
am following below youtube link as guide
https://www.youtube.com/watch?v=MMOIr_VwwAk
setting port on 3000. when try to run it, throws error like as fallows
**mongoose.connect('mongodb://localhost/restful');
^
TypeError: Cannot read property 'connect' of undefined**
server.js
var express = require ('express'),
restful = require('node-rest-client'),
mongoose = restful.mongoose;
var app = express();
app.get(function(){
app.use(express.bodyParser());
app.use(express.methodOverride());
});
mongoose.connect('mongodb://localhost/restful');
var ProductSchema = mongoose.Schema({
name : String,
sku: String,
price:Number
});
var Products =restful.model('products',ProductSchema);
Products.methods(['get','put','post','delete']);
Products.register(app,'/api/products');
app.listen(3000);
console.log("am running on port 3000");
package.json
{
"name": "restful",
"main": "server.js",
"dependencies": {
"express": "^4.14.0",
"mangoose": "latest",
"node-restful": "latest"
}
}
this what have start with as of now.
helps much appreciated.
Your package.json appears to have typos. Did you get errors when you ran npm install?
I assume mangoose is meant to be mongoose.
Also node-restful does not match any of your require statements. Instead you have restful = require('node-rest-client')