Skip to content

Instantly share code, notes, and snippets.

@Code-Hex
Last active July 7, 2022 03:09
Show Gist options
  • Save Code-Hex/530458c4b4d54844100d80ae5e831e4a to your computer and use it in GitHub Desktop.
Save Code-Hex/530458c4b4d54844100d80ae5e831e4a to your computer and use it in GitHub Desktop.
okinawa.rb #222 で Cloudflare Workers を紹介しました
// Service Worker Syntax で書いてます
// addEventListener('fetch', event => {
// event.respondWith(handleRequest(event.request));
// });
// Module Worker Syntax で書いてます
// async function handleRequest(request) {
// return new Response('Hello worker!', {
// headers: { 'content-type': 'text/plain' },
// });
// }
// ここからは R2 への画像アップロード
interface Env {
CODEHEX_BUCKET: R2Bucket
}
export default {
async fetch(request: Request, env: Env) {
const url = new URL(request.url)
const path = url.pathname
if (path === "/upload") {
const formdata = await request.formData()
const imagedata = formdata.get("imagedata")
if (imagedata === null) {
throw new Error("not found imagedata")
}
const file = imagedata as File
const obj = await env.CODEHEX_BUCKET.put("image", file, {
httpMetadata: {
contentType: "image/png"
}
})
return new Response(`key: ${obj.key}!!`, {
headers: { 'content-type': 'text/plain' },
})
}
if (path === "/image") {
const obj = await env.CODEHEX_BUCKET.get("image")
if (obj === null) {
throw new Error("upload してー")
}
return new Response(obj.body)
}
return new Response('Not found', {
status: 404,
headers: { 'content-type': 'text/plain' },
});
}
}
{
"name": "hn-image-workers",
"version": "1.0.0",
"description": "cloudflare r2 image workers for hacker news",
"main": "dist/index.js",
"author": "Kei Kamikawa <[email protected]>",
"license": "MIT",
"scripts": {
"dev": "wrangler dev ./src/index.ts",
"deploy": "wrangler publish ./src/index.ts"
},
"devDependencies": {
"@cloudflare/workers-types": "^3.14.0",
"@tsconfig/recommended": "^1.0.1",
"miniflare": "^2.5.1",
"wrangler": "^2.0.16"
},
"dependencies": {}
}
{
"extends": "@tsconfig/recommended/tsconfig.json",
"compilerOptions": {
"lib": ["es2022"],
"target": "es2022",
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node",
"types": [
"@cloudflare/workers-types"
]
}
}
name = "hn-image-workers"
compatibility_date = "2022-07-06"
[[r2_buckets]]
binding = "CODEHEX_BUCKET"
bucket_name = "codehex-bucket"
@Code-Hex
Copy link
Author

Code-Hex commented Jul 6, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment