Я пытаюсь добавить анекдоты о детонации в базу данных Firebase, используя выполнение Dialogflow. В настоящее время массив, который я объявляю, переписывается для каждой записи, и мои функции чтения не могут получить правильные данные.
Есть ли способ добавить новый массив из двух строковых значений, punch1 и punch2, без перезаписи? Есть ли другая структура данных, которую я должен использовать?
Кроме того, если у меня есть другая ссылка на массив массивов для чтения, как я могу рандомизировать выбранное поле и затем возвращать значения индекса 0 и 1 при появлении запроса?
Я пробовал карты, помещая значение в массив так, чтобы каждый добавленный массив содержал все предыдущие данные, и помещая значения непосредственно в ссылку на документ.
let arr1 = [];
let rand;
function WriteArrayToFirestorepunch1 (agent) {
// Get parameter from Dialogflow with the string to add to the database
const punchline1 = agent.parameters.punchline1;
arr1.push(punchline1);
// Get the database collection 'dialogflow' and document 'write' and store
// the document {entry: "<value of database entry>"} in the 'write' document
const dialogflowAgentRef = db.collection('dialogflow').doc('write');
return db.runTransaction(t => {
t.set(dialogflowAgentRef, {joke:arr1});
return Promise.resolve('Write complete');
}).then(doc => {
agent.add(`"${punchline1}" who?`);
}).catch(err => {
console.log(`Error writing to Firestore: ${err}`);
agent.add(`Failed to write "${punchline1}" to the Firestore database.`);
});
}
function WriteArrayToFirestorepunch2 (agent) {
// Get parameter from Dialogflow with the string to add to the database
const punchline2 = agent.parameters.punchline2;
arr1.push(punchline2);
// Get the database collection 'dialogflow' and document 'write' and store
// the document {entry: "<value of database entry>"} in the 'write' document
const dialogflowAgentRef = db.collection('dialogflow').doc('write').push();
return db.runTransaction(t => {
t.set(dialogflowAgentRef, {jokeys:arr1});
return Promise.resolve('Write complete');
}).then(doc => {
agent.add(`Good joke! I think. I've written it into my database for further evaluation.`);
}).catch(err => {
console.log(`Error writing to Firestore: ${err}`);
agent.add(`Failed to write "${punchline2}" to the Firestore database.`);
});
}
function readFromDb1 (agent) {
// Get the database collection 'dialogflow' and document 'agent'
const dialogflowAgentDoc = db.collection('dialogflow').doc('agent');
rand = Math.random() * (3-0)+0;
// Get the value of 'entry' in the document and send it to the user
return dialogflowAgentDoc.get()
.then(doc => {
if (!doc.exists) {
agent.add('No data found in the database!');
} else {
agent.add(doc.data()[rand][0]);
}
return Promise.resolve('Read complete');
}).catch(() => {
agent.add('Error reading entry from the Firestore database.');
agent.add('Please add a entry to the database first by saying, "Write <your phrase> to the database"');
});
}
function readFromDb2 (agent) {
// Get the database collection 'dialogflow' and document 'agent'
const dialogflowAgentDoc = db.collection('dialogflow').doc('agent');
// Get the value of 'entry' in the document and send it to the user
return dialogflowAgentDoc.get()
.then(doc => {
if (!doc.exists) {
agent.add('No data found in the database!');
} else {
agent.add(doc.data()[rand][1]);
}
return Promise.resolve('Read complete');
}).catch(() => {
agent.add('Error reading entry from the Firestore database.');
agent.add('Please add a entry to the database first by saying, "Write <your phrase> to the database"');
});
}
Запись. Мне бы хотелось, чтобы 2 значения добавлялись в сохраненный массив после каждого взаимодействия, или каждый раз добавлялся новый массив из 2 значений. В настоящее время единственное число переписывается каждый раз.
Чтение. Я бы хотел, чтобы был выбран случайный массив от 0 до 3, индекс 0 возвращался из первой функции, а индекс 1 возвращался из второй функции. В настоящее время не работает.