# Cache settings

Estas funções do `azion/applications` criam, listam, leem, atualizam e excluem os cache settings de uma application. A application precisa ter uma origem antes: em uma application sem nenhuma, a API recusa o cache setting com `HTTP error! Status: 400 - BAD REQUEST`.

---

## createCacheSetting

Cria um cache setting em uma application. A application precisa ter uma origem antes. Em uma application sem nenhuma, a API recusa o cache setting, e a função retorna `error` com a mensagem `HTTP error! Status: 400 - BAD REQUEST`.

```typescript
function createCacheSetting(params: {
  applicationId: number;
  data: ApiBaseCacheSettingPayload;
  options?: AzionClientOptions;
}): Promise<AzionApplicationResponse<AzionCacheSetting>>;
```

| Parâmetro       | Tipo                                                                                                                 | Obrigatório | Descrição                                                |
| --------------- | -------------------------------------------------------------------------------------------------------------------- | ----------- | -------------------------------------------------------- |
| `applicationId` | `number`                                                                                                             | Sim         | O ID da application.                                     |
| `data`          | [`ApiBaseCacheSettingPayload`](/pt-br/documentacao/devtools/azion-lib/application/types/#apibasecachesettingpayload) | Sim         | As configurações do cache setting. `name` é obrigatório. |
| `options`       | [`AzionClientOptions`](/pt-br/documentacao/devtools/azion-lib/application/types/#azionclientoptions)                 | Não         | Opções de requisição.                                    |

`browser_cache_settings` recebe `honor`, `override` ou `ignore`, e `cdn_cache_settings` recebe `honor` ou `override`. Com `override`, o exemplo também define o campo de TTL máximo correspondente, `browser_cache_settings_maximum_ttl` ou `cdn_cache_settings_maximum_ttl`.

Retorna `data` como o [AzionCacheSetting](/pt-br/documentacao/devtools/azion-lib/application/types/#azioncachesetting) criado, com o `id` dele.

Este exemplo é em JavaScript, porque o TypeScript rejeita valores de string para `browser_cache_settings` e `cdn_cache_settings`, cujos tipos são enums que o módulo não exporta:

```javascript
import { createCacheSetting } from 'azion/applications';

const applicationId = 1234567890; // Replace with the actual application ID

// Create a new cache setting
const cacheSettingData = {
  name: 'my-cache-setting',
  browser_cache_settings: 'override',
  browser_cache_settings_maximum_ttl: 3600,
  cdn_cache_settings: 'override',
  cdn_cache_settings_maximum_ttl: 7200,
};

const { data: newCacheSetting, error } = await createCacheSetting({ applicationId, data: cacheSettingData });

if (error) {
  console.error('Error creating cache setting:', error);
} else {
  console.log('Cache setting created successfully:', newCacheSetting.id, newCacheSetting.name, newCacheSetting.cdn_cache_settings_maximum_ttl);
}
```

Saída:

```text
Cache setting created successfully: 234567 my-cache-setting 7200
```

---

## getCacheSettings

Lista os cache settings de uma application, uma página por vez.

```typescript
function getCacheSettings(params: {
  applicationId: number;
  params?: ApiListCacheSettingsParams;
  options?: AzionClientOptions;
}): Promise<AzionApplicationCollectionResponse<AzionCacheSetting>>;
```

| Parâmetro       | Tipo                                                                                                          | Obrigatório | Descrição                                                                                                                              |
| --------------- | ------------------------------------------------------------------------------------------------------------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `applicationId` | `number`                                                                                                      | Sim         | O ID da application.                                                                                                                   |
| `params`        | [`ApiListCacheSettingsParams`](/pt-br/documentacao/devtools/azion-lib/application/types/#parametros-de-lista) | Não         | Paginação: `page` e `page_size`. Deixe de fora `sort` e `order`: a API recusa os valores que o tipo declara para eles com um erro 400. |
| `options`       | [`AzionClientOptions`](/pt-br/documentacao/devtools/azion-lib/application/types/#azionclientoptions)          | Não         | Opções de requisição.                                                                                                                  |

Retorna um [AzionApplicationCollectionResponse](/pt-br/documentacao/devtools/azion-lib/application/types/#azionapplicationcollectionresponse) cujo `data.results` contém objetos [AzionCacheSetting](/pt-br/documentacao/devtools/azion-lib/application/types/#azioncachesetting).

```typescript
import { getCacheSettings } from 'azion/applications';

const applicationId = 1234567890; // Replace with the actual application ID

const { data: cacheSettings, error } = await getCacheSettings({
  applicationId,
  params: { page: 1, page_size: 20 },
});

if (error) {
  console.error('Error listing cache settings:', error);
} else {
  console.log(`Found ${cacheSettings?.count} cache settings:`, cacheSettings?.results.map((c) => `${c.id} ${c.name}`));
}
```

Saída:

```text
Found 1 cache settings: [ '234568 my-other-cache-setting' ]
```

---

## getCacheSetting

Retorna um cache setting de uma application pelo ID dele.

```typescript
function getCacheSetting(params: {
  applicationId: number;
  cacheSettingId: number;
  options?: AzionClientOptions;
}): Promise<AzionApplicationResponse<AzionCacheSetting>>;
```

| Parâmetro        | Tipo                                                                                                 | Obrigatório | Descrição              |
| ---------------- | ---------------------------------------------------------------------------------------------------- | ----------- | ---------------------- |
| `applicationId`  | `number`                                                                                             | Sim         | O ID da application.   |
| `cacheSettingId` | `number`                                                                                             | Sim         | O ID do cache setting. |
| `options`        | [`AzionClientOptions`](/pt-br/documentacao/devtools/azion-lib/application/types/#azionclientoptions) | Não         | Opções de requisição.  |

Retorna `data` como um [AzionCacheSetting](/pt-br/documentacao/devtools/azion-lib/application/types/#azioncachesetting).

```typescript
import { getCacheSetting } from 'azion/applications';

const applicationId = 1234567890; // Replace with the actual application ID
const cacheSettingId = 234567; // Replace with the actual cache setting ID

const { data: cacheSetting, error } = await getCacheSetting({ applicationId, cacheSettingId });

if (error) {
  console.error('Error retrieving cache setting:', error);
} else {
  console.log('Cache setting details:', cacheSetting?.id, cacheSetting?.name, cacheSetting?.browser_cache_settings, cacheSetting?.cdn_cache_settings);
}
```

Saída:

```text
Cache setting details: 234567 my-cache-setting override override
```

---

## updateCacheSetting

Envia em uma requisição `PATCH` os campos do cache setting que você passa.

```typescript
function updateCacheSetting(params: {
  applicationId: number;
  cacheSettingId: number;
  data: ApiUpdateCacheSettingPayload;
  options?: AzionClientOptions;
}): Promise<AzionApplicationResponse<AzionCacheSetting>>;
```

| Parâmetro        | Tipo                                                                                                                   | Obrigatório | Descrição                                 |
| ---------------- | ---------------------------------------------------------------------------------------------------------------------- | ----------- | ----------------------------------------- |
| `applicationId`  | `number`                                                                                                               | Sim         | O ID da application.                      |
| `cacheSettingId` | `number`                                                                                                               | Sim         | O ID do cache setting a atualizar.        |
| `data`           | [`ApiUpdateCacheSettingPayload`](/pt-br/documentacao/devtools/azion-lib/application/types/#apibasecachesettingpayload) | Sim         | Os campos a mudar. Todo campo é opcional. |
| `options`        | [`AzionClientOptions`](/pt-br/documentacao/devtools/azion-lib/application/types/#azionclientoptions)                   | Não         | Opções de requisição.                     |

Retorna `data` como o [AzionCacheSetting](/pt-br/documentacao/devtools/azion-lib/application/types/#azioncachesetting) atualizado. Um payload sem campos de enum, como `name` e um TTL, passa na verificação de tipos do TypeScript.

```typescript
import { updateCacheSetting } from 'azion/applications';

const applicationId = 1234567890; // Replace with the actual application ID
const cacheSettingId = 234567; // Replace with the actual cache setting ID

const { data: updatedCacheSetting, error } = await updateCacheSetting({
  applicationId,
  cacheSettingId,
  data: { name: 'my-cache-setting-updated', cdn_cache_settings_maximum_ttl: 3600 },
});

if (error) {
  console.error('Error updating cache setting:', error);
} else {
  console.log('Cache setting updated:', updatedCacheSetting?.name, updatedCacheSetting?.cdn_cache_settings_maximum_ttl);
}
```

Saída:

```text
Cache setting updated: my-cache-setting-updated 3600
```

---

## deleteCacheSetting

Exclui um cache setting de uma application pelo ID dele.

```typescript
function deleteCacheSetting(params: {
  applicationId: number;
  cacheSettingId: number;
  options?: AzionClientOptions;
}): Promise<AzionApplicationResponse<void>>;
```

| Parâmetro        | Tipo                                                                                                 | Obrigatório | Descrição                        |
| ---------------- | ---------------------------------------------------------------------------------------------------- | ----------- | -------------------------------- |
| `applicationId`  | `number`                                                                                             | Sim         | O ID da application.             |
| `cacheSettingId` | `number`                                                                                             | Sim         | O ID do cache setting a excluir. |
| `options`        | [`AzionClientOptions`](/pt-br/documentacao/devtools/azion-lib/application/types/#azionclientoptions) | Não         | Opções de requisição.            |

Uma exclusão bem-sucedida retorna `error` com a mensagem `Expected JSON response, but got: `, por isso o exemplo lê o cache setting de volta com [getCacheSetting](#getcachesetting). Um erro `404` confirma a exclusão.

```typescript
import { deleteCacheSetting, getCacheSetting } from 'azion/applications';

const applicationId = 1234567890; // Replace with the actual application ID
const cacheSettingId = 234567; // Replace with the actual cache setting ID

const { error: deleteError } = await deleteCacheSetting({ applicationId, cacheSettingId });

// On success (HTTP 204) the envelope still carries an error, so confirm by reading it back
const { error } = await getCacheSetting({ applicationId, cacheSettingId });
if (error) {
  console.log(`Cache setting ${cacheSettingId} deleted (read back: ${error.message})`);
} else {
  console.error('Error deleting cache setting:', deleteError);
}
```

Saída:

```text
Cache setting 234567 deleted (read back: HTTP error! Status: 404 - NOT FOUND)
```

---

## Recursos relacionados

- [Azion Lib](/pt-br/documentacao/devtools/azion-lib.md): Os módulos da Azion Lib e o pacote npm em que cada um é distribuído.
- [Applications](/pt-br/documentacao/devtools/azion-lib/application.md): A autenticação do módulo, o envelope de resposta dele e os erros que as funções reportam.
- [Tipos de application](/pt-br/documentacao/devtools/azion-lib/application/types.md): Os tipos de payload e de resposta que estas funções recebem e retornam.
- [Cache settings](/pt-br/documentacao/plataforma/applications/cache/cache-settings.md): O cache setting que uma application aplica, com os TTLs e a chave de cache dele.
