Box Node SDK

repository·main·Indexed 41 days ago

https://github.com/box/box-node-sdk

Official SDK for Box Platform APIs, providing a programmatic interface to the Box Content Cloud for Node.js and browser environments. Supports multiple authentication methods including OAuth 2.0, JWT, and Client Credentials Grant. Version 10.15.0 features full API coverage via sdk-gen, while version 4 provides legacy and combined support.

Tokens
92.8K
Snippets
418
Records
509
Agent score
52%

What's inside Box Node SDK

  1. Manage AI agents with AiStudioManager

    main

    The AiStudioManager provides methods to manage AI agents within Box AI Studio. You can list, create, update, retrieve, and delete agents using the client.aiStudio property.

    Key capabilities for agents include ask, text_gen, and extract. When creating an agent, at least one of these capabilities must be provided.

    const aiStudio = client.aiStudio;
    // Use aiStudio methods like getAiAgents(), createAiAgent(), etc.
  2. Manage Shield Lists with ShieldListsManager

    main
    The ShieldListsManager provides methods to manage Box Shield lists within an enterprise. You can retrieve all lists, create new ones, fetch a specific list by its ID, update existing lists, or delete them. Most operations use the V2025R0 versioned methods.
  3. How event deduplication works in the Event Stream

    main
    The EventStream class automatically handles deduplication. It uses the event_id of incoming events to ensure that if the same event is received multiple times via long-polling, it is only emitted once to your listeners.
  4. Manage metadata taxonomy levels

    main

    Metadata taxonomies can have multiple levels. You can manage these levels using the following methods:

    • Create multiple levels: createMetadataTaxonomyLevel allows you to define an array of MetadataTaxonomyLevel objects at once.
    • Update a specific level: updateMetadataTaxonomyLevelById updates a level at a specific levelIndex.
    • Append a level: addMetadataTaxonomyLevel creates a new level and appends it to the existing hierarchy. If no levels exist, it creates the first one.
    • Delete the last level: deleteMetadataTaxonomyLevel removes the most recent level (trimming the hierarchy).
    // Create multiple levels
    await client.metadataTaxonomies.createMetadataTaxonomyLevel(
      namespace,
      taxonomyKey,
      [
        { displayName: 'Continent', description: 'Continent Level' } satisfies MetadataTaxonomyLevel,
        { displayName: 'Country', description: 'Country Level' } satisfies MetadataTaxonomyLevel,
      ],
    );
    
    // Update a level by index
    await client.metadataTaxonomies.updateMetadataTaxonomyLevelById(
      namespace,
      taxonomyKey,
      1,
      { displayName: 'Continent UPDATED', description: 'Continent Level UPDATED' } satisfies UpdateMetadataTaxonomyLevelByIdRequestBody,
    );
    
    // Append a new level
    await client.metadataTaxonomies.addMetadataTaxonomyLevel(
      namespace,
      taxonomyKey,
      { displayName: 'Region', description: 'Region Description' } satisfies AddMetadataTaxonomyLevelRequestBody,
    );
    
    // Delete the last level
    await client.metadataTaxonomies.deleteMetadataTaxonomyLevel(namespace, taxonomyKey);
  5. Key differences: Async/Await and Promises in sdk-gen

    main

    The sdk-gen module enforces consistent use of Promises across the entire SDK, moving away from the optional callback pattern used in the manual box-node-sdk.

    Manual (box-node-sdk) pattern: Allowed passing a callback as the last argument.

    Generated (sdk-gen) pattern: Always returns a Promise, making async/await the standard interaction method.

    // Manual (box-node-sdk)
    function callback(user) {
      console.log('hello', user);
    }
    client.users.get('123456', {} /* options */, callback);
    
    // Generated (sdk-gen)
    const user = await client.users.getUserById('123456');
  6. Use ChunkedUploadsManager for large file uploads

    main

    The ChunkedUploadsManager is used to manage chunked uploads, which are required for files that are at least 20MB in size. It provides methods to create upload sessions (for both new and existing files), upload individual file parts, list uploaded parts, plan uploads to optimize by skipping existing parts, and commit or abort sessions. Many operations can be performed using either a specific uploadSessionId or a direct url provided by the Box API during session creation.

    // The manager is accessed via client.chunkedUploads
    const manager = client.chunkedUploads;
  7. Key differences: Immutable design in sdk-gen

    main

    The sdk-gen module follows an immutable design pattern. Instead of methods modifying the state of an existing client instance, they return a new instance of the class with the modified state. This prevents side effects and makes code more predictable.

    Methods that return a new modified instance are prefixed with with.

    // In sdk-gen, methods return a new instance
    asUserClient: BoxClient = client.withAsUserHeader('USER_ID');
  8. Understand the v10 SDK architecture and namespaces

    main

    The v10 release introduces an auto-generated module called sdk-gen. To maintain backward compatibility, the sdk-gen module is located under the box-node-sdk namespace. You can access it using the box-node-sdk/sdk-gen alias namespace.

    If you are migrating from v3, you can use the v4 version of the SDK to consolidate both the manually maintained box-node-sdk (v3 style) and the new sdk-gen (v10 style) modules. This allows you to adopt new features from sdk-gen incrementally without a full immediate migration.

  9. Switch from Service Account to User authentication in JWT

    main

    In sdk-gen, you can switch the authenticated subject (e.g., from a Service Account to a specific User) by calling .withUserSubject(userId) on an existing BoxJwtAuth instance. This returns a new BoxJwtAuth instance which can be used to create a new BoxClient.

    const userAuth = jwtAuth.withUserSubject('USER_ID');
    const userClient = new BoxClient({ auth: userAuth });
  10. Understand the Box SDK retry strategy

    main

    The SDK uses a built-in BoxRetryStrategy via the BoxNetworkClient to automatically retry failed API requests using exponential backoff.

    The strategy manages two main concerns:

    1. shouldRetry: Decides if a request should be retried based on HTTP status codes (e.g., 429, 5xx, 202 with Retry-After), authentication state (401), or network exceptions (status 0).
    2. retryAfter: Calculates the delay before the next attempt, prioritizing the server's Retry-After header if present, otherwise using an exponential backoff formula with jitter.

    Key behaviors:

    • Network Exceptions: Failures like DNS or connection errors are treated as status 0. These are tracked by a separate counter (maxRetriesOnException) but still count towards the total maxAttempts limit.
    • Exponential Backoff: If no Retry-After header is provided, the delay is calculated as: delay = 2^attemptNumber * retryBaseInterval * random(1 - factor, 1 + factor).
    • Authentication: If a 401 error occurs and a refresh token is available, the SDK will attempt to refresh the token and then retry the request.
  11. Understand the architectural change from v4 to v10

    main

    The Box Node SDK underwent a major architectural shift between version 4 and version 10:

    • In v4: The SDK provided two modules side-by-side: a manually maintained box-node-sdk and an auto-generated sdk-gen module.
    • In v10: The manually maintained box-node-sdk module has been removed. The SDK now consists entirely of the auto-generated sdk-gen module.

    Backward Compatibility: To assist with migration, the sdk-gen module is moved to the box-node-sdk namespace using the box-node-sdk/sdk-gen alias namespace.

  12. Understand null behavior in update operations

    main

    When performing update operations (e.g., modifying users, files, folders, or metadata) using the Box Node SDK, the SDK follows a specific pattern based on how you provide fields in the requestBody:

    • Omitting a field: The field is not included in the HTTP request, and the existing value on the Box resource remains unchanged.
    • Setting a field to null: The field is sent with a null value in the HTTP request, which removes or disassociates the current value from the resource.
    • Providing a value: A non-null value assigns or updates the field to the new value provided.