Skip to content

Commit

Permalink
comments dev
Browse files Browse the repository at this point in the history
  • Loading branch information
StephenJLu committed Jan 4, 2025
1 parent c20b505 commit 30aac5b
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 96 deletions.
99 changes: 29 additions & 70 deletions app/routes/r2-test/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// Check requests for a pre-shared secret
const hasValidHeader = (request, env) => {
return (request.headers.get("X-Custom-Auth-Key") === env.AUTH_KEY_SECRET);
};
Expand All @@ -12,7 +11,6 @@ export default {
'Content-Type': 'application/json'
};

// Handle OPTIONS preflight
if (request.method === 'OPTIONS') {
return new Response(null, {
headers: corsHeaders
Expand All @@ -26,93 +24,54 @@ export default {
});
}

const url = new URL(request.url);
const key = url.pathname.slice(1);

try {
switch (request.method) {
case "PUT": {
// Get existing comments or initialize empty array
let comments = [];
const existingComments = await env.R2_BUCKET.get('comments.json');

if (existingComments) {
const existingData = await existingComments.json();
comments = existingData || [];
try {
const existingText = await existingComments.text();
if (existingText) {
comments = JSON.parse(existingText);
}
} catch (e) {
console.error('Failed to parse existing comments:', e);
comments = [];
}
}

// Add new comment
const newComment = await request.json();
comments.push(newComment);

// Save updated comments
await env.R2_BUCKET.put('comments.json', JSON.stringify(comments));

return new Response(JSON.stringify({ success: true }), {
return new Response(JSON.stringify({
success: true,
message: 'Comment saved'
}), {
headers: corsHeaders
});
}

case "GET":
if (key.endsWith('/')) {
// List objects with prefix
const prefix = key;
const objects = [];
let cursor;

do {
const listing = await env.R2_STORAGE.list({
prefix: prefix,
cursor: cursor,
limit: 1000
});

objects.push(...listing.objects.map(obj => ({
name: obj.key,
size: obj.size,
uploaded: obj.uploaded.toISOString()
})));

cursor = listing.cursor;
} while (cursor);

return new Response(JSON.stringify(objects), {
headers: {
...corsHeaders,
'Content-Type': 'application/json'
}
case "GET": {
const comments = await env.R2_BUCKET.get('comments.json');
if (!comments) {
return new Response(JSON.stringify([]), {
headers: corsHeaders
});
} else {
const object = await env.R2_STORAGE.get(key);
if (object === null) {
return new Response("Object Not Found", {
status: 404,
headers: corsHeaders
});
}
const headers = new Headers(corsHeaders);
object.writeHttpMetadata(headers);
headers.set("etag", object.httpEtag);
return new Response(object.body, { headers });
}
default:
return new Response("Method Not Allowed", {
status: 405,
headers: {
...corsHeaders,
Allow: "PUT, GET"
}
}
const data = await comments.text();
return new Response(data, {
headers: corsHeaders
});
}
} catch (error) {
console.error('Worker error:', error);
return new Response(JSON.stringify({
success: false,
error: error.message
}), {
status: 500,
headers: corsHeaders
});
}
} catch (error) {
console.error('Worker error:', error);
return new Response(JSON.stringify([]), {
headers: corsHeaders
});
}
};
}
};
48 changes: 22 additions & 26 deletions app/routes/r2-test/r2-worker-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,19 +27,23 @@ interface LoaderData {

export const loader = async ({ context }: { context: any }) => {
try {
console.log('Fetching comments...');
const response = await fetch('https://r2-worker.stephenjlu.com/comments.json', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'X-Custom-Auth-Key': context.cloudflare.env.AUTH_KEY_SECRET // Need to pass auth key for GET
'X-Custom-Auth-Key': context.cloudflare.env.AUTH_KEY_SECRET
}
});

console.log('Loader response status:', response.status);
const comments = await response.json();
console.log('Loaded comments:', comments);
console.log('Response status:', response.status);
const text = await response.text();
console.log('Raw response:', text);

return json<LoaderData>({ comments: comments || [] });
const comments = text ? JSON.parse(text) : [];
console.log('Parsed comments:', comments);

return json<LoaderData>({ comments });
} catch (error) {
console.error('Loader error:', error);
return json<LoaderData>({ comments: [] });
Expand Down Expand Up @@ -133,6 +137,8 @@ export const R2WorkerTest = () => {
}
}, [actionData?.success, navigate]);

console.log('Render comments:', comments);

return (
<div data-theme="dark" style={{
display: 'flex',
Expand Down Expand Up @@ -195,30 +201,20 @@ export const R2WorkerTest = () => {
</div>
)}

<div style={{
width: '100%',
maxWidth: '600px',
marginTop: '2rem'
}}>
<h2>Comments</h2>
{comments.length === 0 ? (
<div>No comments yet!</div>
) : (
comments.map((comment: Comment, index: number) => (
<div key={index} style={{
padding: '1rem',
marginBottom: '1rem',
borderBottom: '1px solid #333'
}}>
<div style={{ width: '100%', maxWidth: '600px', marginTop: '2rem' }}>
<h2>Comments ({comments.length})</h2>
{comments.length === 0 ? (
<div>No comments yet!</div>
) : (
comments.map((comment, index) => (
<div key={index} style={{ marginBottom: '1rem', padding: '1rem', border: '1px solid #ccc' }}>
<strong>{comment.name}</strong>
<p>{comment.comment}</p>
<small style={{ color: '#666' }}>
{formatDate(comment.timestamp)}
</small>
<small>{formatDate(comment.timestamp)}</small>
</div>
))
)}
</div>
))
)}
</div>
</div>
);
};

0 comments on commit 30aac5b

Please sign in to comment.