Skip to content

Instantly share code, notes, and snippets.

@abinavseelan
Last active May 18, 2020 00:17
Show Gist options
  • Save abinavseelan/ace0ae4d4c594194c6c698df800e516e to your computer and use it in GitHub Desktop.
Save abinavseelan/ace0ae4d4c594194c6c698df800e516e to your computer and use it in GitHub Desktop.
Firebase Cloud Function to handle online/offline status
const functions = require('firebase-functions');
const Firestore = require('@google-cloud/firestore');
const firestore = new Firestore();
exports.onUserStatusChanged = functions.database
.ref('/status/{userId}') // Reference to the Firebase RealTime database key
.onUpdate(event => {
const usersRef = firestore.collection('/users'); // Create a reference to the Firestore Collection
return event.data.ref.once('value')
.then(statusSnapshot => snapShot.val()) // Get the latest value from the Firebase Realtime database
.then(status => {
// check if the value is 'offline'
if (status === 'offline') {
// Set the Firestore's document's online value to false
usersRef
.doc(event.params.userId)
.set({
online: false
}, { merge: true });
}
})
});
@FilipeOS
Copy link

FilipeOS commented Jul 8, 2019

Hi there,

I can't deploy this index.js and have no idea why, can you advise please?


const functions = require('firebase-functions');
const Firestore = require('@google-cloud/firestore');

const firestore = new Firestore();

exports.onUserStatusChanged = functions.database
  .ref('/s/{userId}') // Reference to the Firebase RealTime database key
  .onUpdate(event => {
    const usersRef = firestore.collection('/u'); // Create a reference to the Firestore Collection
  
    return event.data.ref.once('value')
      .then(statusSnapshot => snapShot.val()) // Get the latest value from the Firebase Realtime database
      .then(status => {
        // check if the value is 'offline'
        if (status === 'off') {
          // Set the Firestore's document's online value to false
          usersRef
            .doc(event.params.userId)
            .set({
              status: 'off'
            }, { merge: true });
        }
      })
  });

LOG:

0 info it worked if it ends with ok
1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   '--prefix',
1 verbose cli   'C:\\Users\\XXX\\AppData\\Roaming\\npm\\functions',
1 verbose cli   'run',
1 verbose cli   'lint' ]
2 info using [email protected]
3 info using [email protected]
4 verbose run-script [ 'prelint', 'lint', 'postlint' ]
5 info lifecycle functions@~prelint: functions@
6 info lifecycle functions@~lint: functions@
7 verbose lifecycle functions@~lint: unsafe-perm in lifecycle true
8 verbose lifecycle functions@~lint: PATH: C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin;C:\Users\XXX\AppData\Roaming\npm\functions\node_modules\.bin;C:\Users\XXX\AppData\Roaming\npm;C:\Program Files\nodejs\;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;C:\Program Files\PuTTY\;D:\Android\flutter\bin;C:\Program Files\nodejs\;C:\Program Files\Git\cmd;C:\Users\XXX\AppData\Roaming\npm
9 verbose lifecycle functions@~lint: CWD: C:\Users\XXX\AppData\Roaming\npm\functions
10 silly lifecycle functions@~lint: Args: [ '/d /s /c', 'eslint .' ]
11 silly lifecycle functions@~lint: Returned: code: 1  signal: null
12 info lifecycle functions@~lint: Failed to exec lint script
13 verbose stack Error: functions@ lint: `eslint .`
13 verbose stack Exit status 1
13 verbose stack     at EventEmitter.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\index.js:301:16)
13 verbose stack     at EventEmitter.emit (events.js:189:13)
13 verbose stack     at ChildProcess.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:189:13)
13 verbose stack     at maybeClose (internal/child_process.js:970:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:259:5)
14 verbose pkgid functions@
15 verbose cwd C:\Users\XXX\AppData\Roaming\npm
16 verbose Windows_NT 10.0.17763
17 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "--prefix" "C:\\Users\\XXX\\AppData\\Roaming\\npm\\functions" "run" "lint"
18 verbose node v10.15.3
19 verbose npm  v6.4.1
20 error code ELIFECYCLE
21 error errno 1
22 error functions@ lint: `eslint .`
22 error Exit status 1
23 error Failed at the functions@ lint script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1, true ]

ERROR:


 15:9  error  Each then() should return a value or throw  promise/always-return

✖ 1 problem (1 error, 0 warnings)

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! functions@ lint: `eslint .`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the functions@ lint script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\XXX\AppData\Roaming\npm-cache\_logs\2019-07-08T18_11_57_171Z-debug.log
events.js:174
      throw er; // Unhandled 'error' event
      ^

Error: spawn npm --prefix "%RESOURCE_DIR%" run lint ENOENT
    at notFoundError (C:\Users\XXX\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\cross-env\node_modules\cross-spawn\lib\enoent.js:6:26)
    at verifyENOENT (C:\Users\XXX\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\cross-env\node_modules\cross-spawn\lib\enoent.js:40:16)
    at ChildProcess.cp.emit (C:\Users\XXX\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\cross-env\node_modules\cross-spawn\lib\enoent.js:27:25)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:248:12)
Emitted 'error' event at:
    at ChildProcess.cp.emit (C:\Users\XXX\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\cross-env\node_modules\cross-spawn\lib\enoent.js:30:37)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:248:12)

Error: functions predeploy error: Command terminated with non-zero exit code1

The Hello World example I can submit and test but this can't even deploy.. Please advise

@expl0r3rgu1
Copy link

Just place a return 0; statement at the end of then() function @FilipeOS

@savan-gotrakiya
Copy link

I have used above code.
but I am getting an Error
TypeError: Cannot read property 'userId' of undefined
at exports.onUserStatusChanged.functions.database.ref.onUpdate.event

please help me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment