# CosmosDB Client

Interact with Azure CosmosDB with full type safety and runtime validation.

## Methods

| Method                                   | Description                                          |
| ---------------------------------------- | ---------------------------------------------------- |
| `apiRequest(options, schema, metadata?)` | Make any CosmosDB API request with schema validation |

## Usage

### Query Documents

```typescript
import { api, z, cosmosdb } from "@superblocksteam/sdk-api";

// Integration ID from the integrations panel
const PROD_COSMOSDB = "a1b2c3d4-5678-90ab-cdef-cosmosdb0001";

const QueryResponseSchema = z.object({
  Documents: z.array(
    z.object({
      id: z.string(),
      name: z.string(),
      email: z.string(),
    }),
  ),
  _count: z.number(),
});

export default api({
  name: "CosmosDBExample",
  integrations: {
    cosmosdb: cosmosdb(PROD_COSMOSDB),
  },
  input: z.object({
    status: z.string(),
  }),
  output: z.object({
    users: z.array(
      z.object({
        id: z.string(),
        name: z.string(),
        email: z.string(),
      }),
    ),
  }),
  async run(ctx, { status }) {
    const result = await ctx.integrations.cosmosdb.apiRequest(
      {
        method: "POST",
        path: "/dbs/mydb/colls/users/docs",
        headers: {
          "Content-Type": "application/query+json",
        },
        body: {
          query: "SELECT * FROM c WHERE c.status = @status",
          parameters: [{ name: "@status", value: status }],
        },
      },
      { response: QueryResponseSchema },
    );

    return { users: result.Documents };
  },
});
```

### Get Document

```typescript
const GetDocumentResponseSchema = z.object({
  id: z.string(),
  name: z.string(),
  email: z.string(),
});

const result = await ctx.integrations.cosmosdb.apiRequest(
  {
    method: "GET",
    path: `/dbs/mydb/colls/users/docs/${documentId}`,
    headers: {
      "x-ms-documentdb-partitionkey": `["${partitionKey}"]`,
    },
  },
  { response: GetDocumentResponseSchema },
);
```

### Create Document

```typescript
const CreateResponseSchema = z.object({
  id: z.string(),
  _rid: z.string(),
  _etag: z.string(),
});

const result = await ctx.integrations.cosmosdb.apiRequest(
  {
    method: "POST",
    path: "/dbs/mydb/colls/users/docs",
    headers: {
      "x-ms-documentdb-partitionkey": `["${partitionKey}"]`,
    },
    body: {
      id: "user-123",
      name: "John Doe",
      email: "john@example.com",
      partitionKey: partitionKey,
    },
  },
  { response: CreateResponseSchema },
);
```

### Replace Document

```typescript
const ReplaceResponseSchema = z.object({
  id: z.string(),
  _etag: z.string(),
});

const result = await ctx.integrations.cosmosdb.apiRequest(
  {
    method: "PUT",
    path: `/dbs/mydb/colls/users/docs/${documentId}`,
    headers: {
      "x-ms-documentdb-partitionkey": `["${partitionKey}"]`,
    },
    body: {
      id: documentId,
      name: "Jane Doe",
      email: "jane@example.com",
      partitionKey: partitionKey,
    },
  },
  { response: ReplaceResponseSchema },
);
```

### Delete Document

```typescript
const DeleteResponseSchema = z.object({}).passthrough();

await ctx.integrations.cosmosdb.apiRequest(
  {
    method: "DELETE",
    path: `/dbs/mydb/colls/users/docs/${documentId}`,
    headers: {
      "x-ms-documentdb-partitionkey": `["${partitionKey}"]`,
    },
  },
  { response: DeleteResponseSchema },
);
```

## Trace Metadata

All methods accept an optional `metadata` parameter as the last argument for diagnostics labeling. See the [root SDK README](../../../README.md#trace-metadata) for details.

## Common Pitfalls

### Partition Key Header

Always include the partition key header:

```typescript
headers: {
  "x-ms-documentdb-partitionkey": `["${partitionKey}"]`,
}
```

### Query Content-Type

For queries, use the special content type:

```typescript
headers: {
  "Content-Type": "application/query+json",
}
```

### Response Schema is Required

```typescript
// CORRECT - Response schema is required
await ctx.integrations.cosmosdb.apiRequest(
  { method: "POST", path: "/...", body: { ... } },
  { response: ResponseSchema }
);
```

## Error Handling

```typescript
import { RestApiValidationError } from "@superblocksteam/sdk-api";

try {
  const result = await ctx.integrations.cosmosdb.apiRequest(
    { method: "POST", path: "/...", body: { ... } },
    { response: ResponseSchema }
  );
} catch (error) {
  if (error instanceof RestApiValidationError) {
    console.error("Validation failed:", error.details.zodError);
  }
}
```

## API Reference

- [CosmosDB REST API](https://docs.microsoft.com/en-us/rest/api/cosmos-db/)
- [CosmosDB SQL Query](https://docs.microsoft.com/en-us/azure/cosmos-db/sql-query-getting-started)
