function getCustomAudienceBatchSender()

in src/utils/batchSenders.js [168:255]


function getCustomAudienceBatchSender(
  accessToken: string,
  audienceID: string,
  sessionID: ?number,
  mapping: Object,
  method: 'POST' | 'DELETE',
  appIDs: ?Array<string>,
  pageIDs: ?Array<string>,
): {
  batchSender: BatchSender,
  lastDummyBatchSender: () => Promise<void>,
} {
  if (sessionID == null) {
    sessionID = Math.floor(Math.random() * UINT_MAX);
  }
  const columns = getColumnsFromMappingsForCustomAudience(mapping);
  const schema = columns.map(column => column.toUpperCase());
  const batchSender = (batch: Batch) => {
    return new Promise((resolve, reject) => {
      const data = batch.rows.map(row => {
        const normalizedValue = JSON.parse(JSON.stringify(row));
        return columns.map(propKey => {
          propKey = propKey.toLowerCase();
          let value, parent;
          if (normalizedValue[propKey] != null) {
            value = normalizedValue[propKey];
            parent = normalizedValue;
          } else if (
            normalizedValue.match_keys != null &&
            normalizedValue.match_keys[propKey]
          ) {
            value = normalizedValue.match_keys[propKey];
            parent = normalizedValue.match_keys;
          }
          if (Array.isArray(value)) {
            value = value.shift();
          } else if (parent != null) {
            parent[propKey] = null;
          }
          return value || '';
        });
      });
      const params: Object = {
        access_token: accessToken,
        payload: {
          app_ids: appIDs,
          page_ids: pageIDs,
          schema,
          data,
        },
        session: {
          last_batch_flag: false,
          session_id: sessionID,
        },
      };
      const {
        thenCallback,
        catchCallback,
      } = getGraphAPICallbacks(resolve, reject, batch);
      graphAPI(`${audienceID}/users`, method, params)
        .catch(catchCallback)
        .then(thenCallback);
      winston.debug(`Batch [${batch.start}, ${batch.end}): sending`);
    });
  };
  const lastDummyBatchSender = () => {
    const params: Object = {
      access_token: accessToken,
      payload: {
        app_ids: appIDs,
        page_ids: pageIDs,
        schema,
        // A row of dummy data (non zero) as payload.
        data: [schema.map(() => '1')],
      },
      session: {
        batch_seq: 1,
        last_batch_flag: true,
        session_id: sessionID,
      },
    };
    return graphAPI(`${audienceID}/users`, method, params);
  };
  return {
    batchSender,
    lastDummyBatchSender,
  };
}