export async function createIndexTriggerHandler()

in storage-reverse-image-search/functions/src/functions/create_index_trigger.ts [25:62]


export async function createIndexTriggerHandler(
  change: functions.Change<functions.firestore.QueryDocumentSnapshot>
) {
  const statusAfter = change.after.get('status');
  const statusBefore = change.before.get('status');

  if (!statusAfter || statusAfter === statusBefore) return;

  const doc = await admin.firestore().doc(config.metadataDoc).get();

  const {outputShape} = doc.data()
    ? (doc.data() as {outputShape?: number})
    : {outputShape: null};

  if (!outputShape || typeof outputShape !== 'number') {
    functions.logger.error(
      'Could not trigger index creation, output shape is not defined in task document.'
    );
    return;
  }

  if (statusAfter === BackfillStatus.DONE) {
    functions.logger.log(
      `Backfill task is done, creating the index with ${outputShape} dimensions...`
    );

    const operation = await createIndex(outputShape);
    functions.logger.log('Index creation initiated!', operation);

    await admin.firestore().doc(config.metadataDoc).set(
      {
        status: IndexStatus.BUILDING,
        operation,
      },
      {merge: false}
    );
  }
}