| 22 | ]; |
| 23 | |
| 24 | export async function handleR2TestSetup( |
| 25 | env: TestSetupBindings, |
| 26 | ): Promise<Response> { |
| 27 | if (env.ENVIRONMENT !== "test") { |
| 28 | console.warn("Attempted to run R2 setup outside test environment."); |
| 29 | return new Response("Forbidden", { |
| 30 | status: 403, |
| 31 | headers: { "Content-Type": "application/json" }, |
| 32 | }); |
| 33 | } |
| 34 | |
| 35 | console.log("Handling R2 setup for tests using hardcoded content..."); |
| 36 | |
| 37 | if (!env.DOCS_BUCKET) { |
| 38 | console.error("DOCS_BUCKET binding not found in environment."); |
| 39 | return new Response( |
| 40 | JSON.stringify({ error: "R2 bucket binding not configured" }), |
| 41 | { |
| 42 | status: 500, |
| 43 | headers: { "Content-Type": "application/json" }, |
| 44 | }, |
| 45 | ); |
| 46 | } |
| 47 | |
| 48 | const results = []; |
| 49 | let errors = 0; |
| 50 | |
| 51 | for (const file of dummyFilesToUpload) { |
| 52 | try { |
| 53 | await env.DOCS_BUCKET.put(file.bucketPath, file.content); |
| 54 | results.push( |
| 55 | `Successfully uploaded hardcoded content to ${file.bucketPath}`, |
| 56 | ); |
| 57 | console.log(`Uploaded hardcoded content to ${file.bucketPath} in R2`); |
| 58 | } catch (error) { |
| 59 | const errorMessage = |
| 60 | error instanceof Error ? error.message : String(error); |
| 61 | console.error( |
| 62 | `Error uploading hardcoded content to ${file.bucketPath} in R2:`, |
| 63 | errorMessage, |
| 64 | ); |
| 65 | results.push( |
| 66 | `Failed to upload hardcoded content to ${file.bucketPath}: ${errorMessage}`, |
| 67 | ); |
| 68 | errors++; |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | const responseBody = { |
| 73 | message: |
| 74 | errors > 0 |
| 75 | ? `R2 setup partially failed. ${errors} errors.` |
| 76 | : "R2 setup with hardcoded content successful.", |
| 77 | details: results, |
| 78 | }; |
| 79 | const status = errors > 0 ? 500 : 200; |
| 80 | |
| 81 | return new Response(JSON.stringify(responseBody), { |