返回响应
编辑此页面在 SolidStart 中,可以从服务端函数返回一个 Response 对象。solid-router
知道如何通过它的 cache
和 action
API 处理某些响应。
对于 TypeScript,当使用 solid-routers
的 redirect
、reload
或 json
辅助函数返回响应时,它们不会影响服务端函数的返回值。
虽然我们建议根据函数类型来区别处理错误,但你始终可以返回或抛出响应。
示例
在下面的示例中,hello
函数将返回 Promise<{ hello: string }>
类型的值:
import { json } from "@solidjs/router";import { GET } from "@solidjs/start";
const hello = GET(async (name: string) => { "use server"; return json( { hello: new Promise<string>((r) => setTimeout(() => r(name), 1000)) }, { headers: { "cache-control": "max-age=60" } } );});
然而,在这个示例中,由于 redirect
和 reload
返回 never
作为它们的类型,getUser
只能返回 Promise<User>
类型的值:
export async function getUser() { "use server";
const session = await getSession(); const userId = session.data.userId; if (userId === undefined) return redirect("/login");
try { const user: User = await db.user.findUnique({ where: { id: userId } }); // throwing can awkward. if (!user) return redirect("/login"); return user; } catch { // do stuff throw redirect("/login"); }}