75 lines
2.9 KiB
TypeScript
75 lines
2.9 KiB
TypeScript
import Taro from "@tarojs/taro";
|
||
import type { RuntimeWorkspace } from "@personal-brand/types";
|
||
export function brandSlug() {
|
||
if (process.env.TARO_ENV === "h5") {
|
||
const search = new URLSearchParams(window.location.search);
|
||
return search.get("brand") || BRAND_SLUG;
|
||
}
|
||
return BRAND_SLUG;
|
||
}
|
||
function isEditorPreview() {
|
||
return (
|
||
process.env.TARO_ENV === "h5" &&
|
||
new URLSearchParams(window.location.search).get("editor") === "1"
|
||
);
|
||
}
|
||
export const tokenKey = () => `customerToken:${brandSlug()}`;
|
||
export function hasSession() {
|
||
return Boolean(Taro.getStorageSync<string>(tokenKey()));
|
||
}
|
||
export async function request<T>(
|
||
path: string,
|
||
options: { method?: "GET" | "POST"; data?: unknown; customer?: boolean } = {},
|
||
): Promise<T> {
|
||
const context = path.startsWith("/public/") || path.startsWith("/customer/session/wechat");
|
||
const query =
|
||
context && !(isEditorPreview() && path === "/public/workspace")
|
||
? `${path.includes("?") ? "&" : "?"}brandSlug=${encodeURIComponent(brandSlug())}`
|
||
: "";
|
||
const response = await Taro.request<T & { error?: { message?: string; requestId?: string } }>({
|
||
url: API_BASE_URL.replace(/\/$/, "") + path + query,
|
||
method: options.method || "GET",
|
||
data: options.data,
|
||
header: {
|
||
accept: "application/json",
|
||
...(options.customer
|
||
? { Authorization: `Bearer ${Taro.getStorageSync<string>(tokenKey()) || ""}` }
|
||
: {}),
|
||
},
|
||
});
|
||
if (response.statusCode < 200 || response.statusCode >= 300) {
|
||
if (options.customer && response.statusCode === 401) Taro.removeStorageSync(tokenKey());
|
||
throw new Error(response.data?.error?.message || `请求失败(${response.statusCode})`);
|
||
}
|
||
return response.data;
|
||
}
|
||
export async function loadWorkspace() {
|
||
const data = await request<RuntimeWorkspace>("/public/workspace");
|
||
const editorPreview = isEditorPreview();
|
||
if (!editorPreview && data.publication?.status !== "published") throw new Error("品牌尚未发布");
|
||
if (!editorPreview && data.brand.visualTemplateKey !== TEMPLATE_KEY)
|
||
throw new Error("该品牌使用其他模板,请选择匹配的模板预览地址");
|
||
return {
|
||
...data,
|
||
brand: data.brand ?? {},
|
||
templateData: data.templateData ?? {},
|
||
offerings: data.offerings ?? [],
|
||
inquiryForms: data.inquiryForms ?? [],
|
||
trustItems: data.trustItems ?? [],
|
||
trustPresentation: data.trustPresentation ?? {},
|
||
capabilities: data.capabilities ?? [],
|
||
theme: data.theme ?? { colors: {} },
|
||
};
|
||
}
|
||
export async function ensureSession() {
|
||
if (hasSession()) return;
|
||
if (process.env.TARO_ENV === "h5")
|
||
throw new Error("请在微信小程序中登录后提交;Web 预览可填写表单,尚未接入 Web 登录。");
|
||
const login = await Taro.login();
|
||
const session = await request<{ token: string }>("/customer/session/wechat", {
|
||
method: "POST",
|
||
data: { code: login.code },
|
||
});
|
||
Taro.setStorageSync(tokenKey(), session.token);
|
||
}
|