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

server-functions-handler.ts

323 lines9.4 KB

1import { isNotFound } from '@tanstack/router-core'
2import invariant from 'tiny-invariant'
3import {
4 TSS_FORMDATA_CONTEXT,
5 X_TSS_RAW_RESPONSE,
6 X_TSS_SERIALIZED,
7 getDefaultSerovalPlugins,
8} from '@tanstack/start-client-core'
9import { fromJSON, toCrossJSONAsync, toCrossJSONStream } from 'seroval'
10import { getResponse } from './request-response'
11import { getServerFnById } from './getServerFnById'
12​
13let regex: RegExp | undefined = undefined
14​
15export const handleServerAction = async ({
16 request,
17 context,
18}: {
19 request: Request
20 context: any
21}) => {
22 const controller = new AbortController()
23 const signal = controller.signal
24 const abort = () => controller.abort()
25 request.signal.addEventListener('abort', abort)
26​
27 if (regex === undefined) {
28 regex = new RegExp(`${process.env.TSS_SERVER_FN_BASE}([^/?#]+)`)
29 }
30​
31 const method = request.method
32 const url = new URL(request.url, 'http://localhost:3000')
33 // extract the serverFnId from the url as host/_serverFn/:serverFnId
34 // Define a regex to match the path and extract the :thing part
35​
36 // Execute the regex
37 const match = url.pathname.match(regex)
38 const serverFnId = match ? match[1] : null
39 const search = Object.fromEntries(url.searchParams.entries()) as {
40 payload?: any
41 createServerFn?: boolean
42 }
43​
44 const isCreateServerFn = 'createServerFn' in search
45​
46 if (typeof serverFnId !== 'string') {
47 throw new Error('Invalid server action param for serverFnId: ' + serverFnId)
48 }
49​
50 const action = await getServerFnById(serverFnId)
51​
52 // Known FormData 'Content-Type' header values
53 const formDataContentTypes = [
54 'multipart/form-data',
55 'application/x-www-form-urlencoded',
56 ]
57​
58 const contentType = request.headers.get('Content-Type')
59 const serovalPlugins = getDefaultSerovalPlugins()
60​
61 function parsePayload(payload: any) {
62 const parsedPayload = fromJSON(payload, { plugins: serovalPlugins })
63 return parsedPayload as any
64 }
65​
66 const response = await (async () => {
67 try {
68 let result = await (async () => {
69 // FormData
70 if (
71 formDataContentTypes.some(
72 (type) => contentType && contentType.includes(type),
73 )
74 ) {
75 // We don't support GET requests with FormData payloads... that seems impossible
76 invariant(
77 method.toLowerCase() !== 'get',
78 'GET requests with FormData payloads are not supported',
79 )
80 const formData = await request.formData()
81 const serializedContext = formData.get(TSS_FORMDATA_CONTEXT)
82 formData.delete(TSS_FORMDATA_CONTEXT)
83​
84 const params = {
85 context,
86 data: formData,
87 }
88 if (typeof serializedContext === 'string') {
89 try {
90 const parsedContext = JSON.parse(serializedContext)
91 if (typeof parsedContext === 'object' && parsedContext) {
92 params.context = { ...context, ...parsedContext }
93 }
94 } catch {}
95 }
96​
97 return await action(params, signal)
98 }
99​
100 // Get requests use the query string
101 if (method.toLowerCase() === 'get') {
102 invariant(
103 isCreateServerFn,
104 'expected GET request to originate from createServerFn',
105 )
106 // By default the payload is the search params
107 let payload: any = search.payload
108 // If there's a payload, we should try to parse it
109 payload = payload ? parsePayload(JSON.parse(payload)) : {}
110 payload.context = { ...context, ...payload.context }
111 // Send it through!
112 return await action(payload, signal)
113 }
114​
115 if (method.toLowerCase() !== 'post') {
116 throw new Error('expected POST method')
117 }
118​
119 let jsonPayload
120 if (contentType?.includes('application/json')) {
121 jsonPayload = await request.json()
122 }
123​
124 // If this POST request was created by createServerFn,
125 // its payload will be the only argument
126 if (isCreateServerFn) {
127 const payload = jsonPayload ? parsePayload(jsonPayload) : {}
128 payload.context = { ...payload.context, ...context }
129 return await action(payload, signal)
130 }
131​
132 // Otherwise, we'll spread the payload. Need to
133 // support `use server` functions that take multiple
134 // arguments.
135 return await action(...jsonPayload)
136 })()
137​
138 // Any time we get a Response back, we should just
139 // return it immediately.
140 if (result.result instanceof Response) {
141 result.result.headers.set(X_TSS_RAW_RESPONSE, 'true')
142 return result.result
143 }
144​
145 // If this is a non createServerFn request, we need to
146 // pull out the result from the result object
147 if (!isCreateServerFn) {
148 result = result.result
149​
150 // The result might again be a response,
151 // and if it is, return it.
152 if (result instanceof Response) {
153 return result
154 }
155 }
156​
157 // TODO: RSCs Where are we getting this package?
158 // if (isValidElement(result)) {
159 // const { renderToPipeableStream } = await import(
160 // // @ts-expect-error
161 // 'react-server-dom/server'
162 // )
163​
164 // const pipeableStream = renderToPipeableStream(result)
165​
166 // setHeaders(event, {
167 // 'Content-Type': 'text/x-component',
168 // } as any)
169​
170 // sendStream(event, response)
171 // event._handled = true
172​
173 // return new Response(null, { status: 200 })
174 // }
175​
176 if (isNotFound(result)) {
177 return isNotFoundResponse(result)
178 }
179​
180 const response = getResponse()
181 let nonStreamingBody: any = undefined
182​
183 if (result !== undefined) {
184 // first run without the stream in case `result` does not need streaming
185 let done = false as boolean
186 const callbacks: {
187 onParse: (value: any) => void
188 onDone: () => void
189 onError: (error: any) => void
190 } = {
191 onParse: (value) => {
192 nonStreamingBody = value
193 },
194 onDone: () => {
195 done = true
196 },
197 onError: (error) => {
198 throw error
199 },
200 }
201 toCrossJSONStream(result, {
202 refs: new Map(),
203 plugins: serovalPlugins,
204 onParse(value) {
205 callbacks.onParse(value)
206 },
207 onDone() {
208 callbacks.onDone()
209 },
210 onError: (error) => {
211 callbacks.onError(error)
212 },
213 })
214 if (done) {
215 return new Response(
216 nonStreamingBody ? JSON.stringify(nonStreamingBody) : undefined,
217 {
218 status: response?.status,
219 statusText: response?.statusText,
220 headers: {
221 'Content-Type': 'application/json',
222 [X_TSS_SERIALIZED]: 'true',
223 },
224 },
225 )
226 }
227​
228 // not done yet, we need to stream
229 const stream = new ReadableStream({
230 start(controller) {
231 callbacks.onParse = (value) =>
232 controller.enqueue(JSON.stringify(value) + '\n')
233 callbacks.onDone = () => {
234 try {
235 controller.close()
236 } catch (error) {
237 controller.error(error)
238 }
239 }
240 callbacks.onError = (error) => controller.error(error)
241 // stream the initial body
242 if (nonStreamingBody !== undefined) {
243 callbacks.onParse(nonStreamingBody)
244 }
245 },
246 })
247 return new Response(stream, {
248 status: response?.status,
249 statusText: response?.statusText,
250 headers: {
251 'Content-Type': 'application/x-ndjson',
252 [X_TSS_SERIALIZED]: 'true',
253 },
254 })
255 }
256​
257 return new Response(undefined, {
258 status: response?.status,
259 statusText: response?.statusText,
260 })
261 } catch (error: any) {
262 if (error instanceof Response) {
263 return error
264 }
265 // else if (
266 // isPlainObject(error) &&
267 // 'result' in error &&
268 // error.result instanceof Response
269 // ) {
270 // return error.result
271 // }
272​
273 // Currently this server-side context has no idea how to
274 // build final URLs, so we need to defer that to the client.
275 // The client will check for __redirect and __notFound keys,
276 // and if they exist, it will handle them appropriately.
277​
278 if (isNotFound(error)) {
279 return isNotFoundResponse(error)
280 }
281​
282 console.info()
283 console.info('Server Fn Error!')
284 console.info()
285 console.error(error)
286 console.info()
287​
288 const serializedError = JSON.stringify(
289 await Promise.resolve(
290 toCrossJSONAsync(error, {
291 refs: new Map(),
292 plugins: serovalPlugins,
293 }),
294 ),
295 )
296 const response = getResponse()
297 return new Response(serializedError, {
298 status: response?.status ?? 500,
299 statusText: response?.statusText,
300 headers: {
301 'Content-Type': 'application/json',
302 [X_TSS_SERIALIZED]: 'true',
303 },
304 })
305 }
306 })()
307​
308 request.signal.removeEventListener('abort', abort)
309​
310 return response
312​
313function isNotFoundResponse(error: any) {
314 const { headers, ...rest } = error
315​
316 return new Response(JSON.stringify(rest), {
317 status: 404,
318 headers: {
319 'Content-Type': 'application/json',
320 ...(headers || {}),
321 },
322 })