How to Manage Fastio File Metadata with Prisma ORM
Managing Fastio file metadata with Prisma ORM involves setting up a schema matching Fastio's file and workspace IDs. Handle webhooks to keep your database current. You can then query files with app data using Prisma's type-safe client. Prisma is trusted by more than 500k monthly active developers and works well for workspace-file relationships. Developers use it to track agent uploads, check usage, or build dashboards. Start with the Prisma schema, followed by the webhook handler.
Managing Fastio File Metadata with Prisma ORM: Why Sync?
Fastio workspaces store files with details like names, sizes, MIME types, and upload times. Agent apps need this data next to user records or analytics in their database. Webhooks sync changes without polling the API. This saves credits and keeps data up to date. Prisma lets you run quick queries. It works for other storage services too. Fastio events for uploads, updates, and access fit right in. The setup can handle thousands of files across agent-driven workflows. Helpful references: Fastio Workspaces, Fastio Collaboration, and Fastio AI.
Prisma Schema for Fastio Files
Start with a schema for key Fastio file details. Use their node IDs as unique keys.
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model Workspace {
id String @id @default(uuid())
fastioId String @unique // Fastio workspace profile ID
name String
description String?
createdAt DateTime @default(now())
files File[]
}
model File {
id String @id @default(uuid())
fastioId String @unique // Fastio node opaque ID (f..., d...)
name String
sizeBytes BigInt
mimeType String
uploadedAt DateTime?
workspaceId String
workspace Workspace @relation(fields: [workspaceId], references: [id])
metadata Json? // Custom or AI-extracted metadata
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
Run npx prisma db push to apply it. This sets up one-to-many workspaces to files, using Fastio IDs to avoid duplicates.
Build Agent Workspaces with File Sync
Get 50GB free storage and 5,000 monthly credits for agents. No credit card needed. Sync metadata and query with Prisma in your workflows.
How to Configure Fastio Webhooks
In Fastio org settings or via API, point a webhook to your endpoint, like https://yourapp.com/api/fastio-webhook.
Subscribe to file.uploaded, file.updated, file.deleted, file.accessed. Fastio sends JSON payloads with file details and node ID.
Verify with the signature header. Upsert records in Prisma on receipt. This approach ensures data consistency even with duplicate deliveries.
Example payload:
{
"event": "file.uploaded",
"workspace_id": "1234567890123456789",
"node_id": "f3jm5-zqzfx-pxdr2-dx8z5-bvnb3-rpjfm4",
"name": "report.pdf",
"size_bytes": 2048000,
"mime_type": "application/pdf"
}
How to Build the Webhook Sync Handler
Create an Express or Next.js API route. Verify signature, find or create workspace, then upsert file.
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
export async function POST(req: Request) {
const payload = await req.json();
const signature = req.headers.get('Fastio-Signature');
// Verify signature (implement HMAC check with your webhook secret)
const { event, workspace_id: fastioWorkspaceId, node_id: fastioFileId, name, size_bytes, mime_type, uploaded_at } = payload;
// Upsert workspace
const workspace = await prisma.workspace.upsert({
where: { fastioId: fastioWorkspaceId },
update: {},
create: { fastioId: fastioWorkspaceId, name: 'Unknown Workspace' }
});
// Upsert file
await prisma.file.upsert({
where: { fastioId: fastioFileId },
update: {
name,
sizeBytes: BigInt(size_bytes),
mimeType: mime_type,
uploadedAt: new Date(uploaded_at),
workspaceId: workspace.id
},
create: {
fastioId: fastioFileId,
name,
sizeBytes: BigInt(size_bytes),
mimeType: mime_type,
uploadedAt: new Date(uploaded_at),
workspaceId: workspace.id
}
});
return Response.json({ received: true });
}
Deploy to Vercel or similar. Test it with Fastio's webhook tester.
Querying Synced Metadata
Data in place? Time to query.
Large files: prisma.file.findMany({ where: { sizeBytes: { gt: 100000000n } } })
Recent uploads in a workspace:
const recent = await prisma.file.findMany({
where: {
workspace: { fastioId: 'your-workspace-id' },
uploadedAt: { gt: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000) }
},
include: { workspace: true },
orderBy: { uploadedAt: 'desc' }
});
By MIME type totals: prisma.file.groupBy({ by: ['mimeType'], _sum: { sizeBytes: true } })
Tie it into users or tasks for full picture. For example, join files with user accounts to track uploads per developer or agent session.
Advanced: Fetch Full Details and Handle Deletes
Webhooks cover basics like file name and size. For complete metadata such as preview URLs and AI extraction status, hit Fastio's GET /storage/details API using the node ID.
Add this to the handler:
// Fetch full details if needed
const details = await fetch(`https://api.fast.io/current/storage/${workspace.fastioId}/${fastioFileId}/details/`, {
headers: { Authorization: `Bearer ${process.env.FASTIO_TOKEN}` }
}).then(r => r.json());
// Update with details.preview_url, details.ai_state, etc.
On file.deleted: prisma.file.update({ where: { fastioId: fastioFileId }, data: { deletedAt: new Date() } }) or soft delete.
For edge cases, check updated_at for idempotency, batch for rate limits, use transactions for conflicts.
Error Handling and Idempotency
Webhook handlers must verify signatures and handle failures gracefully. Start with HMAC verification using your Fastio webhook secret.
import crypto from 'crypto';
const signature = req.headers.get('Fastio-Signature');
const secret = process.env.FASTIO_WEBHOOK_SECRET!;
const hmac = crypto.createHmac('sha256', secret);
const digest = `sha256=${hmac.update(JSON.stringify(payload)).digest('hex')}`;
if (signature !== digest) {
return new Response('Invalid signature', { status: 401 });
}
For retries, use exponential backoff on transient errors like database locks. Prisma Client retries some operations internally, but for serverless workloads consider connection pooling. Implement idempotency by checking the incoming event ID or timestamp against your stored updatedAt value before writing.
Dead-letter queues such as Redis, SQS, or another durable queue can capture permanent failures for manual review.
Scaling Sync for Production
Agents can generate high webhook volume. Offload processing to queues like BullMQ or AWS SQS instead of doing every write inline with the request. This keeps webhook response times low during traffic spikes from multiple agents.
Batch upserts with Prisma transactions:
await prisma.$transaction(
files.map((fileData) =>
prisma.file.upsert({
where: { fastioId: fileData.fastioId },
create: fileData,
update: fileData,
})
)
);
For initial bootstrap, list the existing files from Fastio and seed your tables before turning on webhooks. Then measure sync lag by comparing stored update timestamps against the latest webhook event time.
Agent Integration and MCP
Fastio's MCP server gives agents direct upload, search, sharing, and workflow access, so the same agent can trigger uploads and your webhook handler can persist the metadata into Prisma.
A practical workflow looks like this: an agent creates or joins a workspace, uploads a report, your webhook stores the metadata in Prisma, and then a downstream process reads Prisma for analytics or audit reporting. Prisma queries enable joining file metadata with agent execution logs for end-to-end traceability.
Use the Fastio MCP marketing page for agent setup guidance, not the raw MCP endpoint URL, when you link this article to product pages.
Frequently Asked Questions
How do I store file metadata in a database?
Link Fastio file IDs to Prisma records. Upsert webhook data for name, size, MIME type, and extras in JSON. Relate files to workspaces or users.
How to sync external API data with Prisma?
Webhooks for events. Verify signatures and upsert by ID. Fetch more via API if needed. Use transactions to stay consistent.
What Fastio events trigger metadata sync?
file.uploaded, file.updated, file.deleted, file.accessed. Set in org settings or API. Payloads include node ID for matching.
Can agents manage this sync?
Yes, use Fastio MCP tools or REST API to create webhooks programmatically. Free agent tier supports up to multiple shares and multiple workspaces.
How to handle large-scale sync?
Batch upserts in Prisma transactions. Use queues like BullMQ for volume. Watch Fastio credits on API calls.
Related Resources
Build Agent Workspaces with File Sync
Get 50GB free storage and 5,000 monthly credits for agents. No credit card needed. Sync metadata and query with Prisma in your workflows.