How to use forEach in Firebase Cloud Functions while querying? - javascript

So, I have a https function, which when triggered, needs to read the current server time and get the list of items that have a target_date which is lesser than the current time. Once it gets those list of items, those respective items need to be updated by setting its 'status' value to 'completed'. I have written the function but it is throwing an error. Can you please help me fix it?
exports.checkCampaignDate = functions.https.onRequest((request, response) => {
const current_time = Date.now();
console.log("current time", current_time);
var targetRef = admin.database().ref('/Fund');
console.log("target ref", targetRef);
targetRef.orderByChild("time_left").endAt(current_time).once("value", function(snapshot) {
const artcall_list = snapshot.val();
const artcall_id = snapshot.key;
snapshot.forEach((artcallSnap) => {
console.log("Artcall Snap", artcallSnap.val());
artcallSnap.child("status").set("completed");
});
console.log("This is the list of artcalls that have this same date", artcall_list);
console.log("This is the artcall id:", artcall_id);
// do some stuff once
});
return null;
});
My database:
"Fund" : {
"-LEEy7uxXEeI4AJuePoB" : {
"amount_funded" : 5200,
"artist_name" : "Sean Roldan and Friends",
"genre" : "Indian Blues and Jazz",
"image_url" : "https://firebasestorage.googleapis.com/v0/b/artcall-f8f1a.appspot.com/o/profile_images%2Fthumbs%2Fseanroldan.jpg?alt=media&token=6414d8d6-e8a8-487e-baf3-0d36d017a205",
"percent_funded" : 0.29714285714285715,
"perf_location" : "Chennai",
"reward_amt" : 6000,
"target_amount" : 1750000,
"target_date" : 1566568176731,
"time_left" : 1566568176731,
"total_backers" : 1
"status" : "incomplete"
},
"-asdffdsa123" : {
"amount_funded" : 0,
"artist_name" : "Agam",
"genre" : "Rock",
"image_url" : "default",
"percent_funded" : 0,
"perf_location" : "Chennai",
"target_amount" : 1300000,
"target_amt" : 1300000,
"target_date" : 1566568176731,
"time_left" : 1566568176731,
"total_backers" : 0
"status" : "incomplete"
}
},
Error:
TypeError: artcallSnap.child(...).set is not a function
at snapshot.forEach (/user_code/index.js:311:36)
at /user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/index.node.cjs.js:4255:20
at /user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/index.node.cjs.js:3669:24
at LLRBNode.inorderTraversal (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/index.node.cjs.js:2606:13)
at SortedMap.inorderTraversal (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/index.node.cjs.js:3052:27)
at ChildrenNode.forEachChild (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/index.node.cjs.js:3668:24)
at DataSnapshot.forEach (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/index.node.cjs.js:4254:31)
at /user_code/index.js:309:12
at onceCallback (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/index.node.cjs.js:4843:51)
at /user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/index.node.cjs.js:4465:22
at exceptionGuard (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/index.node.cjs.js:691:9)
at EventList.raise (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/index.node.cjs.js:9727:17)
at EventQueue.raiseQueuedEventsMatchingPredicate_ (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/index.node.cjs.js:9681:41)
at EventQueue.raiseEventsForChangedPath (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/index.node.cjs.js:9665:14)
at Repo.onDataUpdate_ (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/index.node.cjs.js:12770:26)
at PersistentConnection.onDataPush_ (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/index.node.cjs.js:12070:18)
at PersistentConnection.onDataMessage_ (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/index.node.cjs.js:12064:18)
at Connection.onDataMessage_ (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/index.node.cjs.js:11341:14)
at Connection.onPrimaryMessageReceived_ (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/index.node.cjs.js:11335:18)
at WebSocketConnection.onMessage (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/index.node.cjs.js:11236:27)
at WebSocketConnection.appendFrame_ (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/index.node.cjs.js:10841:18)
at WebSocketConnection.handleIncomingFrame (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/index.node.cjs.js:10891:22)

artcallSnap is a DataSnapshot, which doesn't have a set() method. To get the Reference from a snapshot, use its ref property. So:
artcallSnap.ref.child("status").set("completed")

Related

Getting json fields from json file

I am facing a problem. I have this json log
{
"log": "Log Info : { \"datetime\" : \"datetime\", \"field1\" : \"value1\", \"field2\" : \"value2\", \"field3\" : \"value3\", \"field4\" : \"value4\", \"field5\" : \"value5\", \"field6\" : \"value6\", \"field7\" : \"value7\", \"field8\" : \"value8\", \"field9\" : \"value9\", \"field10\" : \"value10\", \"field11\" : \"value11\"}\n",
"stream": "stdout",
"kubernetes": {
"pod_name": "pod_name",
"namespace_name": "namespace_name",
"pod_id": "pod_id",
"host": "host",
"container_name": "container_name",
"docker_id": "docker_id",
"container_hash": "container_hash",
"container_image": "container_image"
}
}
I need to get all field inside "log" key. These fields will be increased, so I need to get all fields inside log dynamically. I am using this code to parse json, but the output is this. Maybe someone can help me? Thanks.
const readFile = require("fs").readFile;
readFile("log.json", (err, data) => {
if (err) throw err;
const log = JSON.parse(data);
console.log(log);
});
Output:
{
log: 'Log Info : { "datetime" : "datetime", "field1" : "value1", "
field2" : "value2", "field3" : "value3", "field4" : "value4", "field5" :
"value5", "field6" : "value6", "field7" : "value7", "field8" : "value8"
, "field9" : "value9", "field10" : "value10", "field11" : "value11"}\n',
stream: 'stdout',
kubernetes: {
pod_name: 'pod_name',
namespace_name: 'namespace_name',
pod_id: 'pod_id',
host: 'host',
container_name: 'container_name',
docker_id: 'docker_id',
container_hash: 'container_hash',
container_image: 'container_image'
}
}
You need to JSON.parse also the "inner" json (after you clean it from the prefix)
var obj = {
"log": "Log Info : { \"datetime\" : \"datetime\", \"field1\" : \"value1\", \"field2\" : \"value2\", \"field3\" : \"value3\", \"field4\" : \"value4\", \"field5\" : \"value5\", \"field6\" : \"value6\", \"field7\" : \"value7\", \"field8\" : \"value8\", \"field9\" : \"value9\", \"field10\" : \"value10\", \"field11\" : \"value11\"}\n",
"stream": "stdout",
"kubernetes": {
"pod_name": "pod_name",
"namespace_name": "namespace_name",
"pod_id": "pod_id",
"host": "host",
"container_name": "container_name",
"docker_id": "docker_id",
"container_hash": "container_hash",
"container_image": "container_image"
}
}
var str = (obj.log).substring(obj.log.indexOf(':') + 1);
//console.log(str)
var result = JSON.parse(str);
console.log(result)

Generate a json file dynamically

I need to do a post request using a JSON file. The JSON is currently looking like this:
{
"compositeRequest" : [{
// Account
"method" : "POST",
"url" : "/services/data/v52.0/sobjects/Account",
"referenceId" : "refAccount",
"body" : {
"Name" : req.body.accName
}
},{
// Contact
"method" : "POST",
"url" : "/services/data/v52.0/sobjects/Contact",
"referenceId" : "refContact",
"body" : {
"LastName" : req.body.conLastName,
"AccountId" : "#{refAccount.id}"
}
},{
// Order
"method" : "POST",
"url" : "/services/data/v52.0/sobjects/Order",
"referenceId" : "refOrder",
"body" : {
"AccountId" : "#{refAccount.id}",
"Pricebook2Id" : PBResult.records[0].Id,
"EffectiveDate" : date,
"Status" : "Draft"
}
},{
// OrderItem
"method" : "POST",
"url" : "/services/data/v52.0/sobjects/OrderItem",
"referenceId" : "refOrderItem",
"body" : {
"Product2Id" : req.params.productId,
"OrderId" : "#{refOrder.id}",
"Quantity" : req.body.itemQuantity,
"PricebookEntryId" : entryResult.records[0].Id,
"UnitPrice" : entryResult.records[0].UnitPrice,
"blng__BillableUnitPrice__c": entryResult.records[0].UnitPrice,
"SBQQ__ChargeType__c": prodResult.records[0].SBQQ__ChargeType__c,
"blng__TaxRule__c": prodResult.records[0].blng__TaxRule__c,
"blng__BillingRule__c": prodResult.records[0].blng__BillingRule__c,
"blng__RevenueRecognitionRule__c": prodResult.records[0].blng__RevenueRecognitionRule__c,
"ServiceDate": date,
"blng__LastChargeToDate__c": date
}
}
]
}
I want to generate more OrderItem objects(indicated in the comment) based on the size of an array, how can I do this? I already have the data that I need to add on the body. Is it possible to create a function to create another OrderItem, and place it after the already existing one (it would even be better if I was going to create the first OrderItem from zero).
Thanks in advance.
If you want to add something to an object, you have to use
Object.assign(myObject, data);
If you want to add something to an array, you have to use:
myArray.push(data);
As I don´t really understand the structure of your data construct, I just try to refer to // OrderItem, which you marked. In this case it would be something like:
let newOrderItem = {
// OrderItem
"method" : "POST",
"url" : "/services/data/v52.0/sobjects/OrderItem",
"referenceId" : "refOrderItem",
"body" : {
"Product2Id" : req.params.productId,
"OrderId" : "#{refOrder.id}",
"Quantity" : req.body.itemQuantity,
"PricebookEntryId" : entryResult.records[0].Id,
"UnitPrice" : entryResult.records[0].UnitPrice,
"blng__BillableUnitPrice__c": entryResult.records[0].UnitPrice,
"SBQQ__ChargeType__c": prodResult.records[0].SBQQ__ChargeType__c,
"blng__TaxRule__c": prodResult.records[0].blng__TaxRule__c,
"blng__BillingRule__c": prodResult.records[0].blng__BillingRule__c,
"blng__RevenueRecognitionRule__c": prodResult.records[0].blng__RevenueRecognitionRule__c,
"ServiceDate": date,
"blng__LastChargeToDate__c": date
}
yourObject.compositeRequest.push(newOrderItem)

AngularJS 1.x - $scope inspections shows $scope.data but direct access to $scope.data == undefined

I am watching $scope.taskId and then trying to access a property on $scope.data.
Here's my function:
$scope.$watch('taskId', function(value) {
console.log('here---------------');
console.log($scope, $scope.data);
var titlePrefix = undefined;
if (value) {
titlePrefix = $scope.getTaskTitlePrefix();
Page.setTitle(titlePrefix + $scope.taskId);
$scope.loadData();
}
});
I am logging $scope and $scope.data above in line 3.
(console.log($scope, $scope.data);)
Here's the output in the console:
here---------------
m {$$childTail: m, $$childHead: b, $$nextSibling: m, $$watchers:
Array(81), $$listeners: Object…}
undefined
Any ideas why $scope seems to be ready and available but its variables are not??
This is the HTML where the taskId variable is initialised and as you can see there is a whole lot going on here. This is a major Laravel and Angular application with more than 2700 pages without including vendor or node folders (1700+ Laravel, 1000+ angular)
<div ng-controller="TasksCtrl" ng-init="taskId = '{!! $task->id !!}'" ng-cloak>
<span ng-init="severities = {{ json_encode($severities) }}"></span>
<span ng-init="statuses = {{ $statuses }}"></span>
<span ng-init="users = {{ $users }}"></span>
<span ng-init="subtypes = {{ App\Modules\Bookings\TaskSubtype::support()->get() }}"></span>
<span ng-init="standard_prices = {{ StandardPrice::all() }}"></span>
<span ng-init="shelf_types = {{ json_encode(App\Modules\Bookings\Task::getShelfTypes()) }}"></span>
That is an excerpt from tasks.blade.php file which is the content section of the page.
The actual title is used in layouts.blade.php and it actually sets the title of the browser tab and NOT the title of any "on page" heading.
>head<
>meta charset="utf-8"<
>meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"<
<title ng-controller="TitleController" ng-cloak>{[{ Page.getTitle() }]}</title>
This is the getTitle function that is called into play when the taskId changes.
archDB.factory('Page', function () {
var title = 'Seraph';
return {
getTitle: function() { return title; },
setTitle: function(newTitle) { title = newTitle; }
};
});
And here's the $scope.data variable part of the $scope inspection from the browser console to give a sense of scale.
data: m
$promise
:
d
$resolved
:
true
alarm_date
:
null
antivirus_state
:
null
assigned_to
:
104
attended_time
:
0
auto_booked
:
1
booking_fee
:
null
booking_fee_id
:
null
builds
:
Array(0)
cancelled_reason
:
null
client
:
Object
client_id
:
53
client_type
:
"client"
collected_at
:
null
completed
:
0
completed_at
:
null
created_at
:
"2016-12-07 11:23:03"
created_by
:
16
creator
:
Object
customer_notifications
:
Array(0)
deleted_at
:
null
delivered
:
0
delivered_by
:
null
devices
:
Array(0)
direct_dial
:
null
due_date
:
null
exchange_id
:
null
feedback
:
null
followup_id
:
null
formatedAttendedTime
:
""
formatedUnattendedTime
:
""
id
:
84222
invoice_number
:
null
invoiced
:
0
invoiced_at
:
null
invoiced_by_project
:
0
labour
:
0
modifier
:
Object
needs_calling
:
0
needs_delivery
:
null
no_price_reason
:
null
nopassword_reason
:
null
onsite_end
:
"0000-00-00 00:00:00"
onsite_start
:
"0000-00-00 00:00:00"
order_task_id
:
null
paid
:
0
paid_at
:
"2016-12-07"
parts
:
Array(0)
parts_total
:
0
passed_qa
:
null
passwords
:
Array(0)
pin
:
null
points
:
0
prebook
:
0
prebook_date
:
"01-01-1970"
problem
:
" removed"
project_id
:
null
qa_id
:
null
qa_tasks
:
Array(0)
related_tasks
:
Array(0)
return_id
:
null
revision_history
:
Array(0)
satisfied_client
:
null
seraph_id
:
null
severity_id
:
2
shelf
:
null
shelf_type
:
null
site
:
Object
site_id
:
53
site_user
:
Object
site_user_id
:
535
standard_price
:
null
standard_price_id
:
null
status
:
Object
status_id
:
1
subscribed_user
:
Array(0)
subscribers
:
Array(0)
subtype_id
:
1
template_items
:
Array(0)
templates
:
Array(0)
time_spent
:
0
title
:
"For Nadeem"
type
:
"support"
unattended_time
:
0
updated_at
:
"2016-12-07 11:24:04"
updated_by
:
94
user
:
Object
---------------- edit 00.14 -----------------
Here's a loadData function that makes an ajax call to the laravel api and the response gets assigned to $scope.data there
$scope.loadData = function() {
Tasks.get({taskId: $scope.taskId}, function(response){
$scope.data = response;
$scope.modified = false;
CustomerNotificationsService.setNotifications(response.customer_notifications);
$ClientsManager.setClient(response.client);
$ClientsManager.setClientType(response.client_type);
$scope.registerWatchers();
}, ErrorsHandler);
};
Simple fix actually;
Simply watched the data property I was interested in, in new $watch and pulled the call to Page.setTitle in to it.
$scope.$watch('taskId', function(value) {
if (value) {
$scope.loadData();
}
});
// set browser tab title prefix
$scope.$watch('data.type', function(value) {
var browserTabTitlePrefix = undefined;
if(typeof value != 'undefined') {
browserTabTitlePrefix = $scope.getBrowserTabTitlePrefix(value);
Page.setTitle(browserTabTitlePrefix + $scope.taskId);
}
});
Now because I'm watching the right property and only calling the sub-function (Page.setTitle) once it is ready I'm golden.
Alhamdulillaah katheerun

Return value from firebase database Javascript

My attempts at retrieving the value of a firebase record are failing. My JSON is as follows:
{
"accounts" : {
"-KRPSyO4B48IpBnHBTYg" : {
"dateCreated" : "",
"email" : "",
"provider" : "",
"userId" : ""
}
},
"products" : {
"-KUKRafaNurpFhGF4jQa" : {
"name" : ""
}
},
"total" : 1
}
I'm trying to return the value of "total". Here's the latest attampt:
var totals = firebase.database().ref('total').once('value', function(products) {});
$scope.totalPosts = totals;
and my HTML:
<div class="card" ng-controller="myController">{{totalPosts}}</div>
All I'm getting is an empty {}. What am I doing wrong?
Thanks in advance!
Firebase queries are asynchronous, try this.
firebase.database().ref('total').once('value', function(products) {
$scope.totalPosts = products.val();
});
Read and write Data

sap.m.UploadCollection, doesn't work

i try to implement the UploadCollection, according to this example. But i can`t make it runnable.
DataMock:
var data = {
"attachments" : [
{
"contributor" : "Susan Baker",
"documentId" : "64469d2f-b3c4-a517-20d6-f91ebf85b9da",
"enableEdit" : true,
"enableDelete" : true,
"fileName" : "Screenshot.jpg",
"fileSize" : 20,
"mimeType" : "image/jpg",
"thumbnailUrl" : "",
"uploadedDate" : "2014-07-30",
"url" : "image/orianda.png"
}, {
"contributor" : "John Smith",
"documentId" : "5082cc4d-da9f-2835-2c0a-8100ed47bcde",
"enableEdit" : true,
"enableDelete" : false,
"fileName" : "Notes.txt",
"fileSize" : 10,
"mimeType" : "text/plain",
"thumbnailUrl" : "",
"uploadedDate" : "2014-08-01",
"url" : "image/orianda.png"
}
]};
Dosen`t work
sap.ui.getCore().setModel(new sap.ui.model.json.JSONModel(), "runtime" )
var oRuntime = sap.ui.getCore().getModel("runtime");
Runtime.setData( data );
and view.xml:
<UploadCollection id="UploadCollection" maximumFilenameLength="55" multiple="true" change="onChange" fileDeleted="onFileDeleted" fileRenamed="onFileRenamed" fileSizeExceed="onFileSizeExceed" typeMissmatch="onTypeMissmatch" uploadComplete="onUploadComplete" items="{runtime>/attachments}">
<items>
<UploadCollectionItem contributor="{contributor}" documentId="{documentId}" fileName="{fileName}" fileSize="{fileSize}" mimeType="{mimeType}" thumbnailUrl="{thumbnailUrl}" uploadedDate="{uploadedDate}" url="{url}" enableEdit="{enableEdit}" enableDelete="{enableDelete}" />
</items>
</UploadCollection>
Works almost:
sap.ui.getCore().setModel(new sap.ui.model.json.JSONModel() )
var oRuntime = sap.ui.getCore().getModel();
Runtime.setData( data );
and view.xml:
<UploadCollection id="UploadCollection" maximumFilenameLength="55" multiple="true" change="onChange" fileDeleted="onFileDeleted" fileRenamed="onFileRenamed" fileSizeExceed="onFileSizeExceed" typeMissmatch="onTypeMissmatch" uploadComplete="onUploadComplete" items="{/attachments}">
<items>
<UploadCollectionItem contributor="{contributor}" documentId="{documentId}" fileName="{fileName}" fileSize="{fileSize}" mimeType="{mimeType}" thumbnailUrl="{thumbnailUrl}" uploadedDate="{uploadedDate}" url="{url}" enableEdit="{enableEdit}" enableDelete="{enableDelete}" />
</items>
</UploadCollection>
The first version loads the two items, but the values for each item is empty.
The second version loads the items correct. The only difference is the named model.
Both versions throw an error, when i try to upload something.
Cannot read property 'addEventListener' of undefined -
What did i wrong?
update: i figured out; its caused by the mock server.The rootURI dosent macht with the upload URI, therefore it should not influents it.
I will open a bug report, if someone can confirm me that this is a bug.
jQuery.sap.require("sap.ui.core.util.MockServer");
var sMockdataBaseUrl = "testdata/data/"
var sMetadataUrl = "testdata/metadata.xml"
sap.ui.core.util.MockServer.config({
autoRespond : true,
autoRespondAfter : 3000
});
var oMockServer = new sap.ui.core.util.MockServer({
rootUri : '/server/'
});
oMockServer.simulate(sMetadataUrl, {
'sMockdataBaseUrl' : sMockdataBaseUrl,
'bGenerateMissingMockData' : true
});
oMockServer.start();
I replicated the scenario and it is perfectly working fine.
Here is example I tried.
https://github.com/Sarathchandrach/openui5examples/tree/master/UploadCollectionDemo.
and Sample code I tried.
Controller:
var oModel = new sap.ui.model.json.JSONModel();
oModel.setData({
modelData: data
});
this.getView().setModel(oModel, "oAppView");
View:
<UploadCollection id="UploadCollection" maximumFilenameLength="55" multiple="true" change="onChange" fileDeleted="onFileDeleted" fileRenamed="onFileRenamed" fileSizeExceed="onFileSizeExceed" typeMissmatch="onTypeMissmatch" uploadComplete="onUploadComplete" items="{oAppView>/modelData/attachments}">
<items>
<UploadCollectionItem contributor="{oAppView>contributor}" documentId="{oAppView>documentId}" fileName="{oAppView>fileName}" fileSize="{oAppView>fileSize}" mimeType="{oAppView>mimeType}" thumbnailUrl="{oAppView>thumbnailUrl}" uploadedDate="{oAppView>uploadedDate}" url="{oAppView>url}" enableEdit="{oAppView>enableEdit}" enableDelete="{oAppView>enableDelete}" />
</items>
</UploadCollection>

Categories