Express.js Integration
Torrin provides a dedicated Express middleware for seamless integration.
Setup
First, ensure you have the required packages:
bash
npm install express @torrin-kit/server @torrin-kit/server-express @torrin-kit/storage-localBasic Implementation
typescript
import express from 'express';
import { createTorrinExpressRouter } from '@torrin-kit/server-express';
import { createLocalStorageDriver } from '@torrin-kit/storage-local';
import { createInMemoryStore } from '@torrin-kit/server';
const app = express();
const port = 3000;
// Important: Parse JSON bodies
app.use(express.json());
// Configure Torrin Router
const torrinRouter = createTorrinExpressRouter({
// Where to store the uploaded chunks/files
storage: createLocalStorageDriver({
baseDir: './uploads'
}),
// Where to store upload state/metadata (In-memory is fine for dev, use Redis/DB for prod)
store: createInMemoryStore(),
// Configuration
defaultChunkSize: 1024 * 1024, // 1MB
maxChunkSize: 10 * 1024 * 1024, // 10MB
uploadTtlMs: 24 * 60 * 60 * 1000, // 24 hours
// Hooks
onBeforeInit: async (req, res) => {
console.log('New upload initialized');
// You can check auth here
// if (!req.user) throw new Error('Unauthorized');
},
onBeforeComplete: async (req, res) => {
console.log('Upload completing...');
}
});
// Mount the router
app.use('/torrin/uploads', torrinRouter);
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});