Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Storage #2

Merged
merged 6 commits into from
Jan 19, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ dist
dist-ssr
*.local

# cloudflare wrangler
/.wrangler/

# Editor directories and files
.vscode/*
!.vscode/extensions.json
Expand Down
87 changes: 87 additions & 0 deletions functions/api/store/[project].ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
export interface Env {
BUCKET: R2Bucket
}

export const onRequest: PagesFunction<Env> = async ({ request, env }) => {
const { url, method } = request
const { pathname, searchParams } = new URL(url)
const readKey = pathname.split('/')[3]
if (method === 'GET') {
return await get(readKey, env)
}

if (method !== 'POST') {
return new Response('Method not allowed', { status: 405 })
}

const contentType = request.headers.get('content-type')
if (!contentType || !contentType.includes('application/json')) {
return new Response('Invalid content type', { status: 400 })
}
// check body size
const body = await request.blob()
if (body.size > 1024 * 10) {
return new Response('File too large', { status: 413 })
}

if (readKey === 'new') {
return await storeNew(body, env)
} else {
return await storeExisting(body, readKey, searchParams, env)
}
}

async function get(readKey: string, env: Env): Promise<Response> {
const object = await env.BUCKET.get(filesPath(readKey))
if (object === null) {
return new Response('Project not found', { status: 404 })
} else {
return new Response(object.body, { headers: { 'content-type': 'application/json' } })
}
}

async function storeNew(body: Blob, env: Env): Promise<Response> {
const readKey = generateHex(16)
const writeKey = generateHex(32)
await Promise.all([env.BUCKET.put(filesPath(readKey), body), env.BUCKET.put(writeKeyPath(readKey), writeKey)])
const response = {
readKey,
writeKey,
}
return new Response(JSON.stringify(response), {
status: 201,
headers: {
'content-type': 'application/json',
},
})
}

async function storeExisting(body: Blob, readKey: string, search: URLSearchParams, env: Env): Promise<Response> {
const writeKey = search.get('writeKey')
if (!writeKey) {
return new Response('Unauthorized - no writeKey', { status: 401 })
}
const object = await env.BUCKET.get(writeKeyPath(readKey))
if (!object) {
return new Response('Project not found', { status: 404 })
}
const realWriteKey = await object.text()
if (realWriteKey !== writeKey) {
return new Response('Unauthorized - wrong writeKey', { status: 403 })
}

await env.BUCKET.put(filesPath(readKey), body)
return new Response('ok')
}

const filesPath = (readKey: string) => `${readKey}/files`
const writeKeyPath = (readKey: string) => `${readKey}/writeKey`

export function generateHex(length: number): string {
const size = Math.ceil(length / 2)
const array = new Uint8Array(size)
crypto.getRandomValues(array)
return toHexString(array).substring(0, length)
}

const toHexString = (array: Uint8Array) => Array.from(array, (byte) => byte.toString(16).padStart(2, '0')).join('')
16 changes: 16 additions & 0 deletions functions/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"lib": ["esnext"],

/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true,

"types": ["@cloudflare/workers-types"]
}
}
Loading
Loading