Any idea why I can't use childByAutoId?
exports.addPersonalRecordHistory = functions.database.ref('/personalRecords/{userId}/current/{exerciseId}')
.onWrite(event => {
var path = 'personalRecords/' + event.params.userId + '/history/' + event.params.exerciseId;
var reference = admin.database().ref(path).childByAutoId();
reference.set({
username: "asd",
email: "asd"
});
});
Error
TypeError: admin.database(...).ref(...).childByAutoId is not a function
at exports.addPersonalRecordHistory.functions.database.ref.onWrite.event (/user_code/index.js:18:111)
childByAutoId() is for the iOS SDK. For admin.Database(), use push().
var reference = admin.database().ref(path).push();
It should work like this:
exports.addPersonalRecordHistory = functions.database.ref('/personalRecords/{userId}/current/{exerciseId}').onWrite(event => {
var path = 'personalRecords/' + event.params.userId + '/history/' + event.params.exerciseId;
return admin.database().ref(path).set({
username: "asd",
email: "asd"
});
});
Related
I'm facing some problem and I'm still new with this react native and SQLite thing but how do I delete a data from database if the create method is like this?
simpanCatatan = async () => {
const { navigation } = this.props
const date = new Date()
const dateNow = date.getDate() + " " + bulan[date.getMonth()] + " " + date.getFullYear()
await Catatan.create({
title: this.state.title,
value: this.state.catatan,
user_id: this.state.user_id,
video_id: this.state.idVideo,
video_name: this.state.namaVideo,
materi_id: this.state.idMateri,
created_at:dateNow
})
navigation.goBack()
navigation.state.params.getAllCatatan()
}
First post from a non-development expert. I have been scouring the libraries and online resources on how to use Dialogflow Fulfilment to integrate with the Google Calendar API. I am able to set the start and end times, the summary, description, location successfully in the Google Calendar, but I am unable to add attendees successfully. I have tried many variations on the attendees format. Here is the code I am using I removed the private key for security reasons. One note when I used the square brackets as some sites suggested I always received a response that the time was already booked.
'use strict';
const functions = require('firebase-functions');
const {google} = require('googleapis');
const {WebhookClient} = require('dialogflow-fulfillment');
// Enter your calendar ID below and service account JSON below
const calendarId = 'piec3rnlo2v2p2cemgjdjfctmg#group.calendar.google.com';
const serviceAccount = {
"type": "service_account",
"project_id": "whatduewhen2020v1-kgwjyd",
"private_key_id": "2a2dead3e050ef295cfef9c2c27bd2ac7d2b7471",
"private_key": "-----BEGIN PRIVATE KEY-----,
"client_email": "google-calendar#whatduewhen2020v1-kgwjyd.iam.gserviceaccount.com",
"client_id": "114290887729963225819",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/google-calendar%40whatduewhen2020v1-kgwjyd.iam.gserviceaccount.com"
}; // Starts with {"type": "service_account",...
// Set up Google Calendar Service account credentials
const serviceAccountAuth = new google.auth.JWT({
email: serviceAccount.client_email,
key: serviceAccount.private_key,
scopes: 'https://www.googleapis.com/auth/calendar'
});
const calendar = google.calendar('v3');
process.env.DEBUG = 'dialogflow:*'; // enables lib debugging statements
const timeZone = 'America/Toronto';
const timeZoneOffset = '-05:00';
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
console.log("Parameters", agent.parameters);
const appointment_type = agent.parameters.AppointmentType;
const attendee_email = agent.parameters.email;
const attendee_phone = agent.parameters.phone_number;
const attendee_firstname = agent.parameters.given_name;
const attendee_lastname = agent.parameters.last_name;
function makeAppointment (agent) {
// Calculate appointment start and end datetimes (end = +1hr from start)
//console.log("Parameters", agent.parameters.date);
const dateTimeStart = new Date(Date.parse(agent.parameters.date.split('T')[0] + 'T' + agent.parameters.time.split('T')[1].split('-')[0] + timeZoneOffset));
const dateTimeEnd = new Date(new Date(dateTimeStart).setHours(dateTimeStart.getHours() + 1));
const appointmentTimeString = dateTimeStart.toLocaleString(
'en-US',
{ month: 'long', day: 'numeric', hour: 'numeric', timeZone: timeZone }
);
// Check the availibility of the time, and make an appointment if there is time on the calendar
return createCalendarEvent(dateTimeStart, dateTimeEnd, appointment_type, attendee_email, attendee_phone, attendee_firstname, attendee_lastname).then(() => {
agent.add(`Excellent, it looks like ${appointmentTimeString} is available and we have reserved the time for you!.`);
}).catch(() => {
agent.add(`I'm so sorry, it looks like we're already booked on ${appointmentTimeString} is there an alternate day or time you are available?`);
});
}
let intentMap = new Map();
intentMap.set('Schedule Appointment', makeAppointment);
agent.handleRequest(intentMap);
});
function createCalendarEvent (dateTimeStart, dateTimeEnd, appointment_type, attendee_email, attendee_phone, attendee_firstname, attendee_lastname) {
return new Promise((resolve, reject) => {
calendar.events.list({
auth: serviceAccountAuth, // List events for time period
calendarId: calendarId,
timeMin: dateTimeStart.toISOString(),
timeMax: dateTimeEnd.toISOString()
}, (err, calendarResponse) => {
// Check if there is a event already on the Calendar
if (err || calendarResponse.data.items.length > 0) {
reject(err || new Error('Requested time conflicts with another appointment'));
} else {
// Create event for the requested time period
calendar.events.insert({ auth: serviceAccountAuth,
calendarId: calendarId,
resource: {summary: ' Membership Discussion' + ' ' + attendee_email + ' ' + attendee_phone ,
description: ' Membership Discussion' + ' ' + attendee_email + ' ' + attendee_phone,
location: 'Call ' + attendee_firstname + ' ' + attendee_lastname + ' at ' + attendee_phone,
start: {dateTime: dateTimeStart},
end: {dateTime: dateTimeEnd},
attendees: { email: 'new#example.com'} },
}, (err, event) => {
err ? reject(err) : resolve(event);
}
);
}
});
});
}
Yesterday my app was launched, Ionic v1, and a few users entered the wrong password and can't log into the app.
The app uses firebase authentication. I have a __refs file that points to the database and have tried numerous things trying to get the reset to work.
I've tried referencing $firebaseAuth, of course my __refs, $firebase then use $firebase.auth()...
I didn't write the authentication of this app so I'm not real sure how it works. I'm hoping that someone can help me.
My reset controller
angular.module('formulaWizard').controller('ResetPasswordCtrl',
function($scope, $ionicLoading, $firebaseAuth, __Refs) {
$scope.user = {
email: ''
};
$scope.errorMessage = null;
var fbAuth = $firebaseAuth(__Refs.rootRef);
$scope.resetPassword = function() {
$scope.errorMessage = null;
$ionicLoading.show({
template: 'Please wait...'
});
fbAuth.sendPasswordResetEmail($scope.user.email)
.then(showConfirmation)
.catch(handleError);
};
function showConfirmation() {
$scope.emailSent = true;
$ionicLoading.hide();
}
function handleError(error) {
switch (error.code) {
case 'INVALID_EMAIL':
case 'INVALID_USER':
$scope.errorMessage = 'Invalid email';
break;
default:
$scope.errorMessage = 'Error: [' + error.code + ']';
}
$ionicLoading.hide();
}
});
My Refs file
angular.module('formulaWizard')
.factory('__Refs', function ($firebaseArray, $firebaseObject) {
// Might use a resource here that returns a JSON arrayf
var ref = new Firebase('https://firebasedatabase.com/');
return {
rootRef: ref,
customers: ref.child('customers'),
}
});
I can't take credit for the answer it was provide by Abimbola Idowu on HackHands.
Since I paid for the answer I thought I would share it with anyone else that might also be stumped by this.
$scope.resetPassword = function() {
$scope.errorMessage = null;
$ionicLoading.show({
template: 'Please wait...'
});
__Refs.rootRef.resetPassword({ email: $scope.user.email }, function(error) {
if (error === null) {
showConfirmation();
} else {
handleError()
}
});
};
This is the __refs service
angular.module('formulaWizard')
.factory('__Refs', function ($firebaseArray, $firebaseObject) {
// Might use a resource here that returns a JSON arrayf
var ref = new Firebase('https://firebasedatabase.com/');
return {
rootRef: ref,
}
});
I am using firebase realtime database for chat feature in my application, I just need to return an Obserable of type any or type Message from firebase query,
Here is my code:
getMessageHistory(farmerId) {
let chatMessages = [];
var chats;
firebase.database().ref('/' + this.chatUrl + '/' + farmerId + '/').once('value', function (snapshot) {
chats = snapshot.val();
if (chats != null) {
Object.keys(chats).forEach(element => {
let chat = chats[element.toString()];
var Message = {
fromId: chat.from,
toId: chat.to,
message: chat.message
}
let mockedHistory: Array<Message>;
mockedHistory.push(Message)
});
}
else {
}
});
}`
How do I return Observable from above method. I have tried angularfire2 but throwing an error while compiling (Angular Version 4)
Got the solution but I don't know is it recommended or not!
let mockedHistory: Array<Message> = [];
let totalRecords = this.db.list('/' + this.chatUrl + '/' + userId + '/');
return totalRecords.valueChanges<any>().map((chat)=>{
var newChat = chat.map((message) => {
let msg = new Message();
msg.fromId = message.from;
msg.toId= message.to,
msg.message= message.message
return msg;
});
return newChat;
}
)
I'm using firebase in angular/ionic 2 and I need to check if a value exists and to create it if it doesn't however firebase is not returning null as it states in the docs and my check does not run because of it.
subscribeToOffer(uid, offerID) {
var path = 'users/' + uid + '/offers/' + offerID;
this.rootRef.child(path).on('value', subscribed => {
if (subscribed.val() !== null) {
console.log('subscribed');
} else {
console.log('not subscribed');
}
});
}
Here i have write a simple function for you that will return true if offer id exist and false in other case.
subscribeToOffer(userId,offerId){
var userRef = new Firebase(FBURL+'users');
var userOfferRef = userRef.child(userId).child("offers");
return userOfferRef.on("value", function(snap) {
var offerIds = snap.val();
return !!offerIds.hasOwnProperty(offerId);
});
};