Files
persionalBrand/apps/miniapp/utils/request.js
T

36 lines
1.3 KiB
JavaScript

const config = require("./config");
function withBrandContext(path, options) {
if (options.includeBrand === false || !path.startsWith("/public/")) return path;
const separator = path.includes("?") ? "&" : "?";
return path + separator + "brandSlug=" + encodeURIComponent(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("customerToken");
return request(path, {
...options,
header: { ...(options.header || {}), Authorization: "Bearer " + token },
});
}
module.exports = { request, customerRequest };