42 lines
1.5 KiB
JavaScript
42 lines
1.5 KiB
JavaScript
const config = require("./config");
|
|
|
|
function withBrandContext(path, options) {
|
|
const requiresBrandContext =
|
|
path.startsWith("/public/") || path.startsWith("/customer/session/wechat");
|
|
if (options.includeBrand === false || !requiresBrandContext) return path;
|
|
const separator = path.includes("?") ? "&" : "?";
|
|
return path + separator + "brandSlug=" + encodeURIComponent(config.brandSlug);
|
|
}
|
|
|
|
function customerTokenKey() {
|
|
return "customerToken:" + config.brandSlug;
|
|
}
|
|
|
|
function request(path, options = {}) {
|
|
return new Promise((resolve, reject) => {
|
|
const requestPath = withBrandContext(path, options);
|
|
wx.request({
|
|
url: config.apiBaseUrl + requestPath,
|
|
method: options.method || "GET",
|
|
header: { accept: "application/json", ...(options.header || {}) },
|
|
...(options.data === undefined ? {} : { data: options.data }),
|
|
success: (response) => {
|
|
if (response.statusCode >= 200 && response.statusCode < 300) return resolve(response.data);
|
|
const error = response.data?.error?.message || "请求失败";
|
|
reject(Object.assign(new Error(error), { statusCode: response.statusCode, response }));
|
|
},
|
|
fail: reject,
|
|
});
|
|
});
|
|
}
|
|
|
|
function customerRequest(path, options = {}) {
|
|
const token = wx.getStorageSync(customerTokenKey());
|
|
return request(path, {
|
|
...options,
|
|
header: { ...(options.header || {}), Authorization: "Bearer " + token },
|
|
});
|
|
}
|
|
|
|
module.exports = { request, customerRequest, customerTokenKey };
|