How can I get insight of each level (campaign,adset,ad) in a Facebook ad campaign in single query?

620 views Asked by At

I had created a method to retrieve insight data for each level of the campaign. But the problem is that I use loop to gain insight into each entity, causing my Ad Account-Level Rate Limit to reach its maximum. Is it possible to do all this in a single query? Here is my code , I'm using "facebook-nodejs-business-sdk" Facebook Business SDK in NodeJS.

const AdSetInsight = async (userId, AdInsightId, fields, params) => {
  const existingUser = await facebookAccount.findOne( userId );
  const api = adsSdk.FacebookAdsApi.init(existingUser.accessToken);
  const AdSet = adsSdk.AdSet;
  const AdSetInsight = new AdSet(AdInsightId);
  const insights = await AdSetInsight.getInsights(
    fields,
    params
  );
  return (await Promise.all(insights.map(insight => _.cloneDeep(insight)._data)));

}
    
const levelInsight = () =>{
    const { startDate, endDate } = req.query;
    let fields = ['campaign_id', 'campaign_name', 'spend', 'impressions', 'clicks', 'reach', 'cpp', 'cpm', 'cpc', 'purchase_roas', 'outbound_clicks_ctr', 'actions', 'action_values'],
      params = {
        level: 'campaign'
      };
    if (startDate && endDate) {
      params.time_range = { "since": startDate, "until": endDate }
    }
    const insights = await AdSetInsight(
      req.user._id,
      req.params.adSetId,
      fields,
      params
    );
    fields = ['adset_id', 'adset_name', 'spend', 'impressions', 'clicks', 'reach', 'cpp', 'cpm', 'cpc', 'purchase_roas', 'outbound_clicks_ctr', 'actions', 'action_values'],
      params = {
        level: 'adset'
      };
    await Promise.all(insights.map(async (insight, key) => {
      insight.adsets = await AdSetInsight(
        req.user._id,
        insight.campaign_id,
        fields,
        params
      );
      let purchaseValue = insight.action_values ? insight.action_values.filter(action => action.action_type === "omni_purchase") : 0;
      let purchases = insight.actions ? insight.actions.filter(action => action.action_type === "omni_purchase") : 0;
      let landing_page_view = insight.actions ? insight.actions.filter(action => action.action_type === "landing_page_view") : 0;
      let add_to_cart = insight.actions ? insight.actions.filter(action => action.action_type === "add_to_cart") : 0;
      let cost_per_add_to_cart = insight.action_values ? insight.action_values.filter(action => action.action_type === "omni_add_to_cart") : 0;
      let initiated_checkout = insight.actions ? insight.actions.filter(action => action.action_type === "initiated_checkout") : 0;
      let cost_per_initiated_checkout = insight.action_values ? insight.action_values.filter(action => action.action_type === "omni_initiated_checkout") : 0;
      insight.purchaseValue = parseFloat(_.get(purchaseValue, '[0].value', 0));
      insight.landing_page_view = parseFloat(_.get(landing_page_view, '[0].value', 0));
      insight.add_to_cart = parseFloat(_.get(add_to_cart, '[0].value', 0));
      insight.cost_per_add_to_cart = parseFloat(_.get(cost_per_add_to_cart, '[0].value', 0));
      insight.initiated_checkout = parseFloat(_.get(initiated_checkout, '[0].value', 0));
      insight.cost_per_initiated_checkout = parseFloat(_.get(cost_per_initiated_checkout, '[0].value', 0));
      insight.purchases = parseFloat(_.get(purchases, '[0].value', 0));
      insight.roas = parseFloat(_.get(insight, 'purchase_roas[0].value', 0)).toFixed(2);
      insight.link_ctr = parseFloat(_.get(insight, 'outbound_clicks_ctr[0].value', 0)).toFixed(2);
      delete insight.actions;
      delete insight.purchase_roas;
      delete insight.actions;
      delete insight.action_values;
      delete insight.outbound_clicks_ctr;
      fields = ['id', 'name', 'creative'],
        params = {
        };
      await Promise.all(insight.adsets.map(async (adInsight, key) => {

        const existingUser = await facebookAccount.findOne({ pondirId: req.user._id });
        const api = adsSdk.FacebookAdsApi.init(existingUser.accessToken);
        const Ads = adsSdk.AdSet;
        const AdSetAcc = new Ads(adInsight.adset_id);
        await AdSetAcc.getAds(fields,
          params).then(adDetail => {
            adInsight.ad = adDetail.map((account) => account._data);
          })
          .catch();

        let purchaseValue = adInsight.action_values ? adInsight.action_values.filter(action => action.action_type === "omni_purchase") : 0;
        let purchases = adInsight.actions ? adInsight.actions.filter(action => action.action_type === "omni_purchase") : 0;
        let landing_page_view = adInsight.actions ? adInsight.actions.filter(action => action.action_type === "landing_page_view") : 0;
        let add_to_cart = adInsight.actions ? adInsight.actions.filter(action => action.action_type === "add_to_cart") : 0;
        let cost_per_add_to_cart = adInsight.action_values ? adInsight.action_values.filter(action => action.action_type === "omni_add_to_cart") : 0;
        let initiated_checkout = adInsight.actions ? adInsight.actions.filter(action => action.action_type === "initiated_checkout") : 0;
        let cost_per_initiated_checkout = adInsight.action_values ? adInsight.action_values.filter(action => action.action_type === "omni_initiated_checkout") : 0;
        adInsight.purchaseValue = parseFloat(_.get(purchaseValue, '[0].value', 0));
        adInsight.landing_page_view = parseFloat(_.get(landing_page_view, '[0].value', 0));
        adInsight.add_to_cart = parseFloat(_.get(add_to_cart, '[0].value', 0));
        adInsight.cost_per_add_to_cart = parseFloat(_.get(cost_per_add_to_cart, '[0].value', 0));
        adInsight.initiated_checkout = parseFloat(_.get(initiated_checkout, '[0].value', 0));
        adInsight.cost_per_initiated_checkout = parseFloat(_.get(cost_per_initiated_checkout, '[0].value', 0));
        adInsight.purchases = parseFloat(_.get(purchases, '[0].value', 0));
        adInsight.roas = parseFloat(_.get(adInsight, 'purchase_roas[0].value', 0)).toFixed(2);
        adInsight.link_ctr = parseFloat(_.get(adInsight, 'outbound_clicks_ctr[0].value', 0)).toFixed(2);
        delete adInsight.actions;
        delete adInsight.purchase_roas;
        delete adInsight.actions;
        delete adInsight.action_values;
        delete adInsight.outbound_clicks_ctr;
        await Promise.all(adInsight.ad.map(async (ad, key) => {
          const AdCreative = adsSdk.AdCreative;
          fields = [
          ];
          params = {
            'ad_format': 'MOBILE_FEED_STANDARD',
          };
          if (ad.creative) {
            const previews = await (new AdCreative(ad.creative.id)).getPreviews(
              fields,
              params
            );
            ad.previews = previews.map((account) => account._data.body)[0];
          }
          fields = ['ad_id', 'ad_name', 'spend', 'impressions', 'reach', 'cpp', 'cpm', 'cpc', 'purchase_roas', 'outbound_clicks_ctr', 'actions', 'action_values'],
            params = {
              level: 'ad'
            };
          let metrics = await AdSetInsight(
            req.user._id,
            ad.id,
            fields,
            params
          );

          if (metrics.length > 0) {

            let purchaseValue = metrics[0].action_values ? metrics[0].action_values.filter(action => action.action_type === "omni_purchase") : 0;
            let purchases = metrics[0].actions ? metrics[0].actions.filter(action => action.action_type === "omni_purchase") : 0;
            let landing_page_view = metrics[0].actions ? metrics[0].actions.filter(action => action.action_type === "landing_page_view") : 0;
            let add_to_cart = metrics[0].actions ? metrics[0].actions.filter(action => action.action_type === "add_to_cart") : 0;
            let cost_per_add_to_cart = metrics[0].action_values ? metrics[0].action_values.filter(action => action.action_type === "omni_add_to_cart") : 0;
            let initiated_checkout = metrics[0].actions ? metrics[0].actions.filter(action => action.action_type === "initiated_checkout") : 0;
            let cost_per_initiated_checkout = metrics[0].action_values ? metrics[0].action_values.filter(action => action.action_type === "omni_initiated_checkout") : 0;
            ad.purchaseValue = parseFloat(_.get(purchaseValue, '[0].value', 0));
            ad.landing_page_view = parseFloat(_.get(landing_page_view, '[0].value', 0));
            ad.add_to_cart = parseFloat(_.get(add_to_cart, '[0].value', 0));
            ad.cost_per_add_to_cart = parseFloat(_.get(cost_per_add_to_cart, '[0].value', 0));
            ad.initiated_checkout = parseFloat(_.get(initiated_checkout, '[0].value', 0));
            ad.cost_per_initiated_checkout = parseFloat(_.get(cost_per_initiated_checkout, '[0].value', 0));
            ad.purchases = parseFloat(_.get(purchases, '[0].value', 0));
            ad.roas = parseFloat(_.get(metrics[0], 'purchase_roas[0].value', 0)).toFixed(2);
            ad.link_ctr = parseFloat(_.get(metrics[0], 'outbound_clicks_ctr[0].value', 0)).toFixed(2);
            ad.spend = metrics[0].spend;
            ad.reach = metrics[0].reach;
            ad.cpp = metrics[0].cpp;
            ad.cpm = metrics[0].cpm;
            ad.impressions = metrics[0].impressions;
            ad.cpc = metrics[0].cpc;
            ad.ad_name = metrics[0].ad_name;
            ad.ad_id = metrics[0].ad_id;
            delete metrics[0].actions;
            delete metrics[0].purchase_roas;
            delete metrics[0].actions;
            delete metrics[0].action_values;
            delete metrics[0].outbound_clicks_ctr;
          }
          ad.ad_id = ad.ad_id ? ad.ad_id : ad.id;
          ad.ad_name = ad.ad_name ? ad.ad_name : ad.name;
          delete ad.id;
          delete ad.name;
          if (ad.spend === "0") {
            delete adInsight.ad.splice(key, 1);
          }
        }))
        if (adInsight.spend === "0") {
          delete insight.adsets.splice(key, 1);;
        }
      }))
      if (insight.spend === "0") {
        delete insights.splice(key, 1);;
      }
    }))
    sendSuccessResponse(res, { data: insights });
  }
0

There are 0 answers