Skip to content

Commit 3715e94

Browse files
author
Gerome El-assaad
committed
feat: Update file handling API endpoints
1 parent 70315ad commit 3715e94

2 files changed

Lines changed: 21 additions & 20 deletions

File tree

app/api/files/content/route.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
import { NextResponse } from 'next/server'
22
import { Sandbox } from '@e2b/code-interpreter'
3+
import { LRUCache } from 'lru-cache'
4+
5+
const cache = new LRUCache<string, string>({
6+
max: 500,
7+
ttl: 1000 * 60 * 5, // 5 minutes
8+
})
39

410
export const runtime = 'nodejs'
511
export const dynamic = 'force-dynamic'
@@ -41,8 +47,18 @@ export async function GET(req: Request) {
4147
)
4248
}
4349

50+
const cacheKey = `${sessionID}:${path}`
51+
const cachedContent = cache.get(cacheKey)
52+
53+
if (cachedContent) {
54+
return NextResponse.json({ content: cachedContent })
55+
}
56+
4457
const sandbox = await getSandbox(sessionID, template || undefined)
4558
const content = await sandbox.files.read(path)
59+
60+
cache.set(cacheKey, content)
61+
4662
return NextResponse.json({ content })
4763
} catch (error: any) {
4864
return NextResponse.json(
@@ -65,6 +81,10 @@ export async function POST(req: Request) {
6581

6682
const sandbox = await getSandbox(sessionID, template || undefined)
6783
await sandbox.files.write(path, content)
84+
85+
const cacheKey = `${sessionID}:${path}`
86+
cache.delete(cacheKey)
87+
6888
return NextResponse.json({ success: true })
6989
} catch (error: any) {
7090
return NextResponse.json(

app/api/files/route.ts

Lines changed: 1 addition & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { NextRequest, NextResponse } from 'next/server'
22
import { Sandbox, FileType } from '@e2b/code-interpreter'
33
import { FileSystemNode } from '@/components/file-tree'
4+
import { getSandbox } from '@/lib/sandbox'
45

56
export const runtime = 'nodejs'
67
export const dynamic = 'force-dynamic'
@@ -31,26 +32,6 @@ async function listFilesRecursively(
3132
return nodes
3233
}
3334

34-
const E2B_API_KEY = process.env.E2B_API_KEY
35-
36-
const sandboxTimeout = 10 * 60 * 1000
37-
38-
async function getSandbox(sessionID: string, template?: string) {
39-
if (!E2B_API_KEY) {
40-
throw new Error('E2B_API_KEY environment variable not found')
41-
}
42-
43-
const sandbox = await Sandbox.create(template || 'code-interpreter-v1', {
44-
apiKey: E2B_API_KEY,
45-
metadata: {
46-
sessionID,
47-
template: template || 'code-interpreter-v1',
48-
},
49-
timeoutMs: sandboxTimeout,
50-
})
51-
return sandbox
52-
}
53-
5435
export async function GET(request: NextRequest) {
5536
const searchParams = request.nextUrl.searchParams
5637
const sessionID = searchParams.get('sessionID')

0 commit comments

Comments
 (0)