Функции Firebase: syn c с Algolia не работает - PullRequest
2 голосов
/ 28 мая 2020

В настоящее время я пытаюсь синхронизировать c мои документы firestore с algolia при создании нового или обновлении документа. Путь к коллекции в firestore - видео / видео. Кажется, что функция запускается нормально, однако после запуска функция firebase, похоже, не передает какую-либо информацию в algolia (записи не создаются). Я не получаю ошибок в журнале. (Я также дважды проверил правила и убедился, что узел может быть прочитан по умолчанию, и да, я нахожусь в плане пламени). Кто-нибудь знает, как синхронизировать c узел firestore и algolia? Спасибо за вашу помощь!

"use strict";
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const algoliasearch_1 = require("algoliasearch");
// Set up Firestore.
admin.initializeApp();
const env = functions.config();
// Set up Algolia.
// The app id and API key are coming from the cloud functions environment, as we set up in Part 1,
const algoliaClient = algoliasearch_1.default(env.algolia.appid, env.algolia.apikey);
// Since I'm using develop and production environments, I'm automatically defining 
// the index name according to which environment is running. functions.config().projectId is a default property set by Cloud Functions.
const collectionindexvideo = algoliaClient.initIndex('videos');

exports.collectionvideoOnCreate = functions.firestore.document('videos/{uid}').onCreate(async(snapshot, context) => {
  await savevideo(snapshot);
});
exports.collectionvideoOnUpdate = functions.firestore.document('videos/{uid}').onUpdate(async(change, context) => {
  await updatevideo(change);
});
exports.collectionvideoOnDelete = functions.firestore.document('videos/{uid}').onDelete(async(snapshot, context) => {
  await deletevideo(snapshot);
});
async function savevideo(snapshot) {
  if (snapshot.exists) {
    const document = snapshot.data();
    // Essentially, you want your records to contain any information that facilitates search, 
    // display, filtering, or relevance. Otherwise, you can leave it out.
    const record = {
      objectID: snapshot.id,
      uid: document.uid,
      title: document.title,
      thumbnailurl: document.thumbnailurl,
      date: document.date,
      description: document.description,
      genre: document.genre,
      recipe: document.recipe
    };
    if (record) { // Removes the possibility of snapshot.data() being undefined.
      if (document.isIncomplete === false) {
        // In this example, we are including all properties of the Firestore document 
        // in the Algolia record, but do remember to evaluate if they are all necessary.
        // More on that in Part 2, Step 2 above.
        await collectionindexvideo.saveObject(record); // Adds or replaces a specific object.
      }
    }
  }
}
async function updatevideo(change) {
  const docBeforeChange = change.before.data();
  const docAfterChange = change.after.data();
  if (docBeforeChange && docAfterChange) {
    if (docAfterChange.isIncomplete && !docBeforeChange.isIncomplete) {
      // If the doc was COMPLETE and is now INCOMPLETE, it was 
      // previously indexed in algolia and must now be removed.
      await deletevideo(change.after);
    } else if (docAfterChange.isIncomplete === false) {
      await savevideo(change.after);
    }
  }
}
async function deletevideo(snapshot) {
  if (snapshot.exists) {
    const objectID = snapshot.id;
    await collectionindexvideo.deleteObject(objectID);
  }
}

1 Ответ

2 голосов
/ 29 мая 2020

Все еще не знаю, что я сделал не так, однако, если кто-то еще застрял в этой ситуации, этот репозиторий станет отличным ресурсом: https://github.com/nayfin/algolia-firestore-sync. Я использовал его и смог правильно синхронизировать c firebase и algolia. Ура!

// Takes an the Algolia index and key of document to be deleted
const removeObject = (index, key) => {
  // then it deletes the document
  return index.deleteObject(key, (err) => {
    if (err) throw err
    console.log('Key Removed from Algolia Index', key)
  })
}
// Takes an the Algolia index and data to be added or updated to
const upsertObject = (index, data) => {
  // then it adds or updates it
  return index.saveObject(data, (err, content) => {
    if (err) throw err
    console.log(`Document ${data.objectID} Updated in Algolia Index `)
  })
}

exports.syncAlgoliaWithFirestore = (index, change, context) => {
  const data = change.after.exists ? change.after.data() : null;
  const key = context.params.id; // gets the id of the document changed
  // If no data then it was a delete event
  if (!data) {
    // so delete the document from Algolia index
    return removeObject(index, key);
  }
  data['objectID'] = key;
  // upsert the data to the Algolia index
  return upsertObject(index, data);
};
...