feat: 新增 Taro 模板双端运行与独立 Web 预览
This commit is contained in:
1 parent
f4061a24bd
commit
7e8fc01fba
48 files changed
+11576
-12
No files matched your search
@@ -0,0 +1,56 @@
|
||||
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;
|
||||
}
|
||||
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
|
||||
? `${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");
|
||||
if (data.publication?.status !== "published") throw new Error("品牌尚未发布");
|
||||
if (data.brand.visualTemplateKey !== TEMPLATE_KEY)
|
||||
throw new Error("该品牌使用其他模板,请选择匹配的模板预览地址");
|
||||
return data;
|
||||
}
|
||||
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);
|
||||
}
|
||||
Reference in new issue
Block a user