-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontentstack-cli.mdc
More file actions
165 lines (140 loc) · 4.4 KB
/
contentstack-cli.mdc
File metadata and controls
165 lines (140 loc) · 4.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
---
description: 'Contentstack CLI specific patterns and API integration'
globs: ['**/import/**/*.ts', '**/export/**/*.ts', '**/modules/**/*.ts', '**/services/**/*.ts', '**/utils/**/*.ts']
alwaysApply: false
---
# Contentstack CLI Standards
## API Integration
- Use `@contentstack/cli-utilities` for SDK factory: `managementSDKClient(config)`
- Stack-scoped API access: `stackAPIClient.asset()`, `stackAPIClient.extension()`
- Fluent SDK chaining: `stack.contentType().entry().query().find()`
- Custom HTTP for variants: `apiClient.put/get` with path strings
## Authentication
- Use `@contentstack/cli-utilities` for token management
- Management token alias: `configHandler.get('tokens.<alias>')`
- OAuth context: `configHandler.get('userUid'|'email'|'oauthOrgUid')`
- Authentication check: `isAuthenticated()` before operations
- Never log API keys or tokens in console or files
## Rate Limiting - Multiple Mechanisms
### Batch Spacing (Import/Export)
```typescript
// ✅ GOOD - Ensure minimum 1 second between batches
async logMsgAndWaitIfRequired(processName: string, start: number): Promise<void> {
const end = Date.now();
const exeTime = end - start;
if (exeTime < 1000) await this.delay(1000 - exeTime);
}
```
### 429 Retry (Branches)
```typescript
// ✅ GOOD - Handle 429 with retry
export async function handleErrorMsg(err, retryCallback?: () => Promise<any>) {
if (err?.status === 429 || err?.response?.status === 429) {
await new Promise((resolve) => setTimeout(resolve, 1000)); // 1 sec delay
if (retryCallback) {
return retryCallback(); // Retry the request
}
}
}
```
### Variant Pagination Throttle
```typescript
// ✅ GOOD - Throttle variant API requests
if (requestTime < 1000) {
await delay(1000 - requestTime);
}
```
## Error Handling
### Standard Pattern
```typescript
// ✅ GOOD - Use handleAndLogError from utilities
try {
const result = await this.stack.contentType().entry().fetch();
} catch (error) {
handleAndLogError(error);
this.logAndPrintErrorDetails(error, config);
}
```
### User-Friendly Errors
```typescript
// ✅ GOOD - User-facing error display
cliux.print(errorMessage, { color: 'red' });
// For critical failures
process.exit(1);
```
## Module Architecture (Import/Export)
### BaseClass Pattern
```typescript
// ✅ GOOD - Extend BaseClass for entity modules
export class ContentTypes extends BaseClass {
constructor(params: ModuleClassParams) {
super(params);
// Entity-specific initialization
}
async import(): Promise<void> {
// Use this.makeConcurrentCall for batching
// Use this.logMsgAndWaitIfRequired for rate limiting
}
}
```
### Batch Processing
```typescript
// ✅ GOOD - Concurrent batch processing
const batches = chunk(apiContent, batchSize);
for (const batch of batches) {
const start = Date.now();
await this.makeConcurrentCall(batch, this.processItem.bind(this));
await this.logMsgAndWaitIfRequired('Processing', start, batches.length, batchIndex);
}
```
## Configuration Patterns
### Import/Export Config
```typescript
// ✅ GOOD - Use configHandler for management tokens
const config = {
host: configHandler.get('region.cma'),
managementTokenAlias: flags.alias,
stackApiKey: flags['stack-api-key'],
rateLimit: 5, // Default rate limit
};
```
### Regional Configuration
```typescript
// ✅ GOOD - Handle regional endpoints
const defaultConfig = {
host: 'https://api.contentstack.io',
cdn: 'https://cdn.contentstack.io',
// Regional developer hub URLs
};
```
## Testing Patterns
### SDK Mocking
```typescript
// ✅ GOOD - Mock stack client methods
const mockStackClient = {
fetch: sinon.stub().resolves({ name: 'Test Stack', uid: 'stack-uid' }),
locale: sinon.stub().returns({
query: sinon.stub().returns({
find: sinon.stub().resolves({ items: [], count: 0 }),
}),
}),
};
```
### Error Simulation
```typescript
// ✅ GOOD - Test error handling
it('should handle 429 rate limit', async () => {
const error = { status: 429 };
mockClient.fetch.rejects(error);
// Test retry logic
});
```
## Package-Specific Patterns
### Plugin vs Library
- **Plugin packages**: Have `oclif.commands` in package.json
- **Library packages** (e.g., variants): No OCLIF commands, consumed by other packages
### Monorepo Structure
- Commands: `packages/*/src/commands/cm/**/*.ts`
- Modules: `packages/*/src/{import,export,modules}/**/*.ts`
- Utilities: `packages/*/src/utils/**/*.ts`
- Built artifacts: `packages/*/lib/**` (not source)