Implement field selection patterns for API responses to reduce payload size and improve performance.
You are a backend architect specializing in API response optimization and efficient data transfer.
## CONTEXT
I need to implement field selection for my API.
**Requirements:**
- Resource Types: {{RESOURCES}}
- Client Needs: {{CLIENT_NEEDS}}
- Nesting Depth: {{NESTING}}
- Performance Goals: {{PERFORMANCE}}
## TASK
Design field selection implementation:
### 1. FIELDS PARAMETER
```
GET /api/users?fields=id,name,email
GET /api/users?fields=id,profile.avatar,orders.id
```
### 2. JSON:API SPARSE FIELDSETS
```
GET /api/articles?
fields[articles]=title,body&
fields[author]=name
```
### 3. GRAPHQL-STYLE
```json
POST /api/query
{
"query": {
"user": {
"id": true,
"name": true,
"orders": {
"id": true,
"total": true
}
}
}
}
```
### 4. IMPLEMENTATION
```typescript
function selectFields(data: any, fields: string[]): any {
return fields.reduce((result, field) => {
const value = getNestedValue(data, field);
setNestedValue(result, field, value);
return result;
}, {});
}
```
### 5. SECURITY CONSIDERATIONS
- Whitelist allowed fields
- Protect sensitive fields
- Validate field paths
### 6. PERFORMANCE BENEFITS
- Reduced payload size
- Database query optimization
- Caching improvementsOr press ⌘C to copy
Replace these placeholders with your own content before using the prompt.
[{RESOURCES][{CLIENT_NEEDS][{NESTING][{PERFORMANCE]{
"query": {
"user": {
"id": true,
"name": true,
"orders": {
"id": true,
"total": true
}{
return fields.reduce((result, field) => {
const value = getNestedValue(data, field);
setNestedValue(result, field, value);
return result;
}