Implement conditional requests with ETags and Last-Modified for efficient caching and concurrency control.
You are a caching specialist implementing efficient conditional request handling.
## CONTEXT
I need to implement conditional requests for my API.
**Requirements:**
- Resource Types: {{RESOURCES}}
- Update Frequency: {{FREQUENCY}}
- Concurrency Needs: {{CONCURRENCY}}
- Cache Strategy: {{CACHE}}
## TASK
Design conditional request handling:
### 1. ETAG GENERATION
```typescript
function generateETag(data: any): string {
const hash = crypto
.createHash('md5')
.update(JSON.stringify(data))
.digest('hex');
return `"${hash}"`;
}
```
### 2. GET WITH CONDITIONAL
```
Request:
GET /api/users/123
If-None-Match: "abc123"
Response (not modified):
HTTP/1.1 304 Not Modified
ETag: "abc123"
Response (modified):
HTTP/1.1 200 OK
ETag: "def456"
{...new data...}
```
### 3. PUT WITH CONDITIONAL (Optimistic Locking)
```
Request:
PUT /api/users/123
If-Match: "abc123"
{...update data...}
Response (conflict):
HTTP/1.1 412 Precondition Failed
{
"error": "Resource was modified",
"currentETag": "def456"
}
```
### 4. LAST-MODIFIED
```
Response:
Last-Modified: Wed, 15 Jan 2024 10:30:00 GMT
Request:
If-Modified-Since: Wed, 15 Jan 2024 10:30:00 GMT
```
### 5. IMPLEMENTATION
```typescript
async function handleConditional(req, res, resource) {
const etag = generateETag(resource);
if (req.headers['if-none-match'] === etag) {
return res.status(304).end();
}
res.setHeader('ETag', etag);
return res.json(resource);
}
```
### 6. WEAK VS STRONG ETAGS
```
Strong: "abc123"
Weak: W/"abc123"
```Or press ⌘C to copy
Replace these placeholders with your own content before using the prompt.
[{RESOURCES][{FREQUENCY][{CONCURRENCY][{CACHE]{
const hash = crypto
.createHash('md5')
.update(JSON.stringify(data))
.digest('hex');
return `"${hash}{...new data...}{...update data...}{
"error": "Resource was modified",
"currentETag": "def456"
}{
const etag = generateETag(resource);
if (req.headers['if-none-match'] === etag) {
return res.status(304).end();
}