getContext API
支持在后端函数中读取上下文信息。
import { getContext } from '@toolpad/studio/server';
描述
import { getContext } from '@toolpad/studio/server';
import { parseAuth } from '../../src/lib/auth';
export async function myBackendFunction() {
const ctx = getContext();
const user = await parseAuth(ctx.cookie.authentication);
return user?.id;
}
在后端函数中,您可以调用 getContext
来访问导致调用此后端函数的请求上下文。如果您在已认证的上下文中运行 Toolpad Studio,并且想要重用 Cookie 中可用的访问令牌,这将非常有用。
参数
无参数
返回值
一个 ServerContext
,其中包含有关调用后端函数时所处上下文的信息。
类型
ServerContext
描述调用后端函数时所处的特定上下文。
属性
名称 | 类型 | 描述 |
---|---|---|
cookies |
Record<string, string> |
一个字典,将 Cookie 名称映射到 Cookie 值。 |
setCookie |
(name: string, value: string) => void |
用于设置具有 value 的 Cookie name 。 |
session |
{ user: ServerContextSessionUser } | null |
获取当前的已认证会话数据。 |
ServerContextSessionUser
属性
名称 | 类型 | 描述 |
---|---|---|
name? |
string | null |
已登录用户名。 |
email? |
string | null |
已登录用户邮箱。 |
avatar? |
string | null |
已登录用户头像图片 URL。 |
roles |
string[] |
已登录用户在 Toolpad Studio 中的角色。 |