zksu
/
API
forked from yoone/API
1
0
Fork 0

feat(service): 添加buildURL方法规范URL路径拼接

新增buildURL私有方法用于规范URL各路径段的斜杠,避免因多/或少/导致请求失败
替换原有字符串拼接方式为buildURL调用,提升URL构建的可靠性
This commit is contained in:
tikkhun 2025-11-17 10:42:07 +08:00
parent 2d36370acf
commit dc070fadde
1 changed files with 41 additions and 5 deletions

View File

@ -11,6 +11,24 @@ export class WPService {
@Config('wpSite')
sites: WpSite[];
/**
* URL / /
* 使this.buildURL(wpApiUrl, '/wp-json', 'wc/v3/products', productId)
*/
private buildURL(base: string, ...parts: Array<string | number>): string {
// 去掉 base 末尾多余斜杠,但不影响协议中的 //
const baseSanitized = String(base).replace(/\/+$/g, '');
// 规范各段前后斜杠
const segments = parts
.filter((p) => p !== undefined && p !== null)
.map((p) => String(p))
.map((s) => s.replace(/^\/+|\/+$/g, ''))
.filter(Boolean);
const joined = [baseSanitized, ...segments].join('/');
// 折叠除协议外的多余斜杠,例如 https://example.com//a///b -> https://example.com/a/b
return joined.replace(/([^:])\/{2,}/g, '$1/');
}
/**
* WordPress
* @param wpApiUrl WordPress REST API
@ -31,7 +49,8 @@ export class WPService {
): Promise<T> {
try {
const { wpApiUrl, consumerKey, consumerSecret } = site;
const url = `${wpApiUrl}/wp-json${endpoint}`;
// 构建 URL规避多/或少/问题
const url = this.buildURL(wpApiUrl, '/wp-json', endpoint);
const auth = Buffer.from(`${consumerKey}:${consumerSecret}`).toString(
'base64'
);
@ -64,7 +83,8 @@ export class WPService {
while (hasMore) {
const config: AxiosRequestConfig = {
method: 'GET',
url: `${wpApiUrl}/wp-json${endpoint}`,
// 构建 URL规避多/或少/问题
url: this.buildURL(wpApiUrl, '/wp-json', endpoint),
headers: {
Authorization: `Basic ${auth}`,
},
@ -212,7 +232,8 @@ export class WPService {
);
const config: AxiosRequestConfig = {
method: 'PUT',
url: `${wpApiUrl}/wp-json${endpoint}`,
// 构建 URL规避多/或少/问题
url: this.buildURL(wpApiUrl, '/wp-json', endpoint),
headers: {
Authorization: `Basic ${auth}`,
},
@ -310,7 +331,14 @@ export class WPService {
);
const config: AxiosRequestConfig = {
method: 'POST',
url: `${wpApiUrl}/wp-json/wc-ast/v3/orders/${orderId}/shipment-trackings`,
// 构建 URL规避多/或少/问题
url: this.buildURL(
wpApiUrl,
'/wp-json',
'wc-ast/v3/orders',
orderId,
'shipment-trackings'
),
headers: {
Authorization: `Basic ${auth}`,
},
@ -333,7 +361,15 @@ export class WPService {
// 删除接口: DELETE /wp-json/wc-shipment-tracking/v3/orders/<order_id>/shipment-trackings/<tracking_id>
const config: AxiosRequestConfig = {
method: 'DELETE',
url: `${wpApiUrl}/wp-json/wc-ast/v3/orders/${orderId}/shipment-trackings/${trackingId}`,
// 构建 URL规避多/或少/问题
url: this.buildURL(
wpApiUrl,
'/wp-json',
'wc-ast/v3/orders',
orderId,
'shipment-trackings',
trackingId
),
headers: {
Authorization: `Basic ${auth}`,
},