Skip to content
Open
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
204 changes: 204 additions & 0 deletions playground/app/components/demos/R2Demo.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
<script setup lang="ts">
import { api } from '#convex/api'

const toast = useToast()

type R2Api = {
generateUploadUrl: any
syncMetadata: any
listMetadata: any
deleteObject: any
}

const r2Api = api as typeof api & { r2: R2Api }

const fileInput = ref<HTMLInputElement>()
const selectedFile = ref<File | null>(null)

const {
data,
pages,
isDone,
isLoadingMore,
loadMore,
reset,
isLoading,
} = useConvexPaginatedQuery(
r2Api.r2.listMetadata,
computed(() => ({})),
{ numItems: 9 },
)

const deletingKey = ref<string | null>(null)
const { mutate: deleteObject } = useConvexMutation(r2Api.r2.deleteObject, {
onError: (err) => {
toast.add({ title: 'Delete failed', description: err.message, color: 'error' })
},
})

const { upload, isUploading, progress, error: uploadError } = useConvexR2Upload(r2Api.r2, {
onSuccess: (key) => {
toast.add({ title: 'Uploaded to R2', description: key, color: 'success' })
selectedFile.value = null
reset()
},
onError: (err) => {
toast.add({ title: 'Upload failed', description: err.message, color: 'error' })
},
})

function handleFileSelect(event: Event) {
const file = (event.target as HTMLInputElement).files?.[0]
if (file) {
selectedFile.value = file
}
}

async function handleUpload() {
if (selectedFile.value) {
await upload(selectedFile.value)
}
}

async function handleDelete(key: string) {
if (deletingKey.value) return
deletingKey.value = key
try {
await deleteObject({ key })
reset()
}
finally {
deletingKey.value = null
}
}

function formatSize(bytes?: number) {
if (!bytes && bytes !== 0) return '—'
if (bytes < 1024) return `${bytes} B`
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
}
</script>

<template>
<div class="space-y-6">
<UCard>
<template #header>
<div class="flex items-center gap-2">
<UIcon name="i-simple-icons-cloudflare" class="text-primary" />
<span class="font-semibold">useConvexR2Upload</span>
</div>
</template>

<div class="text-sm text-muted mb-4">
Upload files directly to Cloudflare R2 and sync metadata to Convex.
</div>

<div class="text-xs text-muted mb-4">
Requires R2 credentials in your Convex environment: <code class="bg-muted px-1 rounded">R2_BUCKET</code>,
<code class="bg-muted px-1 rounded">R2_ENDPOINT</code>, <code class="bg-muted px-1 rounded">R2_ACCESS_KEY_ID</code>,
<code class="bg-muted px-1 rounded">R2_SECRET_ACCESS_KEY</code>.
</div>

<input ref="fileInput" type="file" class="hidden" @change="handleFileSelect">

<div class="space-y-4">
<div class="flex gap-2">
<UButton variant="outline" icon="i-heroicons-folder-open" @click="fileInput?.click()">
Select File
</UButton>
<UButton :loading="isUploading" :disabled="!selectedFile" @click="handleUpload">
Upload
</UButton>
</div>

<div v-if="selectedFile" class="flex items-center gap-2 p-2 rounded bg-muted text-sm">
<UIcon name="i-heroicons-document" class="text-muted" />
{{ selectedFile.name }}
<span class="text-muted">({{ formatSize(selectedFile.size) }})</span>
</div>

<div v-if="isUploading" class="space-y-2">
<UProgress :value="progress" />
<p class="text-xs text-muted">
{{ progress }}% uploaded
</p>
</div>

<UAlert v-if="uploadError" color="error" :title="uploadError.message" />
</div>
</UCard>

<UCard>
<template #header>
<div class="flex items-center justify-between">
<div class="flex items-center gap-2">
<UIcon name="i-heroicons-cloud" class="text-secondary" />
<span class="font-semibold">R2 Objects</span>
</div>
<UBadge v-if="data?.length" size="sm" color="neutral" variant="subtle">
{{ data.length }}
</UBadge>
</div>
</template>

<div v-if="isLoading && !data?.length" class="flex items-center gap-2 text-muted py-4">
<UIcon name="i-heroicons-arrow-path" class="animate-spin" />
Loading metadata...
</div>

<div v-else-if="data?.length" class="space-y-4">
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div v-for="item in data" :key="item.key" class="rounded-lg border border-default overflow-hidden">
<img v-if="item.contentType?.startsWith('image/')" :src="item.url" :alt="item.key" class="w-full h-32 object-cover">
<div v-else class="w-full h-32 bg-muted flex items-center justify-center">
<UIcon name="i-heroicons-document" class="size-8 text-muted" />
</div>

<div class="p-3 space-y-2">
<p class="text-xs text-muted truncate" :title="item.key">
{{ item.key }}
</p>
<div class="flex flex-wrap gap-2 text-xs">
<UBadge color="neutral" variant="subtle">
{{ item.contentType || 'unknown' }}
</UBadge>
<UBadge color="neutral" variant="subtle">
{{ formatSize(item.size) }}
</UBadge>
</div>

<div class="flex items-center gap-2">
<UButton size="xs" variant="outline" :to="item.url" target="_blank">
Open
</UButton>
<UButton
size="xs"
icon="i-heroicons-trash"
color="error"
variant="ghost"
:loading="deletingKey === item.key"
@click="handleDelete(item.key)"
/>
</div>
</div>
</div>
</div>

<div class="flex items-center justify-between pt-2 border-t border-default">
<div class="text-xs text-muted">
Showing {{ data.length }} items across {{ pages.length }} page(s)
</div>
<UButton v-if="!isDone" size="sm" :loading="isLoadingMore" @click="loadMore">
Load More
</UButton>
<UBadge v-else color="success" variant="subtle">
All loaded
</UBadge>
</div>
</div>

<UEmpty v-else icon="i-heroicons-cloud" title="No R2 objects" description="Upload a file above" class="py-6" />
</UCard>
</div>
</template>
4 changes: 3 additions & 1 deletion playground/app/pages/dashboard.vue
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@ definePageMeta({ middleware: 'auth' })

const convexUrl = useRuntimeConfig().public.convex?.url as string | undefined

type TabValue = 'queries' | 'mutations' | 'pagination' | 'storage' | 'actions'
type TabValue = 'queries' | 'mutations' | 'pagination' | 'storage' | 'r2' | 'actions'

const tabs: Array<{ label: string, value: TabValue, icon: string }> = [
{ label: 'Queries', value: 'queries', icon: 'i-heroicons-magnifying-glass' },
{ label: 'Mutations', value: 'mutations', icon: 'i-heroicons-pencil-square' },
{ label: 'Pagination', value: 'pagination', icon: 'i-heroicons-list-bullet' },
{ label: 'Storage', value: 'storage', icon: 'i-heroicons-cloud-arrow-up' },
{ label: 'R2', value: 'r2', icon: 'i-simple-icons-cloudflare' },
{ label: 'Actions', value: 'actions', icon: 'i-heroicons-bolt' },
]

Expand All @@ -18,6 +19,7 @@ const demoComponents: Record<TabValue, ReturnType<typeof resolveComponent>> = {
mutations: resolveComponent('DemosMutationsDemo'),
pagination: resolveComponent('DemosPaginationDemo'),
storage: resolveComponent('DemosStorageDemo'),
r2: resolveComponent('DemosR2Demo'),
actions: resolveComponent('DemosActionsDemo'),
}
</script>
Expand Down
2 changes: 2 additions & 0 deletions playground/convex/convex.config.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import betterAuth from '@convex-dev/better-auth/convex.config'
import r2 from '@convex-dev/r2/convex.config.js'
import { defineApp } from 'convex/server'

const app = defineApp()
app.use(betterAuth)
app.use(r2)

export default app
15 changes: 15 additions & 0 deletions playground/convex/r2.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { R2 } from '@convex-dev/r2'
import { componentsGeneric } from 'convex/server'
import type { DataModel } from './_generated/dataModel'

const components = componentsGeneric()

export const r2 = new R2(components.r2)

export const {
generateUploadUrl,
syncMetadata,
getMetadata,
listMetadata,
deleteObject,
} = r2.clientApi<DataModel>()
1 change: 1 addition & 0 deletions playground/nuxt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,5 +45,6 @@ export default defineNuxtConfig({

convex: {
storage: true,
r2: true,
},
})
1 change: 1 addition & 0 deletions playground/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"build": "nuxi build"
},
"dependencies": {
"@convex-dev/r2": "catalog:convex",
"@convex-dev/better-auth": "catalog:convex",
"@nuxthub/core": "catalog:playground",
"@onmax/nuxt-better-auth": "catalog:playground",
Expand Down
Loading
Loading