Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: Improve authentication docs (box/box-codegen#655) #501

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .codegen.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{ "engineHash": "a74691d", "specHash": "1fdcbef", "version": "1.11.0" }
{ "engineHash": "7874ac3", "specHash": "1fdcbef", "version": "1.11.0" }
37 changes: 35 additions & 2 deletions docs/authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
- [Switching between Service Account and User](#switching-between-service-account-and-user)
- [OAuth 2.0 Auth](#oauth-20-auth)
- [Authentication with OAuth2](#authentication-with-oauth2)
- [Injecting existing token into BoxOAuth](#injecting-existing-token-into-boxoauth)
- [Retrieve current access token](#retrieve-current-access-token)
- [Refresh access token](#refresh-access-token)
- [Revoke token](#revoke-token)
Expand Down Expand Up @@ -315,9 +316,27 @@ await oauth.getTokensAuthorizationCodeGrant('code');
const client = new BoxClient({ auth: oauth });
```

### Injecting existing token into BoxOAuth

If you already have an access token and refresh token, you can inject them into the `BoxOAuth` token storage
to avoid repeating the authentication process. This can be useful when you want to reuse the token
between runs of your application.

```js
const accessToken: AccessToken = {
accessToken: '<ACCESS_TOKEN>',
refreshToken: '<REFRESH_TOKEN>',
};
await oauth.tokenStorage.store(accessToken);
const client = new BoxClient({ auth: oauth });
```

Alternatively, you can create a custom implementation of `TokenStorage` interface and pass it to the `BoxOAuth` object.
See the [Custom storage](#custom-storage) section for more information.

# Retrieve current access token

After initializing the authentication object, the SDK will able to retrieve the access token.
After initializing the authentication object, the SDK will be able to retrieve the access token.
To retrieve the current access token you can use the following code:

<!-- sample post_oauth2_token -->
Expand Down Expand Up @@ -403,7 +422,21 @@ const oauth = new BoxOAuth({ config: config });
You can also provide a custom token storage class. All you need to do is create a class that implements `TokenStorage`
interface and pass an instance of your class to the AuthConfig constructor.

```js
```typescript
class MyCustomTokenStorage implements TokenStorage {
async store(token: AccessToken): Promise<undefined> {
// store token in your custom storage
}

async get(): Promise<undefined | AccessToken> {
// retrieve token from your custom storage
}

async clear(): Promise<undefined> {
// clear token from your custom storage
}
}

const config = new OAuthConfig({
clientId: 'OAUTH_CLIENT_ID',
clientSecret: 'OAUTH_CLIENT_SECRET',
Expand Down
110 changes: 102 additions & 8 deletions docs/uploads.md
Original file line number Diff line number Diff line change
@@ -1,17 +1,99 @@
# 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/).

<!-- sample options_files_content -->

```ts
await client.uploads.preflightFileUploadCheck({
name: newFileName,
size: 1024 * 1024,
parent: { id: '0' } satisfies PreflightFileUploadCheckRequestBodyParentField,
} satisfies PreflightFileUploadCheckRequestBody);
```

### 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 -->

Expand All @@ -27,3 +109,15 @@ const files = await client.uploads.uploadFile(body);
const file = files.entries[0];
console.log(`File uploaded with id ${file.id}, name ${file.name}`);
```

### 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.
12 changes: 6 additions & 6 deletions package-lock.json

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

2 changes: 2 additions & 0 deletions src/test/search.generated.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ import { MetadataFilterScopeField } from '../schemas/metadataFilter.generated.js
import { getUuid } from '../internal/utils.js';
import { generateByteStream } from '../internal/utils.js';
import { dateTimeFromString } from '../internal/utils.js';
import { delayInSeconds } from '../internal/utils.js';
import { getDefaultClient } from './commons.generated.js';
import { MetadataFieldFilterDateRange } from '../schemas/metadataFieldFilterDateRange.generated.js';
import { MetadataFieldFilterFloatRange } from '../schemas/metadataFieldFilterFloatRange.generated.js';
Expand Down Expand Up @@ -159,6 +160,7 @@ test('testCreateMetaDataQueryExecuteRead', async function testCreateMetaDataQuer
if (!(metadata.scope == template.scope)) {
throw new Error('Assertion failed');
}
await delayInSeconds(5);
const searchFrom: string = ''.concat(
template.scope!,
'.',
Expand Down
23 changes: 23 additions & 0 deletions src/test/uploads.generated.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ import { serializeFileFull } from '../schemas/fileFull.generated.js';
import { deserializeFileFull } from '../schemas/fileFull.generated.js';
import { serializeUploadFileVersionRequestBodyAttributesField } from '../managers/uploads.generated.js';
import { deserializeUploadFileVersionRequestBodyAttributesField } from '../managers/uploads.generated.js';
import { serializeUploadUrl } from '../schemas/uploadUrl.generated.js';
import { deserializeUploadUrl } from '../schemas/uploadUrl.generated.js';
import { serializePreflightFileUploadCheckRequestBody } from '../managers/uploads.generated.js';
import { deserializePreflightFileUploadCheckRequestBody } from '../managers/uploads.generated.js';
import { serializePreflightFileUploadCheckRequestBodyParentField } from '../managers/uploads.generated.js';
import { deserializePreflightFileUploadCheckRequestBodyParentField } from '../managers/uploads.generated.js';
import { UploadFileOptionalsInput } from '../managers/uploads.generated.js';
import { UploadFileOptionals } from '../managers/uploads.generated.js';
import { ByteStream } from '../internal/utils.js';
Expand All @@ -21,6 +27,9 @@ import { UploadFileVersionRequestBodyAttributesField } from '../managers/uploads
import { CancellationToken } from '../internal/utils.js';
import { UploadFileQueryParams } from '../managers/uploads.generated.js';
import { UploadFileHeaders } from '../managers/uploads.generated.js';
import { UploadUrl } from '../schemas/uploadUrl.generated.js';
import { PreflightFileUploadCheckRequestBody } from '../managers/uploads.generated.js';
import { PreflightFileUploadCheckRequestBodyParentField } from '../managers/uploads.generated.js';
import { getUuid } from '../internal/utils.js';
import { generateByteStream } from '../internal/utils.js';
import { createTokenAndCancelAfter } from '../internal/utils.js';
Expand Down Expand Up @@ -89,4 +98,18 @@ test('testRequestCancellation', async function testRequestCancellation(): Promis
);
}).rejects.toThrow();
});
test('testPreflightCheck', async function testPreflightCheck(): Promise<any> {
const newFileName: string = getUuid();
const preflightCheckResult: UploadUrl =
await client.uploads.preflightFileUploadCheck({
name: newFileName,
size: 1024 * 1024,
parent: {
id: '0',
} satisfies PreflightFileUploadCheckRequestBodyParentField,
} satisfies PreflightFileUploadCheckRequestBody);
if (!!(preflightCheckResult.uploadUrl == '')) {
throw new Error('Assertion failed');
}
});
export {};
Loading