Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

api.video.ts

130 lines3.7 KB

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 threadId: 'panel-video',
23 adapter,
24 prompt,
25 size,
26 duration: seconds,
27 })
28​
29 return new Response(
30 JSON.stringify({
31 action: 'create',
32 jobId: result.jobId,
33 model: result.model,
34 }),
35 {
36 status: 200,
37 headers: { 'Content-Type': 'application/json' },
38 },
39 )
40 }
41​
42 case 'status': {
43 const { jobId } = body
44​
45 if (!jobId) {
46 return new Response(
47 JSON.stringify({
48 error: 'jobId is required for status check',
49 }),
50 {
51 status: 400,
52 headers: { 'Content-Type': 'application/json' },
53 },
54 )
55 }
56​
57 const result = await getVideoJobStatus({ adapter, jobId })
58​
59 return new Response(
60 JSON.stringify({
61 action: 'status',
62 jobId,
63 status: result.status,
64 progress: result.progress,
65 error: result.error,
66 }),
67 {
68 status: 200,
69 headers: { 'Content-Type': 'application/json' },
70 },
71 )
72 }
73​
74 case 'url': {
75 const { jobId } = body
76​
77 if (!jobId) {
78 return new Response(
79 JSON.stringify({
80 error: 'jobId is required for URL retrieval',
81 }),
82 {
83 status: 400,
84 headers: { 'Content-Type': 'application/json' },
85 },
86 )
87 }
88​
89 const result = await getVideoJobStatus({ adapter, jobId })
90​
91 return new Response(
92 JSON.stringify({
93 action: 'url',
94 jobId: result.jobId,
95 url: result.url,
96 expiresAt: result.expiresAt?.toISOString(),
97 }),
98 {
99 status: 200,
100 headers: { 'Content-Type': 'application/json' },
101 },
102 )
103 }
104​
105 default:
106 return new Response(
107 JSON.stringify({
108 error: `Unknown action: ${action}. Valid actions: create, status, url`,
109 }),
110 {
111 status: 400,
112 headers: { 'Content-Type': 'application/json' },
113 },
114 )
115 }
116 } catch (error: any) {
117 return new Response(
118 JSON.stringify({
119 error: error.message || 'An error occurred',
120 }),
121 {
122 status: 500,
123 headers: { 'Content-Type': 'application/json' },
124 },
125 )
126 }
127 },
128 },
129 },
130})