Sample code for 30+ languages & platforms
React Native Requires Chilkat v11.5.0+

Box: Poll User Events and Save a Checkpoint

See more Box Examples

Poll the authenticated user event stream in bounded batches. The local JSON checkpoint keeps processed event IDs and the next stream position. This single-process demonstration logs events; a production worker should commit its business action, deduplication record, and cursor transactionally and prune old IDs.

See the Box API guide for setup and the complete workflow.

Chilkat React Native Downloads

React Native
import { FileAccess, HttpCurl, JsonObject, StringBuilder } from '@chilkat/react-native'

async function chilkatExample() {
  let success = false;

  // Requires Chilkat 11.5.0 or later and a previously unlocked Chilkat bundle.
  // See Global Unlock Sample.
  // Guide: Box API Guide.

  success = false;

  // Supply an unexpired token obtained with one of the Box authentication examples.
  // A token represents a particular user or service account. IDs must be accessible to it.
  const curl = new HttpCurl();
  curl.setVar('access_token', 'BOX_ACCESS_TOKEN');

  const state = new JsonObject();
  const files = new FileAccess();
  const statePath = 'qa_data/box_events_state.json';
  if (files.fileExists(statePath)) {
    success = true;
    try {
      state.loadFile(statePath);
    } catch {
      success = false;
    }
    if (!success) {
      console.log(state.lastErrorText);
      return;
    }

    if (!state.hasMember('position')) {
      console.log('Invalid checkpoint: position missing.');
      return;
    }
  } else {
    // "now" starts a new subscription. It deliberately skips historical events.
    state.updateString('position', 'now');
  }

  curl.setVar('position', state.stringOf('position'));
  const page = new JsonObject();
  const seenPath = new StringBuilder();
  let eventId = '';
  let nextPosition = '';
  let batch = 0;
  let i = 0;
  let count = 0;
  let more = true;
  while ((more) && (batch < 20)) {
    curl.clearTargetOutput('*');
    const authorizedCommand1 = new StringBuilder();
    authorizedCommand1.setString('curl -X GET "https://api.box.com/2.0/events?stream_type=all&stream_position={{position}}&limit=100" -H "Authorization: Bearer {{access_token}}"');
    const headerReplacement1 = authorizedCommand1.replace('{{access_token}}', curl.getVar('access_token'));
    success = true;
    try {
      await curl.doYourThingAsync(authorizedCommand1.getAsString());
    } catch {
      success = false;
    }
    if ((!success) || (curl.statusCode !== 200)) {
      console.log(`Box request failed. HTTP status: ${curl.statusCode}`);
      console.log(`Failure reason: ${curl.failReason}`);
      console.log(curl.responseBodyStr);
      return;
    }

    success = true;
    try {
      curl.getResponseJson(page);
    } catch {
      success = false;
    }
    if (!success) {
      console.log(curl.lastErrorText);
      return;
    }

    count = page.sizeOfArray('entries');
    i = 0;
    while (i < count) {
      page.i = i;
      eventId = page.stringOf('entries[i].event_id');
      if (eventId === '') {
        console.log('Event without an event_id; checkpoint not advanced.');
        return;
      }

      seenPath.clear();
      seenPath.append('seen.');
      seenPath.append(eventId);
      if (!state.hasMember(seenPath.getAsString())) {
        // Replace this logging with your idempotent business operation.
        // Record success only after that operation succeeds.
        console.log(`${eventId} ${page.stringOf('entries[i].event_type')} ${page.stringOf('entries[i].source.id')}`);
        state.updateBool(seenPath.getAsString(), true);
      }

      i++;
    }

    nextPosition = page.stringOf('next_stream_position');
    if (nextPosition === '') {
      console.log('Missing next_stream_position; checkpoint not advanced.');
      return;
    }

    more = (count > 0) && (nextPosition !== curl.getVar('position'));
    state.updateString('position', nextPosition);
    success = true;
    try {
      state.writeFile(statePath);
    } catch {
      success = false;
    }
    if (!success) {
      console.log(state.lastErrorText);
      return;
    }

    curl.setVar('position', nextPosition);
    batch++;
  }

  console.log('Checkpoint saved. Run again later to continue polling.');
}