# Azion `Storage` library

import DocButton from '~/components/webkit/DocButton.vue';

The **Object Storage** library provides methods to interact with the **Object Storage** API, allowing you to manage buckets and objects. This client is configurable and supports both debug mode and environment variable-based configuration.

The library also includes a convenient `setupStorage` utility that ensures a bucket exists before performing operations.

<DocButton href="/en/documentation/products/azion-lib/overview/" label="Go to Azion Libraries Overview" kind="secondary" size="medium" />

You can interact with the API using a `client` or calling the methods directly from the library. When making direct calls, you can use the environment variables to configure the `client` without passing the token and debug parameters directly.

This is an example of how a `.env` file with your environment variables may look like:

```sh
AZION_TOKEN=<your-api-token>
AZION_DEBUG=true
```

| Variable | Description |
|----------|-------------|
| `AZION_TOKEN` | Your Azion API token. |
| `AZION_DEBUG` | Enable debug mode (true/false). |

:::tip
Setting `AZION_DEBUG` to `true` enables **Debug mode**. This mode provides detailed logging of the API requests and responses.
:::

If you want to create a specific `client` for interacting with **Storage**, do it by calling the `createClient` method from the library:

```typescript
import { createClient } from 'azion/storage';
import type { AzionStorageClient, AzionStorageResponse, AzionStorage } from 'azion/storage';

const client: AzionStorageClient = createClient({ token: 'your-api-token', options: { debug: true } });

const { data, error } = await client.createBucket('my-new-bucket');
if (data) {
  console.log(`Bucket created with ID: ${data.id}`);
} else {
  console.error('Failed to create bucket', error);
}
```

The `createClient` method has the following **parameters** and **return value**:

**Parameters**:

| Parameter | Type | Description |
|-----------|------|-------------|
| `config` | `Partial<{ token: string; options?: AzionClientOptions }>` | Configuration options for the Storage client. |

**Returns**:

| Return Type | Description |
|-------------|-------------|
| [`AzionStorageClient`](#azionstorageclient) | An object with methods to interact with Storage. |

:::note
In the following examples, the methods are called directly without the creation of a `client`. For more information on how to interact with services and products using a `client`, check the [Azion Lib Client documentation](/en/documentation/products/azion-lib/client/).
:::

---

## Usage

### `setupStorage`

Ensures a bucket exists by first trying to get an existing bucket, and if it doesn't exist, creates it automatically. This is useful for initialization scripts or ensuring your storage is ready to use.

Example:

```typescript
import { setupStorage } from 'azion/storage';
import type { AzionStorageResponse, AzionBucket } from 'azion/storage';

const { data: bucket, error }: AzionStorageResponse<AzionBucket> = await setupStorage({
  name: 'my-app-bucket',
  workloads_access: 'read_write',
});
if (bucket) {
  console.log(`Storage ready: ${bucket.name}`);
  // Now you can safely use the bucket for operations
  await bucket.createObject({
    key: 'config.json',
    content: '{}',
    params: { content_type: 'application/json' },
  });
} else {
  console.error('Failed to setup storage', error);
}
```

**Parameters**:

| Parameter | Type | Description |
|-----------|------|-------------|
| `name` | `string` | The name of the bucket to get or create. |
| `workloads_access` | `string` | The workloads access configuration for the bucket if it needs to be created. Possible values: `'read_only'`, `'read_write'`, `'restricted'`. |
| `options?` | `AzionClientOptions` | Optional parameters for the request. |

**Returns**:

| Return Type | Description |
|-------------|-------------|
| `Promise<AzionStorageResponse<AzionBucket>>` | The existing or newly created bucket object, or error. |

---

### `createBucket`

Creates a new bucket.

Example:

```typescript
import { createBucket } from 'azion/storage';
import type { AzionStorageResponse, AzionBucket } from 'azion/storage';
const { data, error }: AzionStorageResponse<AzionBucket> = await createBucket({
  name: 'my-new-bucket',
  workloads_access: 'read_only',
});
if (data) {
  console.log(`Bucket created with name: ${data.name}`);
} else {
  console.error('Failed to create bucket', error);
}
```

**Parameters**:

| Parameter | Type | Description |
|-----------|------|-------------|
| `name` | `string` | The name of the new bucket. |
| `workloads_access` | `string` | The workloads access configuration for the bucket. Possible values: `'read_only'`, `'read_write'`, `'restricted'`. |
| `options?` | `AzionClientOptions` | Optional parameters for the request. |

**Returns**:

| Return Type | Description |
|-------------|-------------|
| `Promise<AzionStorageResponse<AzionBucket>>` | The created bucket object or error. |

### `deleteBucket`

Deletes a bucket by its name.

Example:

```typescript
import { deleteBucket, AzionDeletedBucket, AzionStorageResponse } from 'azion/storage';

const { data, error }: AzionStorageResponse<AzionDeletedBucket> = await deleteBucket({ name: 'my-bucket' });
if (data) {
  console.log(`Bucket ${data.name} deleted successfully`);
} else {
  console.error('Failed to delete bucket', error);
}
```

**Parameters**:

| Parameter | Type | Description |
|-----------|------|-------------|
| `name` | `string` | The name of the bucket to be deleted. |
| `options?` | [`AzionClientOptions`](#azionclientoptions) | Optional parameters for the request. |

**Returns**:

| Return Type | Description |
|-------------|-------------|
| `Promise<AzionStorageResponse<AzionDeletedBucket>>` | Object confirming deletion or error. |

### `getBuckets`

Retrieves a list of buckets with optional filtering and pagination.

Example:

```typescript
import { getBuckets, AzionStorageResponse, AzionBucketCollection } from 'azion/storage';

const { data: buckets, error }: AzionStorageResponse<AzionBucketCollection> = await getBuckets({
  params: { page: 1, page_size: 10 },
});
if (buckets) {
  console.log(`Retrieved ${buckets.count} buckets`);
} else {
  console.error('Failed to retrieve buckets', error);
}
```

**Parameters**:

| Parameter | Type | Description |
|-----------|------|-------------|
| `params?` | [`AzionBucketCollectionParams`](#azionbucketcollectionparams) | Parameters for filtering and pagination. |
| `options?` | [`AzionClientOptions`](#azionclientoptions) |  Optional parameters for the request. |

**Returns**:

| Return Type | Description |
|-------------|-------------|
| `Promise<AzionStorageResponse<AzionBucketCollection>>` | Array of bucket objects or error. |

### `getBucket`

Retrieves a bucket by its name.

Example:

```typescript
import { getBucket, AzionBucket } from 'azion/storage';

const { data: bucket, error }: AzionStorageResponse<AzionBucket> = await getBucket({ name: 'my-bucket' });
if (bucket) {
  console.log(`Retrieved bucket: ${bucket.name}`);
} else {
  console.error('Bucket not found', error);
}
```

**Parameters**:

| Parameter | Type | Description |
|-----------|------|-------------|
| `name` | `string` | The name of the bucket to be retrieved. |
| `options?` | [`AzionClientOptions`](#azionclientoptions) |  Optional parameters for the request. |

**Returns**:

| Return Type | Description |
|-------------|-------------|
| `Promise<AzionStorageResponse<AzionBucket>>` | The retrieved bucket object or error if not found. |

### `updateBucket`

Updates an existing bucket.

Example:

```typescript
import { updateBucket, AzionBucket, AzionStorageResponse } from 'azion/storage';

const { data: updatedBucket, error }: AzionStorageResponse<AzionBucket> | null = await updateBucket({
  name: 'my-bucket',
  workloads_access: 'read_write',
});
if (updatedBucket) {
  console.log(`Bucket updated: ${updatedBucket.name}`);
} else {
  console.error('Failed to update bucket', error);
}
```

**Parameters**:

| Parameter | Type | Description |
|-----------|------|-------------|
| `name` | `string` | The name of the bucket to be updated. |
| `workloads_access` | `string` | The new workloads access configuration for the bucket. Possible values: `'read_only'`, `'read_write'`, `'restricted'`. |
| `debug?` | `boolean` | Enables debug mode for detailed logging. |

**Returns**:

| Return Type | Description |
|-------------|-------------|
| `Promise<AzionStorageResponse<AzionBucket>>` | The updated bucket object or error if update failed. |

### `createObject`

Creates a new object in a specific bucket.

Example:

```typescript
import { createObject, AzionBucketObject, AzionStorageResponse } from 'azion/storage';

const { data: newObject, error }: AzionStorageResponse<AzionBucketObject> = await createObject({
  bucket: 'my-bucket',
  key: 'new-file.txt',
  content: 'File content',
});
if (newObject) {
  console.log(`Object created with key: ${newObject.key}`);
  console.log(`Object content: ${newObject.content}`);
} else {
  console.error('Failed to create object', error);
}
```

**Parameters**:

| Parameter   | Type     | Description                                   |
|-------------|----------|-----------------------------------------------|
| `bucket` | `string` | The name of the bucket to create the object in.|
| `key` | `string` | Key (name) of the object to be created.|
| `content` | [`ContentObjectStorage`](#contentobjectstorage) | The content of the file to be uploaded. Accepts `string`, `ArrayBuffer`, `ReadableStream`, or `Uint8Array`.|
| `params?` | `{ content_type?: string }` | Optional object parameters, including the content type of the file. |
| `options?` | [`AzionClientOptions`](#azionclientoptions) |  Optional parameters for the request. |

**Returns**:

| Return Type                             | Description                             |
|-----------------------------------------|-----------------------------------------|
| `Promise< AzionBucketObject \| null>`     | The created object or null if creation failed. |

### `getObjectByKey`

Retrieves an object from a specific bucket by its key.

Example:

```typescript
import { getObjectByKey, AzionBucketObject, AzionStorageResponse } from 'azion/storage';

const { data: object, error }: AzionStorageResponse<AzionBucketObject> = await getObjectByKey({
  bucket: 'my-bucket',
  key: 'file.txt',
});
if (object) {
  console.log(`Retrieved object: ${object.key}`);
} else {
  console.error('Object not found', error);
}
```

**Parameters**:

| Parameter | Type | Description |
|-----------|------|-------------|
| `bucket` | `string` | The name of the bucket containing the object. |
| `key` | `string` | The key of the object to be retrieved. |
| `options?` | [`AzionClientOptions`](#azionclientoptions) |  Optional parameters for the request. |

**Returns**:

| Return Type | Description |
|-------------|-------------|
| `Promise< AzionBucketObject | null>` | The retrieved object or null if not found. |

### `getObjects`

Retrieves a list of objects in a specific bucket.

Example:

```typescript
import { getObjects, AzionBucketObject, AzionStorageResponse } from 'azion/storage';

const { data: objectResult, error }: AzionStorageResponse<AzionBucketObjects> = await getObjects({
  bucket: 'my-bucket',
});
if (objectResult) {
  console.log(`Retrieved ${objectResult.count} objects from the bucket`);
} else {
  console.error('Failed to retrieve objects', error);
}
```

**Parameters**:

| Parameter | Type | Description |
|-----------|------|-------------|
| `bucket` | `string` | The name of the bucket to retrieve objects from. |
| `params?` | [`AzionObjectCollectionParams`](#azionobjectcollectionparams) | Parameters for filtering and pagination. |
| `options?` | [`AzionClientOptions`](#azionclientoptions) |  Optional parameters for the request. |

**Returns**:

| Return Type | Description |
|-------------|-------------|
| `Promise<AzionStorageResponse<AzionBucketObjects>>` | Array of bucket objects or error. |

### `updateObject`

Updates an existing object in a specific bucket.

Example:

```typescript
import { updateObject, AzionBucketObject } from 'azion/storage';

const { data: updatedObject, error }: AzionStorageResponse<AzionBucketObject> = await updateObject({
  bucket: 'my-bucket',
  key: 'file.txt',
  content: 'Updated content',
});
if (updatedObject) {
  console.log(`Object updated: ${updatedObject.key}`);
  console.log(`New content: ${updatedObject.content}`);
} else {
  console.error('Failed to update object', error);
}
```

**Parameters**:

| Parameter | Type | Description |
|-----------|------|-------------|
| `bucket` | `string` | The name of the bucket containing the object. |
| `key` | `string` | The key of the object to be updated. |
| `content` | [`ContentObjectStorage`](#contentobjectstorage) | The new content of the file. Accepts `string`, `ArrayBuffer`, `ReadableStream`, or `Uint8Array`. |
| `params?` | `{ content_type?: string }` | Optional object parameters, including the content type of the file. |
| `options?` | [`AzionClientOptions`](#azionclientoptions) |  Optional parameters for the request. |

**Returns**:

| Return Type | Description |
|-------------|-------------|
| `Promise<AzionStorageResponse<AzionBucketObject>>` | The updated object or error if update failed. |

### `deleteObject`

Deletes an object from a specific bucket.

Example:

```typescript
import { deleteObject, AzionDeletedBucketObject, AzionStorageResponse } from 'azion/storage';

const { data: result, error }: AzionStorageResponse<AzionDeletedBucketObject> = await deleteObject({
  bucket: 'my-bucket',
  key: 'file.txt',
});
if (result) {
  console.log(`Object ${result.key} deleted successfully`);
} else {
  console.error('Failed to delete object', error);
}
```

**Parameters**:

| Parameter | Type | Description |
|-----------|------|-------------|
| `bucket` | `string` | The name of the bucket containing the object. |
| `key` | `string` | The key of the object to be deleted. |
| `options?` | [`AzionClientOptions`](#azionclientoptions) |  Optional parameters for the request. |

**Returns**:

| Return Type | Description |
|-------------|-------------|
| `Promise<AzionStorageResponse<AzionDeletedBucketObject>>` | Confirmation of deletion or error if deletion failed. |

---

## Types

These are the types used by the **Storage** library and its methods:

### AzionBucketCollectionParams

Parameters for filtering and pagination when retrieving a collection of buckets.

| Parameter | Type | Description |
|-----------|------|-------------|
| `page?` | `number` | The page number for pagination. |
| `page_size?` | `number` | The number of items per page. |

### `AzionObjectCollectionParams`

| Parameter | Type | Description |
|-----------|------|-------------|
| `max_object_count?` | `number` | The max number of items per request. |

### `EdgeAccessType`

The type of access control for the bucket.

```typescript
'read_only' | 'read_write' | 'restricted'
```

### `AzionClientOptions`

Configuration options for the Storage client.

| Parameter | Type | Description |
|-----------|------|-------------|
| `debug?` | `boolean` | Enables debug mode for detailed logging. |
| `force?` | `boolean` | Force the operation even if it might be destructive. |
| `env?` | [`AzionEnvironment`](#azionenvironment) | Environment to use (dev, stage, prod).  |
| `external?` | `boolean` | Force using external REST API instead of built-in runtime API. |

### AzionEnvironment

The environment in which the client operates.

```typescript
'development' | 'staging' | 'production'
```

### `StorageClient`

An object with methods to interact with Storage.

| Method | Parameters | Return Type |
|--------|------------|--------------|
| `getBuckets` | `options?: BucketCollectionOptions` | `Promise<AzionStorageResponse<AzionBucketCollection>>` |
| `createBucket` | `name: string, edge_access: EdgeAccessType` | `Promise<AzionStorageResponse<AzionBucket>>` |
| `updateBucket` | `name: string, edge_access: EdgeAccessType` | `Promise<AzionStorageResponse<AzionBucket>>` |
| `deleteBucket` | `name: string` | `Promise<AzionStorageResponse<AzionDeletedBucket>>` |
| `getBucket` | `name: string` | `Promise<AzionStorageResponse<AzionBucket>>` |

### `AzionStorageResponse<T>`

The response object from a bucket operation.

| Property | Type | Description |
|----------|------|-------------|
| `data` | `T` (optional) | The data generic object. |
| `error` | `{ message: string; operation: string; }` (optional) | The error details if the operation fails. |

### `AzionBucket`

The bucket object.

| Property | Type | Description |
|----------|------|-------------|
| `name` | `string` | The name of the bucket. |
| `workloads_access` | `string` (optional) | The workloads access configuration of the bucket. |
| `state` | `'executed' \| 'pending'` (optional) | The state of the bucket. |
| `last_editor` | `string` (optional) | The last editor of the bucket. |
| `last_modified` | `string` (optional) | The last modified timestamp. |
| `product_version` | `string` (optional) | The product version. |
| `getObjects` | `() => Promise<AzionStorageResponse<AzionBucketObjects>>` (optional) | A method to get all objects in the bucket. |
| `getObjectByKey` | `(objectKey: string) => Promise<AzionStorageResponse<AzionBucketObject>>` (optional) | A method to get an object by its key. |
| `createObject` | `(objectKey: string, file: string) => Promise<AzionStorageResponse<AzionBucketObject>>` (optional) | A method to create a new object in the bucket. |
| `updateObject` | `(objectKey: string, file: string) => Promise<AzionStorageResponse<AzionBucketObject>>` (optional) | A method to update an existing object in the bucket. |
| `deleteObject` | `(objectKey: string) => Promise<AzionStorageResponse<AzionDeletedBucketObject>>` (optional) | A method to delete an object from the bucket. |

### `AzionBucketObject`

The bucket object.

| Property | Type | Description |
|----------|------|-------------|
| `key` | `string` | The key of the object. |
| `state` | `'executed' \| 'pending'` (optional) | The state of the object. |
| `size` | `number` (optional) | The size of the object. |
| `last_modified` | `string` (optional) | The last modified date of the object. |
| `content_type` | `string` (optional) | The content type of the object. |
| `content` | `string` (optional) | The content of the object. |

### `AzionDeletedBucket`

The response object from a delete bucket request.

| Property | Type | Description |
|----------|------|-------------|
| `name` | `string` | The name of the bucket. |
| `state` | `'executed' | 'pending'` | The state of the bucket. |

### `AzionDeletedBucketObject`

The response object from a delete object request.

| Property | Type | Description |
|----------|------|-------------|
| `key` | `string` | The key of the deleted object. |
| `state` | `'executed' | 'pending'` | The state of the deletion operation. |