Repository navigation
Expand file tree
/
Copy pathapi-client-patterns.mdc
More file actions
367 lines (314 loc) · 9.39 KB
/
Copy pathapi-client-patterns.mdc
File metadata and controls
367 lines (314 loc) · 9.39 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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
---
description:
globs: **/*.api-client.ts
alwaysApply: false
---
# API Client Patterns
Guidelines for creating and maintaining API clients that communicate with backend services in the T6C project.
## Client Organization Principles
### One Client Per API Service
- **ALWAYS** create a dedicated client package for each API service
- Client naming convention: `{service-name}-api-client` (e.g., `blog-api-client`, `user-api-client`)
- Service class naming: `{ServiceName}Service` (e.g., `BlogPostService`, `UserService`)
```typescript
// ✅ CORRECT - Dedicated client for blog API
export class BlogPostService extends E.Service<BlogPostService>()(
'@web/BlogPostService',
{
dependencies: [FetchHttpClient.layer],
effect: E.gen(function* () {
const client = yield* createHttpClient({
url: envVars.BLOG_SERVICE_URL,
apiKey: envVars.BLOG_SERVICE_API_KEY,
})
return {
// ... methods
}
}),
},
) {}
```
## Import Patterns
### Standard Imports
- Always use relative paths for internal imports
- Import types with `type` keyword when used only for typing
- Import schemas without `type` when used for encoding/decoding
```typescript
// ✅ CORRECT - Import patterns
import {
FetchHttpClient,
HttpClientRequest,
HttpClientResponse,
} from '@effect/platform'
import {
BlogPost,
BlogPostCategory,
type BlogPostPatches,
CreateBlogPostInput,
GetBlogPageInput,
} from '@t6c/blog-domain'
import {
type BlogPostId,
PaginationSchema,
type SearchParamsSchema,
type UserId,
} from '@t6c/domain-common'
import { NotFoundError, createHttpClient } from '@t6c/lib-api'
import { Data, Effect as E, Layer, Schema as S } from 'effect'
import { envVars } from '../config.js'
```
## Method Implementation Patterns
### HTTP Method Mapping
- **GET** requests for data retrieval
- **POST** requests for resource creation
- **PUT** requests for resource updates
- **DELETE** requests for resource deletion
```typescript
// ✅ CORRECT - HTTP method usage
createDraft: ({ authorId }: { authorId: UserId }) =>
HttpClientRequest.post('/v1/blog').pipe(
HttpClientRequest.bodyJson(CreateBlogPostInput.make({ authorId })),
// ...
),
updateAttributes: (blogPostId: string, patches: BlogPostPatches) =>
HttpClientRequest.put(`/v1/blog/${blogPostId}`).pipe(
HttpClientRequest.bodyJson(patches),
// ...
),
delete: (id: string) =>
HttpClientRequest.del(`/v1/blog/${id}`).pipe(
// ...
),
```
### Request Parameter Handling
#### Path Parameters
- Use template literals for path parameters
- Always validate parameter types
```typescript
// ✅ CORRECT - Path parameters
getById: (blogPostId: string) =>
HttpClientRequest.get(`/v1/blog/${blogPostId}`).pipe(
// ...
),
like: (blogPostId: BlogPostId, userId: UserId) =>
HttpClientRequest.get(`/v1/blog/${blogPostId}/like/${userId}`).pipe(
// ...
),
```
#### Query Parameters
- Use `HttpClientRequest.setUrlParams` for query parameters
- Encode complex objects using Schema.encode when needed
- Convert numbers to strings for URL parameters
```typescript
// ✅ CORRECT - Query parameters with schema encoding
getPage: (params: GetBlogPageInput) =>
S.encode(GetBlogPageInput)(params).pipe(
E.flatMap((urlParams) =>
HttpClientRequest.get('/v1/blog').pipe(
HttpClientRequest.setUrlParams(urlParams),
client.execute,
),
),
// ...
),
// ✅ CORRECT - Simple query parameters
search: (input: SearchParamsSchema) =>
HttpClientRequest.get('/v1/blog/search').pipe(
HttpClientRequest.setUrlParams({
query: input.query,
limit: input.limit.toString(),
page: input.page.toString(),
}),
// ...
),
```
#### Request Body
- Use `HttpClientRequest.bodyJson` for JSON payloads
- Always validate request body with schemas
```typescript
// ✅ CORRECT - Request body
createDraft: ({ authorId }: { authorId: UserId }) =>
HttpClientRequest.post('/v1/blog').pipe(
HttpClientRequest.bodyJson(CreateBlogPostInput.make({ authorId })),
// ...
),
```
### Response Handling
#### Schema Validation
- **ALWAYS** decode responses using schemas
- Use appropriate response schemas for each endpoint
- Handle pagination responses correctly
```typescript
// ✅ CORRECT - Response decoding
getById: (blogPostId: string) =>
HttpClientRequest.get(`/v1/blog/${blogPostId}`).pipe(
client.execute,
E.flatMap(HttpClientResponse.schemaBodyJson(BlogPost)),
// ...
),
// ✅ CORRECT - Paginated response
getPage: (params: GetBlogPageInput) =>
// ... request setup
E.flatMap(
HttpClientResponse.schemaBodyJson(PaginationSchema(BlogPost)),
),
// ...
```
#### Error Handling
- **ALWAYS** handle 404 errors appropriately
- Use `E.catchIf` for specific error conditions
- Convert HTTP errors to domain errors when appropriate
```typescript
// ✅ CORRECT - 404 error handling
getById: (blogPostId: string) =>
HttpClientRequest.get(`/v1/blog/${blogPostId}`).pipe(
client.execute,
E.flatMap(HttpClientResponse.schemaBodyJson(BlogPost)),
E.scoped,
E.catchIf(
(error) =>
error._tag === 'ResponseError' && error.response.status === 404,
() => new NotFoundError({ resource: 'BlogPost', id: blogPostId }),
),
// ...
),
```
## Logging and Observability
### Mandatory Logging
- **ALWAYS** log successful responses for debugging
- **ALWAYS** log errors using `E.tapError(E.logError)`
- **ALWAYS** add tracing spans with relevant attributes
```typescript
// ✅ CORRECT - Comprehensive logging and tracing
getById: (blogPostId: string) =>
HttpClientRequest.get(`/v1/blog/${blogPostId}`).pipe(
client.execute,
E.flatMap(HttpClientResponse.schemaBodyJson(BlogPost)),
E.scoped,
E.catchIf(
(error) =>
error._tag === 'ResponseError' && error.response.status === 404,
() => new NotFoundError({ resource: 'BlogPost', id: blogPostId }),
),
E.tap((res) => E.logInfo('getById res', JSON.stringify(res))),
E.tapError(E.logError),
E.withSpan('get-blog-post-by-id', {
attributes: {
blogPostId,
},
}),
),
```
### Span Naming
- Use kebab-case for span names
- Include relevant context in span attributes
- Match span names to operation purpose
```typescript
// ✅ CORRECT - Span naming
E.withSpan('get-blog-post-by-id', {
attributes: { blogPostId },
}),
E.withSpan('search-blog-post', {
attributes: { input },
}),
E.withSpan('update-blog-post-attributes', {
attributes: { blogPostId, patches },
}),
```
## Method Documentation
### JSDoc Comments
- **ALWAYS** document each client method
- Include HTTP method and endpoint path
- Describe parameters and return types
```typescript
// ✅ CORRECT - Method documentation
/**
* Get blog post by ID
* GET /v1/blog/{id}
*/
getById: (blogPostId: string) => // ...
/**
* Search blog posts
* GET /v1/blog/search
*/
search: (input: SearchParamsSchema) => // ...
/**
* Update blog post attributes
* PUT /v1/blog/{id}
*/
updateAttributes: (blogPostId: string, patches: BlogPostPatches) => // ...
```
## Test Service Implementation
### Mock Service Pattern
- **ALWAYS** provide a test service implementation
- Use `Layer.succeed` for mocking
- Provide sensible defaults that throw for unimplemented methods
```typescript
// ✅ CORRECT - Test service
static makeTestService = (
mockImplementation: Partial<Omit<BlogPostService, '_tag'>>,
) =>
Layer.succeed(this, {
_tag: '@web/BlogPostService',
createDraft: () => E.die('Not implemented' as const),
getPage: () => E.die('Not implemented' as const),
getById: () => E.die('Not implemented' as const),
// ... all methods with defaults
...mockImplementation,
})
```
## Endpoint Coverage Requirements
### Complete API Coverage
- **MUST** implement ALL endpoints from the corresponding API service
- **MUST** match handler signatures exactly
- **MUST** use correct HTTP methods as defined in handlers
- **MUST** handle all parameter types (path, query, body)
### Validation Checklist
When adding/updating a client, verify:
- [ ] All handlers from `packages/{service}-api/src/lambdas/` are covered
- [ ] HTTP methods match handler implementations
- [ ] Request parameters are correctly encoded
- [ ] Response types are correctly decoded
- [ ] Error handling covers 404 and other expected errors
- [ ] Logging and tracing are implemented
- [ ] JSDoc documentation is complete
- [ ] Test service mock is updated
## Common Patterns
### Void Responses
- Use `E.asVoid` for endpoints that don't return data
- Still log completion for debugging
```typescript
// ✅ CORRECT - Void response
view: (blogPostId: string) =>
HttpClientRequest.get(`/v1/blog/${blogPostId}/view`).pipe(
client.execute,
E.scoped,
E.asVoid,
E.tap(() => E.logInfo('view completed', { blogPostId })),
E.tapError(E.logError),
E.withSpan('add-view', {
attributes: { blogPostId },
}),
),
```
### Optional Parameters
- Provide sensible defaults for optional parameters
- Use nullish coalescing for default values
```typescript
// ✅ CORRECT - Optional parameters
getAllTags: (params?: GetTagsInput) =>
S.encode(GetTagsInput)(params ?? { page: 1, limit: 100 }).pipe(
// ...
),
```
### Configuration
- **ALWAYS** use environment variables from config
- **NEVER** hardcode URLs or API keys
- Use `createHttpClient` helper for consistent setup
```typescript
// ✅ CORRECT - Configuration usage
const client = yield* createHttpClient({
url: envVars.BLOG_SERVICE_URL,
apiKey: envVars.BLOG_SERVICE_API_KEY,
})
```