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()
}
Related
window.onload = function () {
const user_name =
NAME_ARRAY[Math.round(Math.random() * NAME_ARRAY.length)];
document.getElementById("userName_profile").innerHTML = user_name;
document.getElementById("userName").innerHTML = user_name;
const btn = document.querySelector("#sendMessage");
const textfield = document.querySelector("#messageInput");
const log = document.querySelector("#messageArea");
// +++++++++++++++ For chat messaging system ++++++++++++
NAF.connection.subscribeToDataChannel(
"chat",
(senderId, dataType, data, targetId) => {
console.log("msg", data, "from", senderId, targetId);
messageArea.innerHTML += senderId + ": " + data.txt + "<br>";
}
);
btn.addEventListener("click", (evt) => {
NAF.clientId = user_name;
messageArea.innerHTML +=
NAF.clientId + ": " + textfield.value + "<br>";
NAF.connection.broadcastData("chat", { txt: textfield.value });
document.getElementById("messageInput").value = "";
// NAF.easy = user_name;
});
}
When I've made chat system and working fine. The only, issue is that I want a user name rather than a client id. Please, help with this.
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);
}
);
}
});
});
}
I've been struggling with this piece of code for a while and I'm reaching out for help. I have a array of dates and I"m trying to make http requests in order of the array and to write the return information, also in order.
Here is my code:
const dateArray = ['november-22-2019', 'november-25-2019', 'november-26-2019', 'november-27-2019', 'november-29-2019'];
async function loppThroughArray() {
for (const date of dateArray) {
const options = {
url: process.env.URL + date
};
await asyncRequest(options, date);
}
}
async function asyncRequest(options, date) {
request(options, function(error, response, html) {
if (error) {
return;
}
if (response.statusCode !== 200) {
return;
}
const $ = cheerio.load(html);
const content = $('.entry-content');
const formattedContent = content.text()
.split('\t').join('')
.split('\n\n\n').join('')
.split('\n\n').join('');
const dataToBeWritten = '### ' + date + '\n' + formattedContent + '\n\n';
fs.appendFileSync(`./WODs/${currentDate}.md`, dataToBeWritten, 'utf-8', {'flags':'a+'});
fs.appendFileSync(`./WODs/${currentDate}.txt`, dataToBeWritten, 'utf-8', {'flags':'a+'});
});
}
loppThroughArray();
I managed to solve this by using a version of 'request' that uses promises instead of callbacks. See code:
async function loppThroughArray() {
for (const date of dateArray) {
const options = {
url: process.env.URL + date
};
await asyncRequest(options, date);
console.log('fetching: ', date);
}
}
async function asyncRequest(options, date) {
await rp(options)
.then(function(html){
const $ = cheerio.load(html);
const content = $('.entry-content');
const formattedContent = content.text()
.split('\t').join('')
.split('\n\n\n').join('')
.split('\n\n').join('');
const dataToBeWritten = '### ' + date + '\n' + formattedContent + '\n\n';
fs.appendFileSync(`./WODs/${currentDate}.md`, dataToBeWritten, 'utf-8', {'flags':'a+'});
fs.appendFileSync(`./WODs/${currentDate}.txt`, dataToBeWritten, 'utf-8', {'flags':'a+'});
});
}
loppThroughArray();
I'm using Sqlite plugin in my ionic 3 app.
I have saved and fetched data successfully but when I use Where Clause for fetching data against specific ID using following Query:
const query = "SELECT * FROM " + `${table}` + " WHERE project_id=" + `${project_id}`;
this.database.executeSql(query, []).then((result) => {
console.log('RESULT: '+ JSON.stringify(result));
}, err => {
console.error('Error: '+ err);
});
What am I doing wrong?
Change your query as follows and you will get the response.
const query = "SELECT * FROM " + `${table}` + " WHERE project_id=?";
this.database.executeSql(query, [project_id]).then((result) => {
console.log('RESULT: '+ JSON.stringify(result));
}, err => {
console.error('Error: '+ err);
});
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"
});
});