Design resource expansion patterns for loading related resources in single API calls.
You are an API optimization specialist reducing N+1 query problems and network round trips.
## CONTEXT
I need to implement resource expansion for related data.
**Requirements:**
- Primary Resources: {{RESOURCES}}
- Relationships: {{RELATIONSHIPS}}
- Depth Limits: {{DEPTH}}
- Performance: {{PERFORMANCE}}
## TASK
Design resource expansion:
### 1. EXPAND PARAMETER
```
GET /api/orders/123?expand=customer,items
GET /api/orders/123?expand=customer.address,items.product
```
### 2. RESPONSE FORMAT
```json
{
"id": "order_123",
"status": "shipped",
"customer": {
"id": "cust_456",
"name": "John Doe",
"email": "john@example.com"
},
"items": [
{
"id": "item_1",
"quantity": 2,
"product": {
"id": "prod_789",
"name": "Widget",
"price": 29.99
}
}
]
}
```
### 3. IMPLEMENTATION
```typescript
async function expandResources(data, expansions) {
for (const expansion of expansions) {
const [relation, nested] = expansion.split('.');
const relatedData = await loadRelation(data, relation);
data[relation] = nested
? await expandResources(relatedData, [nested])
: relatedData;
}
return data;
}
```
### 4. DEPTH LIMITING
```typescript
const MAX_EXPANSION_DEPTH = 3;
// Reject: ?expand=a.b.c.d.e
```
### 5. PERFORMANCE OPTIMIZATION
- Batch loading
- Dataloader pattern
- Caching expanded resources
### 6. SECURITY
- Whitelist expandable relations
- Permission checks on relationsOr press ⌘C to copy
Replace these placeholders with your own content before using the prompt.
[{RESOURCES][{RELATIONSHIPS][{DEPTH][{PERFORMANCE]{
"id": "order_123",
"status": "shipped",
"customer": {
"id": "cust_456",
"name": "John Doe",
"email": "john@example.com"
}{
"id": "item_1",
"quantity": 2,
"product": {
"id": "prod_789",
"name": "Widget",
"price": 29.99
}{
for (const expansion of expansions) {
const [relation, nested] = expansion.split('.');
const relatedData = await loadRelation(data, relation);
data[relation] = nested
? await expandResources(relatedData, [nested])
: relatedData;
}