firebase cloud functions limit children - function

Thank you I am deploying a function to limit the child nodes generated from push command.The link I am following code to limit child node Now I am just editing this code putting my custom code as follows link:
'use strict';
const functions = require('firebase-functions');
// Max number of lines of the chat history.
const MAX_LOG_COUNT = 1;
// Removes siblings of the node that element that triggered the function if there are more than MAX_LOG_COUNT.
// In this example we'll keep the max number of chat message history to MAX_LOG_COUNT.
exports.truncate = functions.database.ref('/grid/{pushId}').onWrite((change) => {
const parentRef = change.after.ref.parent;
return parentRef.once('value').then((snapshot) => {
if (snapshot.numChildren() >= MAX_LOG_COUNT) {
let childCount = 0;
const updates = {};
snapshot.forEach((child) => {
if (++childCount <= snapshot.numChildren() - MAX_LOG_COUNT) {
updates[child.key] = null;
}
});
// Update the parent. This effectively removes the extra children.
return parentRef.update(updates);
}
return null;
});
});
So here I deploy the functions to limit the children but, getting error in firebase logs as:
TypeError: Cannot read property 'ref' of undefined
at exports.truncate.functions.database.ref.onWrite (/user_code/index.js:11:33)
at Object.<anonymous> (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:59:27)
at next (native)
at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71
at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:53:36)
at /var/tmp/worker/worker.js:700:26
at process._tickDomainCallback (internal/process/next_tick.js:135:7)

Not sure if you still need this. Have you initialized Firebase App? Add the following lines, if not already added, and check again.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
//Define your trigger

Related

ReferenceError: Window is not defined while importing htmlToDraft from html-to-draftjs on Node.js

I wrote a separate function to convert html to draftjs, there I used htmlToDraft function from
html-to-draftjs.
The Function:
const htmlToDraftBlocks = (html) => {
const blocksFromHTML = htmlToDraft(html);
const state = ContentState.createFromBlockArray(
blocksFromHTML.contentBlocks,
blocksFromHTML.entityMap
);
const editorState = EditorState.createWithContent(state);
return editorState;
};
when running the server in node.js I get the following error:
ReferenceError : window is not defined
I have tried bellow way as well:
let htmlToDraft = null;
if (typeof window !== 'undefined') {
htmlToDraft = require('html-to-draftjs').default;
}
But in this case htmlToDraft remains null, not getting imported.
Why I am getting this error? Any help is appreciated

How to get Course Id from Classroom URL?

Goal: I want to quickly connect to a Google Classroom using a Google Classroom URL via Google Apps Script.
Problem: Need help filtering Map of courses by URL.
Background:
Classroom API has little documentation for GAS. Furthermore, COURSE_ID is used for nearly all connections. I can map the active courses, but I cannot filter the map. The code below originated from Yagisanatode with modifications in an attempt to map active courses by URL. Changing the Logger to (courseData) reveals the creation of the double array.
function findCourseByUrl() {
const courseList = Classroom.Courses.list({"courseStates":["ACTIVE"]}).courses;
const courseData = courseList.map(course => {
let ownerName = Classroom
.Courses
.Teachers
.get(course.id, course.ownerId)
.profile
.name
.fullName;
return `[${course.name}, ${course.id}, ${ownerName}, ${course.alternateLink}]`;
});
const link = 'https://classroom.google.com/c/YOUCLASSROOMURL'; //change this
const data = courseData.filter(function(item){return item[4] === link;});
Logger.log(data);
};
Any help would be appreciated. I'm stuck.
Answer:
link is not defined since it is outside of the courseData.filter(function(item){}). The solution is to call a global variable or create a conditional with the declared variable within the function(item).
The toString is looking for an exact match for the URL text, which is naturally unique.
Video reference: https://youtu.be/PT_TDhMhWsE
Code:
function findCourseByUrl() {
const courseList = Classroom.Courses.list({"courseStates":["ACTIVE"]}).courses;
const courseData = courseList.map(course => {
let ownerName = Classroom
.Courses
.Teachers
.get(course.id, course.ownerId)
.profile
.name
.fullName;
return `[${course.name}, ${course.id}, ${ownerName}, ${course.alternateLink}]`;
});
const filterCourse = function(item){
let link = 'https://classroom.google.com/c/YOURCOURSEURL' ///Change this or replace with a global variable
if(item.toString().indexOf(link) === -1){
return false;
} else {
return true
}
};
let theCourse = courseData.filter(filterCourse); //this could be a return if called by function in Test.gs
Logger.log(theCourse); //remove if using a function with console.log in Test.gs
};

Function inside a Function not calling in React Native

I am new to react-native and calling a function inside a fucntion.
I have done as below so far :
Step 1 : Created a function _snapshotToArray to convert the firebase snapshot to Arrray.
_snapshotToArray(snapshot) {
var returnArr = [];
snapshot.forEach(function(childSnapshot) {
var item = childSnapshot.val();
item.key = childSnapshot.key;
returnArr.push(item);
});
return returnArr;
}
Step 2 : Created another function as below and calling _snapshotToArray inside it.
_readUserDataFromFirebaseConsole() {//once and on
firebase.database().ref('Users/').on('value', function (snapshot) {
console.log(this._snapshotToArray(snapshot));
Toast.show(this._snapshotToArray(snapshot),Toast.LONG);
});
}
Talking about this call :
console.log(this._snapshotToArray(snapshot));
When I press CTRL+CLick, it not letting me to navigate to body of the fuction _snapshotToArray.
In Device am getting below error :
_snapshotToArray is not defined
What might be the issue ?
I'm not at my PC right now, so I cannot test it, but from looking at your code, you need to use a different function notation to allow the varibale access of/from parent methods and parent class.
_snapshotToArray = snapshot => {
var returnArr = [];
snapshot.forEach(function(childSnapshot) {
var item = childSnapshot.val();
item.key = childSnapshot.key;
returnArr.push(item);
});
return returnArr;
}
and
_readUserDataFromFirebaseConsole = () => {
firebase.database().ref('Users/').on('value', snapshot => {
console.log(this._snapshotToArray(snapshot));
Toast.show(this._snapshotToArray(snapshot),Toast.LONG);
});
}

MEAN Nodejs JSON.parse passing data from client to server

I am using MEAN stack and I am sending query parameters dynamically to my Nodejs server endpoints.
My client controller :
$http.get('/api/things',{params:{query:query}}).then(response => {
this.awesomeThings = response.data;
socket.syncUpdates('thing', this.awesomeThings);
});
where query is a value injected into the controller.
This is the server controller function (which works):
export function index(req, res) {
var query = req.query.query && JSON.parse(req.query.query)
Thing.find(query).sort({_id:-1}).limit(20).execAsync()
.then(respondWithResult(res))
.catch(handleError(res));
}
The above works but I am trying to understand the line
var query = req.query.query && JSON.parse(req.query.query)
as I have never seen this before( and I don't come from a programming background). I console.logged query and understand it's an object (which is required by Mongodb) but when I console.logged (JSON.parse(req.query.query)) or JSON.parse(query) to find out the final output, the program stops working with no error messages, very strange..
If someone can explain the above syntax and why it has to be done this way for it work, that would be much appreciated..
PS when I try to console log the JSON.parse like so, it fails to load even though it should have no effect whatsoever:
export function index(req, res) {
var query = req.query.query && JSON.parse(req.query.query)
var que = JSON.parse(req.query.query)
Thing.find(query).sort({_id:-1}).limit(20).execAsync()
.then(respondWithResult(res))
.catch(handleError(res));
console.log("que"+que)
}
function one() {
var x = {};
var res = JSON.parse(x.y);
console.log(res);
}
function two() {
var x = {};
var res = x.y && JSON.parse(x.y);
console.log(res);
}
<button onclick="one()">ERROR</button>
<button onclick="two()">NO ERROR</button>
var x = data && JSON.parse(data);
Since expression is evaluated from left, first data is evaulated.
If it is undefined then, the next part -> JSON.parse() is not performed.
On the other hand, if data is defined parse is tried and the result is returned and stored in x.
Main advantage here is the parse doesn't run if the variable wasn't defined.
it could be equivalent to saying:
if(data) {x = JSON.parse(x);}

Using Q to return secondary query in node with express and mysql

New to node, As I am cycling through a roster of students, I need to check and see if a teacher has requested them for tutoring.
I realized I can't just do this:
var checkRequest = function(id){
var value = '';
roster.query('SELECT * FROM teacher_request WHERE student_id ='+id, function(err, row){
value = row.length;
}
return value;
}
After a bit of digging around promises looked like a great solution, but if I simply return the deferred.promise from the checkRequest function, all I get is an object that says [deferred promise] which I can't access the actual data from. (Or have not figured out how yet)
If I follow along with their api and use .then (as illustrated in the getRow) function, I am back in the same problem I was in before.
function checkRequest(id) {
console.log(id);
var deferred = Q.defer();
connection.query('SELECT * FROM teacher_request WHERE student_id ='+id, function(err, row){
deferred.resolve(row.length);
});
return deferred.promise;
}
var getRow = function(id){
checkRequest(id).then(function(val) {
console.log(val); // works great
return val; //back to the same problem
});
}
The roster needs to be able to be pulled from an external API which is why I am not bundling the request check with the original roster query.
Thanks in advance
From the stuff you posted, I assume you have not really understood the concept of promises. They allow you to queue up callbacks, that get executed, when the asynchronous operation has finished (by succeeding or failing).
So instead of somehow getting the results back to your synchronous workflow, you should convert that workflow to work asynchronous as well. So a small example for your current problem:
// your students' ids in here
var studentsArray = [ 1, 2, 5, 6, 9 ];
for( var i=0; i<studentsArray.length; i++ ) {
checkRequest( i )
.then( function( data ){
console.log( data.student_id );
// any other code related to a specific student in here
});
}
or another option, if you need all students' data at the same time:
// your students' ids in here
var studentsArray = [ 1, 2, 5, 6, 9 ];
// collect all promises
var reqs = [];
for( var i=0; i<studentsArray.length; i++ ) {
reqs.push( checkRequest( i ) );
}
Q.all( reqs )
.then( function(){
// code in here
// use `arguments` to access data
});