Skip to content

Commit

Permalink
chore: update docs (#387)
Browse files Browse the repository at this point in the history
  • Loading branch information
box-sdk-build authored Oct 24, 2024
1 parent 4547148 commit 9262570
Show file tree
Hide file tree
Showing 8 changed files with 323 additions and 47 deletions.
2 changes: 1 addition & 1 deletion .codegen.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{ "engineHash": "c238685", "specHash": "e798cb1", "version": "1.7.0" }
{ "engineHash": "2efc8ab", "specHash": "e798cb1", "version": "1.7.0" }
48 changes: 32 additions & 16 deletions docs/downloads.md
Original file line number Diff line number Diff line change
@@ -1,25 +1,41 @@
# Downloads
# DownloadsManager

Downloads module is used to download files from Box.
- [Download file](#download-file)

<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
## Download file

- [Download a File](#download-a-file)
Returns the contents of a file in binary format.

<!-- END doctoc generated TOC please keep comment here to allow auto update -->
This operation is performed by calling function `downloadFile`.

## Download a File

To get the entire contents of the file as `ArrayBuffer`, call `downloadFile` method.
This method returns a `ArrayBuffer` object which contains the file content.
See the endpoint docs at
[API Reference](https://developer.box.com/reference/get-files-id-content/).

<!-- sample get_files_id_content -->

```js
const fs = require('fs');

const fileContent = await client.downloads.downloadFile('123456789');
const fileWriteStream = fs.createWriteStream('file.pdf');
fileContent.pipe(fileWriteStream);
```ts
await clientWithInterceptor.downloads.downloadFile(uploadedFile.id);
```

### Arguments

- fileId `string`
- The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345"
- optionalsInput `DownloadFileOptionalsInput`
-

### Returns

This function returns a value of type `ByteStream`.

Returns the requested file if the client has the **follow
redirects** setting enabled to automatically
follow HTTP `3xx` responses as redirects. If not, the request
will return `302` instead.
For details, see
the [download file guide](g://downloads/file#download-url).If the file is not ready to be downloaded yet `Retry-After` header will
be returned indicating the time in seconds after which the file will
be available for the client to download.

This response can occur when the file was uploaded immediately before the
download request.
123 changes: 104 additions & 19 deletions docs/uploads.md
Original file line number Diff line number Diff line change
@@ -1,29 +1,114 @@
# Uploads
# UploadsManager

Uploads module is used to upload files to Box. It supports uploading files from a readable stream. For now, it only supports uploading small files without chunked upload.
- [Upload file version](#upload-file-version)
- [Preflight check before upload](#preflight-check-before-upload)
- [Upload file](#upload-file)

<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
## Upload file version

- [Upload a File](#upload-a-file)
Update a file's content. For file sizes over 50MB we recommend
using the Chunk Upload APIs.

<!-- END doctoc generated TOC please keep comment here to allow auto update -->
The `attributes` part of the body must come **before** the
`file` part. Requests that do not follow this format when
uploading the file will receive a HTTP `400` error with a
`metadata_after_file_contents` error code.

## Upload a File
This operation is performed by calling function `uploadFileVersion`.

To upload a small file from a readable stream, call `uploadFile` method. This method returns a `Files` object which contains information about the uploaded files.
See the endpoint docs at
[API Reference](https://developer.box.com/reference/post-files-id-content/).

<!-- sample post_files_id_content -->

```ts
await client.uploads.uploadFileVersion(file.id, {
attributes: {
name: file.name!,
} satisfies UploadFileVersionRequestBodyAttributesField,
file: generateByteStream(20),
} satisfies UploadFileVersionRequestBody);
```

### Arguments

- fileId `string`
- The unique identifier that represents a file. The ID for any file can be determined by visiting a file in the web application and copying the ID from the URL. For example, for the URL `https://*.app.box.com/files/123` the `file_id` is `123`. Example: "12345"
- requestBody `UploadFileVersionRequestBody`
- Request body of uploadFileVersion method
- optionalsInput `UploadFileVersionOptionalsInput`
-

### Returns

This function returns a value of type `Files`.

Returns the new file object in a list.

## Preflight check before upload

Performs a check to verify that a file will be accepted by Box
before you upload the entire file.

This operation is performed by calling function `preflightFileUploadCheck`.

See the endpoint docs at
[API Reference](https://developer.box.com/reference/options-files-content/).

_Currently we don't have an example for calling `preflightFileUploadCheck` in integration tests_

### Arguments

- requestBody `PreflightFileUploadCheckRequestBody`
- Request body of preflightFileUploadCheck method
- headersInput `PreflightFileUploadCheckHeadersInput`
- Headers of preflightFileUploadCheck method
- cancellationToken `undefined | CancellationToken`
- Token used for request cancellation.

### Returns

This function returns a value of type `UploadUrl`.

If the check passed, the response will include a session URL that
can be used to upload the file to.

## Upload file

Uploads a small file to Box. For file sizes over 50MB we recommend
using the Chunk Upload APIs.

The `attributes` part of the body must come **before** the
`file` part. Requests that do not follow this format when
uploading the file will receive a HTTP `400` error with a
`metadata_after_file_contents` error code.

This operation is performed by calling function `uploadFile`.

See the endpoint docs at
[API Reference](https://developer.box.com/reference/post-files-content/).

<!-- sample post_files_content -->

```js
const fs = require('fs');

const attrs = { name: 'filename.txt', parent: { id: '0' } };
const body = {
attributes: attrs,
file: fs.createReadStream('filename.txt'),
};
const files = await client.uploads.uploadFile(body);
const file = files.entries[0];
console.log(`File uploaded with id ${file.id}, name ${file.name}`);
```ts
await parentClient.uploads.uploadFile({
attributes: {
name: getUuid(),
parent: { id: '0' } satisfies UploadFileRequestBodyAttributesParentField,
} satisfies UploadFileRequestBodyAttributesField,
file: generateByteStream(1024 * 1024),
} satisfies UploadFileRequestBody);
```

### Arguments

- requestBody `UploadFileRequestBody`
- Request body of uploadFile method
- optionalsInput `UploadFileOptionalsInput`
-

### Returns

This function returns a value of type `Files`.

Returns the new file object in a list.
58 changes: 47 additions & 11 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

39 changes: 39 additions & 0 deletions src/internal/utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import {
dateFromString,
dateTimeFromString,
dateTimeToString,
dateToString,
generateByteStream,
hexStrToBase64,
readByteStream,
} from './utils';

test('stream', async () => {
const size = 1024 * 1024;
const buffer = await readByteStream(generateByteStream(size));
expect(buffer.length).toBe(size);
});

test('hexStrToBase64', () => {
const hexStr = 'a94a8fe5ccb19ba61c4c0873d391e987982fbbd3';
const base64 = 'qUqP5cyxm6YcTAhz05Hph5gvu9M=';
expect(hexStrToBase64(hexStr)).toBe(base64);
});

describe('date conversions', () => {
test('dateFromString and dateToString', () => {
const dateString = '2024-04-25';
const dateWrapper = dateFromString(dateString);
const result = dateToString(dateWrapper);
expect(result).toBe(dateString);
});
});

describe('datetime conversions', () => {
test('dateTimeFromString and dateTimeToString', () => {
const dateTimeString = '2024-04-25T12:30:00+00:00';
const dateTimeWrapper = dateTimeFromString(dateTimeString);
const result = dateTimeToString(dateTimeWrapper);
expect(result).toBe('2024-04-25T12:30:00+00:00');
});
});
52 changes: 52 additions & 0 deletions src/networking/fetch.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import fetch from 'node-fetch';
import { fetch as builtInFetch, userAgentHeader, xBoxUaHeader } from './fetch';
import { prepareParams, toString } from '../internal/utils';

jest.mock('node-fetch', () =>
jest.fn(async () => ({
text: async () => '',
arrayBuffer: async () => new ArrayBuffer(0),
}))
);

// The fetch method is using NetworkSession, but NetworkSession using BaseUrls
// which is generated during the build process.
// Skip this test for now
test.skip('fetch parses headers correctly and adds analytic headers', async () => {
// The request will fail but we ignore that
// await expect(
// builtInFetch('url', {
// params: prepareParams(
// Object.fromEntries([
// ['key1', toString('value1')],
// ['key2', toString(null)],
// ['key3', toString('value3')],
// ['key4', toString(void 0)],
// ['key5', toString(42)],
// ['key6', toString(true)],
// ])
// ),
// headers: prepareParams(
// Object.fromEntries([
// ['key1', toString('value1')],
// ['key2', toString(null)],
// ['key3', toString('value3')],
// ['key4', toString(void 0)],
// ])
// ),
// })
// ).rejects.toThrow();
// expect(fetch as jest.Mock).toBeCalledWith(
// 'url?key1=value1&key3=value3&key5=42&key6=true',
// {
// method: 'GET',
// headers: {
// 'Content-Type': 'application/json',
// key1: 'value1',
// key3: 'value3',
// 'User-Agent': userAgentHeader,
// 'X-Box-UA': xBoxUaHeader,
// },
// }
// );
});
Loading

0 comments on commit 9262570

Please sign in to comment.