0

Suppose I wrote this function to scrape a title and description from a webpage

getMetadata.ts

import * as functions from "firebase-functions";
import metascraper from "metascraper";
import metascraperTitle from "metascraper-title";
import metascraperDescription from "metascraper-description";

export const getMetadata = functions.https.onCall(async (data, context) => {
  try {
    const url = data.url;
    const res = await fetch(url);
    const html = await res.text();
    const metadata = await metascraper([
      metascraperTitle(),
      metascraperDescription(),
    ])({html, url});
    return {
      title: metadata.title,
      description: metadata.description,
    };
  } catch (error) {
    functions.logger.error(error);
  }
  return false;
});

Now I want to write another callable that will call the getMetadata functions and save the new bookmark in firestore

saveBookmark.ts

import * as functions from "firebase-functions";
import * as admin from "firebase-admin";


export const saveBookmark = functions.https.onCall(async (data, context) => {
  const url = data.url;
  // TODO instantiate callable function getMetadata(url);

  // TODO get metadata from url

  // const metadata = await getMetadata(url);

  // TODO Save to bookmarks collection
  admin.firestore().collection("bookmarks").doc().set({
    url: url,
    // title: metadata.title
    createdAt: Date.now(),
  });
});

Can you please help me improve this code?

Julien Reszka
  • 888
  • 12
  • 25
  • You should just make a shared common TypeScript function that can be invoked from from either Cloud Function. It will be a lot easier than trying to implement the callable protocol yourself, it will perform better, and cost less. – Doug Stevenson May 12 '23 at 16:11
  • Also your code is not awaiting the result of `set()`, which means it will fail unpredictably, without meaningul notice or logs to tell you that happened. – Doug Stevenson May 12 '23 at 16:22

0 Answers0