export default {
async fetch(request, env, ctx) {
try {
// Check if the R2 bucket binding exists
if (!env.MY_BUCKET) {
throw new Error("R2 bucket binding 'MY_BUCKET' is not defined");
}
const prefix = 'your-prefix/' // Replace with your desired prefix
const options = {
prefix: prefix,
limit: 1000, // Adjust as needed
}
const objects = await env.MY_BUCKET.list(options);
const totalFiles = objects.objects.length;
const first10Files = objects.objects.slice(0, 10).map(object => ({
name: object.key,
lastModified: new Date(object.uploaded).toISOString(),
}));
const latestAdditionTime = first10Files.length > 0
? first10Files.reduce((latest, file) =>
file.lastModified > latest ? file.lastModified : latest,
first10Files[0].lastModified)
: null;
return new Response(JSON.stringify({
totalFiles,
latestAdditionTime,
first10Files,
}, null, 2), {
headers: { 'Content-Type': 'application/json' },
});
} catch (error) {
console.error("Error in worker:", error);
return new Response(JSON.stringify({ error: error.message }), {
status: 500,
headers: { 'Content-Type': 'application/json' },
});
}
}
}
export default {
async fetch(request, env, ctx) {
try {
// Check if the R2 bucket binding exists
if (!env.MY_BUCKET) {
throw new Error("R2 bucket binding 'MY_BUCKET' is not defined");
}
const prefix = 'your-prefix/' // Replace with your desired prefix
const options = {
prefix: prefix,
limit: 1000, // Adjust as needed
}
const objects = await env.MY_BUCKET.list(options);
const totalFiles = objects.objects.length;
const first10Files = objects.objects.slice(0, 10).map(object => ({
name: object.key,
lastModified: new Date(object.uploaded).toISOString(),
}));
const latestAdditionTime = first10Files.length > 0
? first10Files.reduce((latest, file) =>
file.lastModified > latest ? file.lastModified : latest,
first10Files[0].lastModified)
: null;
return new Response(JSON.stringify({
totalFiles,
latestAdditionTime,
first10Files,
}, null, 2), {
headers: { 'Content-Type': 'application/json' },
});
} catch (error) {
console.error("Error in worker:", error);
return new Response(JSON.stringify({ error: error.message }), {
status: 500,
headers: { 'Content-Type': 'application/json' },
});
}
}
}