Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import { generateVideo, getVideoJobStatus } from '@tanstack/ai'
3import { openaiVideo } from '@tanstack/ai-openai'
4
5type Action = 'create' | 'status' | 'url'
6
7export const Route = createFileRoute('/api/video')({
8 server: {
9 handlers: {
10 POST: async ({ request }) => {
11 const body = await request.json()
12 const action: Action = body.action || 'create'
13
14 try {
15 const adapter = openaiVideo('sora-2')
16
17 switch (action) {
18 case 'create': {
19 const { prompt, size = '1280x720', seconds = 8 } = body
20
21 const result = await generateVideo({
22 adapter,
23 prompt,
24 size,
25 duration: seconds,
26 })
27
28 return new Response(
29 JSON.stringify({
30 action: 'create',
31 jobId: result.jobId,
32 model: result.model,
33 }),
34 {
35 status: 200,
36 headers: { 'Content-Type': 'application/json' },
37 },
38 )
39 }
40
41 case 'status': {
42 const { jobId } = body
43
44 if (!jobId) {
45 return new Response(
46 JSON.stringify({
47 error: 'jobId is required for status check',
48 }),
49 {
50 status: 400,
51 headers: { 'Content-Type': 'application/json' },
52 },
53 )
54 }
55
56 const result = await getVideoJobStatus({
57 adapter,
58 jobId,
59 })
60
61 return new Response(
62 JSON.stringify({
63 action: 'status',
64 jobId: result.jobId,
65 status: result.status,
66 progress: result.progress,
67 error: result.error,
68 }),
69 {
70 status: 200,
71 headers: { 'Content-Type': 'application/json' },
72 },
73 )
74 }
75
76 case 'url': {
77 const { jobId } = body
78
79 if (!jobId) {
80 return new Response(
81 JSON.stringify({
82 error: 'jobId is required for URL retrieval',
83 }),
84 {
85 status: 400,
86 headers: { 'Content-Type': 'application/json' },
87 },
88 )
89 }
90
91 const result = await adapter.getVideoUrl(jobId)
92
93 return new Response(
94 JSON.stringify({
95 action: 'url',
96 jobId: result.jobId,
97 url: result.url,
98 expiresAt: result.expiresAt?.toISOString(),
99 }),
100 {
101 status: 200,
102 headers: { 'Content-Type': 'application/json' },
103 },
104 )
105 }
106
107 default:
108 return new Response(
109 JSON.stringify({
110 error: `Unknown action: ${action}. Valid actions: create, status, url`,
111 }),
112 {
113 status: 400,
114 headers: { 'Content-Type': 'application/json' },
115 },
116 )
117 }
118 } catch (error: any) {
119 return new Response(
120 JSON.stringify({
121 error: error.message || 'An error occurred',
122 }),
123 {
124 status: 500,
125 headers: { 'Content-Type': 'application/json' },
126 },
127 )
128 }
129 },
130 },
131 },
132})