Cloud function fails after changing Runtime to Node.js 10 - javascript

I am trying to take firebase backup through a cloud function. The function was running completely fine when I was using Runtime: Node.js 8. However, since it is going to be deprecated soon, I now have to use Node.js 10. My fcloud function now fails with the below error:
Error: function execution failed. Details:
Cannot read property 'charCodeAt' of undefined
Detailed error log:
2020-05-27 11:01:21.820 IST
firestore_export
8kxlp9s867dy
TypeError: Cannot read property 'charCodeAt' of undefined at peg$parsetemplate (/workspace/node_modules/google-gax/build/src/pathTemplateParser.js:304:17) at Object.peg$parse [as parse] (/workspace/node_modules/google-gax/build/src/pathTemplateParser.js:633:18) at new PathTemplate (/workspace/node_modules/google-gax/build/src/pathTemplate.js:55:54) at segments.forEach.segment (/workspace/node_modules/google-gax/build/src/pathTemplate.js:120:29) at Array.forEach (<anonymous>) at PathTemplate.render (/workspace/node_modules/google-gax/build/src/pathTemplate.js:114:23) at FirestoreAdminClient.databasePath (/workspace/node_modules/#google-cloud/firestore/build/src/v1/firestore_admin_client.js:904:57) at exports.scheduledFirestoreBackup (/workspace/index.js:6:31) at Promise.resolve.then (/layers/google.nodejs.functions-framework/functions-framework/node_modules/#google-cloud/functions-framework/build/src/invoker.js:330:28) at process._tickCallback (internal/process/next_tick.js:68:7)
Expand all | Collapse all
{
insertId: "000000-f688386c-8f2b-4146-aaf7-1fe67c656fa2"
labels: {…}
logName: "projects/firestore-249705/logs/cloudfunctions.googleapis.com%2Fcloud-functions"
receiveTimestamp: "2020-05-27T05:31:31.171084310Z"
resource: {…}
severity: "ERROR"
textPayload: "TypeError: Cannot read property 'charCodeAt' of undefined
at peg$parsetemplate (/workspace/node_modules/google-gax/build/src/pathTemplateParser.js:304:17)
at Object.peg$parse [as parse] (/workspace/node_modules/google-gax/build/src/pathTemplateParser.js:633:18)
at new PathTemplate (/workspace/node_modules/google-gax/build/src/pathTemplate.js:55:54)
at segments.forEach.segment (/workspace/node_modules/google-gax/build/src/pathTemplate.js:120:29)
at Array.forEach (<anonymous>)
at PathTemplate.render (/workspace/node_modules/google-gax/build/src/pathTemplate.js:114:23)
at FirestoreAdminClient.databasePath (/workspace/node_modules/#google-cloud/firestore/build/src/v1/firestore_admin_client.js:904:57)
at exports.scheduledFirestoreBackup (/workspace/index.js:6:31)
at Promise.resolve.then (/layers/google.nodejs.functions-framework/functions-framework/node_modules/#google-cloud/functions-framework/build/src/invoker.js:330:28)
at process._tickCallback (internal/process/next_tick.js:68:7)"
timestamp: "2020-05-27T05:31:21.820Z"
trace: "projects/firestore-249705/traces/74e27700d135763bc4e7892ebb1a2333"
}
My index.js is as below:
const firestore = require('#google-cloud/firestore');
const client = new firestore.v1.FirestoreAdminClient();
// Replace BUCKET_NAME
const bucket = 'gs://gcp_firestore_ae2/firestore_export'
exports.scheduledFirestoreBackup = (event, context) => {
const databaseName = client.databasePath(
process.env.GCLOUD_PROJECT,
'(default)'
);
return client
.exportDocuments({
name: databaseName,
outputUriPrefix: bucket,
// Leave collectionIds empty to export all collections
// or define a list of collection IDs:
// collectionIds: ['users', 'posts']
collectionIds: ['most_valuable_items','nric_img','pay_slip','pic_of_ofc_entrance'],
})
.then(responses => {
const response = responses[0];
console.log(`Operation Name: ${response['name']}`);
return response;
})
.catch(err => {
console.error(err);
});
};

I had the same issue. I fixed it by changing:
process.env.GCLOUD_PROJECT
to my actual Project ID (e.g. "my_app_37274")

I had the same issue, It seems like in previous versions we don't need to GCLOUD_PROJECT in environment variable i.e it automatically detects it, but from node 10 onwards we need to pass this explicitly.
That's how I resolved it.
So instead of hardcoding it, try passing GCLOUD_PROJECT in cloud functions environment variables.
Note: GCLOUD_PROJECT is project id, not the project name.

Related

What is the problem with binding to the next function in a BehaviourSubject

Background
I was trying to test my authService.getUserProfile() function that looks like below
private authUserSubject$ = new BehaviorSubject<IUser | null>(null);
authUser$ = this.authUserSubject$.asObservable();
getUserProfile = () => this.httpClient.get<IUser>('/user').pipe(
tap(this.authUserSubject$.next)
);
I needed to test that when getUserProfile() is called, then authUser$ is an Observable that has the user object
To achieve this I used the below code
describe('function getUserProfile()' , () =>{
it('should return update authUser$ property', done => {
spyOn(httpClient, 'get').and.returnValue(of({name: 'John Doe'}))
service.getUserProfile().subscribe({
next: (res) => {
expect(res as any).toEqual({name: 'John Doe'});
done();
}
})
});
})
The above test fails
Uncaught TypeError: Cannot read property 'length' of undefined thrown
In the console log for my test I have
zone-evergreen.js:178 Uncaught TypeError: Cannot read property 'length' of undefined
at AuthService.next (:9876/_karma_webpack_/webpack:/node_modules/rxjs/_esm2015/internal/Subject.js:36)
at AuthService.next (:9876/_karma_webpack_/webpack:/node_modules/rxjs/_esm2015/internal/BehaviorSubject.js:30)
at TapSubscriber._next (:9876/_karma_webpack_/webpack:/node_modules/rxjs/_esm2015/internal/operators/tap.js:40)
at TapSubscriber.next (:9876/_karma_webpack_/webpack:/node_modules/rxjs/_esm2015/internal/Subscriber.js:49)
at Observable._subscribe (:9876/_karma_webpack_/webpack:/node_modules/rxjs/_esm2015/internal/util/subscribeToArray.js:3)
at Observable._trySubscribe (:9876/_karma_webpack_/webpack:/node_modules/rxjs/_esm2015/internal/Observable.js:42)
at Observable.subscribe (:9876/_karma_webpack_/webpack:/node_modules/rxjs/_esm2015/internal/Observable.js:28)
at DoOperator.call (:9876/_karma_webpack_/webpack:/node_modules/rxjs/_esm2015/internal/operators/tap.js:16)
at Observable.subscribe (:9876/_karma_webpack_/webpack:/node_modules/rxjs/_esm2015/internal/Observable.js:23)
at UserContext.<anonymous> (:9876/_karma_webpack_/webpack:/src/app/login/services/auth.service.spec.ts:38)
The above should have worked, In fact in the test coverage the code is covered in the testing. To try solve the problem I tried binding this in my function like
getUserProfile = () => this.httpClient.get<IUser>('/user').pipe(
tap(this.authUserSubject$.next.bind(this)) // <-- This is line 38
);
Now I was so sure this will work but to my surprise same error. Finally I decided to try the expanded code i.e
getUserProfile = () => this.httpClient.get<IUser>('/user').pipe(
tap(res => this.authUserSubject$.next(res))
);
The above actually worked...
My question
What I am trying to understand is
Why would
tap(this.authUserSubject$.next.bind(this)) <-- Throws error
tap(res => this.authUserSubject$.next(res)) <-- No error thrown
Where is the length property coming from?

AWS IoT Javascript SDK can not create client

I'm using Vue.js, TypeScript, and the aws-iot-device-sdk package and like to subscribe to a IoT topic. This is how I create a new client:
import AwsIot from 'aws-iot-device-sdk';
import { config } from 'aws-sdk';
client = new AwsIot.device({
region: 'foo',
host: 'foo',
clientId: 'foo',
protocol: 'wss',
accessKeyId: config.credentials.accessKeyId,
secretKey: config.credentials.secretAccessKey,
sessionToken: config.credentials.sessionToken
});
One seconds later I get this console error:
Uncaught TypeError: Cannot read property 'read' of undefined
at nReadingNextTick (_stream_readable.js)
Uncaught TypeError: Cannot read property 'length' of undefined
at onwriteDrain (_stream_writable.js)
at afterWrite (_stream_writable.js)
Uncaught TypeError: Cannot read property 'length' of undefined
at onwriteDrain (_stream_writable.js)
at afterWrite (_stream_writable.js)
Uncaught TypeError: Cannot read property '_readableState' of undefined
at emitReadable_ (_stream_readable.js)
Uncaught TypeError: Cannot read property 'reading' of undefined
at maybeReadMore_ (_stream_readable.js)
node-libs-browser's implementation of process.nextTick does not accept callback arguments. Just override it inside your main.ts!
process.nextTick = function(callback) {
const args = [...arguments];
args.shift();
setTimeout(() => callback.apply(null, args));
}
UPDATE:
It's fixed in v2.2.1: Commit

Error "TypeError: Cannot read property 'indexOf' of undefined" when using ipfs-api

I was performing development using ipfs - api, I encountered the following error, add of image file to ipfs node does not work well.
Looking at the details of the error, it seems that protocol is treated as undefined among if (protocol.indexOf ('https') === 0) { in request.js.
This is the error description
Uncaught (in promise) TypeError: Cannot read property 'indexOf' of undefined
at webpackJsonp../node_modules/ipfs-api/src/utils/request.js.module.exports (request.js:7)
at requestAPI (send-request.js:165)
at send (send-request.js:196)
at send-files-stream.js:99
at Function.promisify (add.js:41)
at index.js:32
at Object.add (add.js:60)
at VueComponent._callee$ (HaikuCompose.vue?0664:118)
at tryCatch (runtime.js:62)
at Generator.invoke [as _invoke] (runtime.js:296)
This is the code I wrote
import IPFS from "ipfs-api"
const ipfsConf = { host: process.env.IPFSHOST, port: process.env.IPFSPORT, protocol: process.env.IPFSPROTCOL }
const ipfs = new IPFS(ipfsConf)
export default {
name: 'ipfstest',
data() {
return {
file:null,
buffer:null,
ipfsHash:null,
}
},
methods: {
async addipfs() {
await ipfs.add(this.buffer, (err, ipfsHash) => {
console.log(err,ipfsHash);
this.ipfsHash = ipfsHash[0].hash;
})
},
From the module sources, indexOf on line 7 of the request.js file is used on the variable storing the protocol, which is undefined in your case.
And from your code, I think I can safely assume that your environment variable process.env.IPFSPROTCOL is undefined.
TL:DR : I think you wanted to write IPFSPROTOCOL instead of IPFSPROTCOL

Electron-dl Cannot read property 'then' of undefined

I am using electron-dl to download a file but I cant seem to make it work.
I did almost exactly same as defined in docs but i dont know what is wrong.
Error:
I get the following error on main process
TypeError: Cannot read property 'then' of undefined
at EventEmitter.ipcMain.on ( \electron-dl-test\main.js:24:7)
How to reproduce (setup):
use repo: https://github.com/mafar/electron-dl-test
npm install and then npm start
main.js:
ipcMain.on('download', (ev, args) => {
download(BrowserWindow.getFocusedWindow(), args.url, args.properties)
.then(dl => console.log(dl.getSavePath()))
.catch(console.error);
})
index.html as renderer:
document.getElementById("download-file").onclick = function () {
//
var ipcRenderer = require('electron').ipcRenderer;
ipcRenderer.send('download', {
url: 'https://textfiles.com/100/ad.txt',
properties: {
saveAs: true,
directory: 'C:\\'
}
});
//
};
Preview:
The download function is part of an object exported by electron-dl. You need to destructure (ES6) or reference it directly (ES5) when requiring the module:
const { download } = require("electron-dl") // ES6
or
var download = require("electron-dl").download // ES5

TypeError: Cannot read property 'calls' of undefined

I am trying to write a unit test for my store in react application.
Unit test looks like:
import FRIENDS from '../../constants/friends';
import FriendsStore from '../friends_store';
jest.dontMock('../../constants/friends');
jest.dontMock('../friends_store');
describe('FriendsStore', () => {
let AppDispatcher;
let callback;
let addFriends = {
actionType: FRIENDS.ADD_FRIENDS,
name: 'Many'
};
let removeFriend = {
actionType: FRIENDS.REMOVE_FRIENDS,
id: '3'
};
beforeEach(function () {
AppDispatcher = require('../../dispatcher/app_dispatcher');
callback = AppDispatcher.register.mock.calls[0][0];
});
it('Should initialize with no friends items', function () {
var all = FriendsStore.getAll();
expect(all).toEqual([]);
});
});
And when I executed with jest statement, I've got the error message:
Using Jest CLI v0.4.0
FAIL scripts/stores/__tests__/friends_store-test.js (0.811s)
● FriendsStore › it Should initialize with no friends items
- TypeError: Cannot read property 'calls' of undefined
at Spec.<anonymous> (/Volumes/Developer/reactjs/app5/scripts/stores/__tests__/friends_store-test.js:33:41)
at jasmine.Block.execute (/Volumes/Developer/reactjs/app5/node_modules/jest-cli/vendor/jasmine/jasmine-1.3.0.js:1065:17)
at jasmine.Queue.next_ (/Volumes/Developer/reactjs/app5/node_modules/jest-cli/vendor/jasmine/jasmine-1.3.0.js:2098:31)
at null._onTimeout (/Volumes/Developer/reactjs/app5/node_modules/jest-cli/vendor/jasmine/jasmine-1.3.0.js:2088:18)
at Timer.listOnTimeout [as ontimeout] (timers.js:112:15)
1 test failed, 0 tests passed (1 total)
Run time: 1.028s
It seems to be, that jest can not find the calls property. What am I doing wrong?
I had a similar issue.
Making the following change should resolve the issue:
beforeEach(function () {
AppDispatcher = require('../../dispatcher/app_dispatcher');
FriendsStore = require('/path/to/store'); //**load in store**
callback = AppDispatcher.register.mock.calls[0][0];
});
Working with ReactJS v15.2.1 & Jest v14.0.0
This also worked on ReactJS v14 too.

Categories