Created
March 2, 2025 22:31
-
-
Save maddsua/61fb5a5a4d267955a2b20b1f06d4649d to your computer and use it in GitHub Desktop.
Backups uploader worker for cloudflare r2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export default { | |
| async fetch(request, env, ctx) { | |
| return await backupHandler(request, env, ctx) | |
| .catch((error) => new Response(`${error}`, { status: 500 })); | |
| }, | |
| }; | |
| const backupHandler = async (request, env, ctx) => { | |
| if (request.method != 'PUT') { | |
| return new Response(null, { status: 405 }); | |
| } | |
| const token = env.TOKEN; | |
| const bearer = request.headers.get('authorization')?.replace(/^bearer\s+/i, ''); | |
| if (token && token != bearer) { | |
| await new Promise(resolve => setTimeout(resolve, 1000 + (Math.random() * 500))) | |
| return new Response(null, { status: 403 }); | |
| } | |
| const path = new URL(request.url).pathname.slice(1); | |
| if (!path.replace(/[\\\/.]+/g, '').length || /[\\\/]$/.test(path)) { | |
| return new Response(null, { status: 400 }); | |
| } | |
| const r2 = env.BUCKET; | |
| if (await r2.get(path)) { | |
| return new Response(null, { status: 409 }); | |
| } | |
| const body = await request.blob(); | |
| if (!body.size) { | |
| return new Response(null, { status: 411 }); | |
| } | |
| await r2.put(path, body) | |
| return new Response(null, { status: 201 }); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment