Niklas
Niklas
Explore posts from servers
CDCloudflare Developers
Created by Niklas on 10/21/2024 in #workers-help
Resizing a private image in an R2 bucket through a worker
export default {
async fetch(request, env): Promise<Response> {
const url = new URL(request.url);
const key = url.pathname.slice(1);

switch (request.method) {
case "PUT":

const url = key + "/image"
await env.MY_BUCKET.put(url, request.body);

const resizeOptions = {cf: {image: {width: 500,height: 500,quality: 50,},},};

const transformedResponse = await fetch(`https://pub-0dc2d101c4l85b4635bbd2ab7et172.r2.dev/${url}`, resizeOptions); //<--Puplic Bucket

if (!transformedResponse.ok) {
return new Response(`Image transformation failed: ${transformedResponse.statusText}`, { status: transformedResponse.status });
}

const transformedImage = await transformedResponse.arrayBuffer();

const thumbnailUrl = key + "/thumbnail";
await env.MY_BUCKET.put(thumbnailUrl, transformedImage);

return new Response(`Put ${key} successfully! Thumbnail stored at ${thumbnailUrl}`);

default:
return new Response("Method Not Allowed", {
status: 405,
headers: {
Allow: "PUT, GET, DELETE",
},
});
}
},
} satisfies ExportedHandler<Env>;
export default {
async fetch(request, env): Promise<Response> {
const url = new URL(request.url);
const key = url.pathname.slice(1);

switch (request.method) {
case "PUT":

const url = key + "/image"
await env.MY_BUCKET.put(url, request.body);

const resizeOptions = {cf: {image: {width: 500,height: 500,quality: 50,},},};

const transformedResponse = await fetch(`https://pub-0dc2d101c4l85b4635bbd2ab7et172.r2.dev/${url}`, resizeOptions); //<--Puplic Bucket

if (!transformedResponse.ok) {
return new Response(`Image transformation failed: ${transformedResponse.statusText}`, { status: transformedResponse.status });
}

const transformedImage = await transformedResponse.arrayBuffer();

const thumbnailUrl = key + "/thumbnail";
await env.MY_BUCKET.put(thumbnailUrl, transformedImage);

return new Response(`Put ${key} successfully! Thumbnail stored at ${thumbnailUrl}`);

default:
return new Response("Method Not Allowed", {
status: 405,
headers: {
Allow: "PUT, GET, DELETE",
},
});
}
},
} satisfies ExportedHandler<Env>;
How can I handle the fetch operation to resize my image when my R2 bucket is private? The resizing only works with a URL, right? Do I have to create another worker to make this possible? Thanks Niklas
1 replies
DTDrizzle Team
Created by Niklas on 9/19/2023 in #help
Is there a faster way todo this?
await db.transaction(async (tx) => {
for (let i = 0; i < data.length; i++) {
tx.update(cities)
.set({ name: data[i].name })
.where(eq(cities.id, data[i].id));
}
});
await db.transaction(async (tx) => {
for (let i = 0; i < data.length; i++) {
tx.update(cities)
.set({ name: data[i].name })
.where(eq(cities.id, data[i].id));
}
});
This takes about 250ms for me, I find this very slow...
4 replies