egg_server/utils/pathTools.ts
zhaoyingbo 09e352a9c1
All checks were successful
Egg Server MIflow / build-image (push) Successful in 1m5s
feat: 抽象网络请求类 & 内容转为ctx向内传递
2024-08-16 09:12:11 +00:00

66 lines
2.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 创建一个路径检查工具,用于精确匹配和前缀匹配路径。
* @param {string} url - 要检查的基础 URL。
* @param {string} [prefix] - 可选的路径前缀。
* @returns {object} 包含路径检查方法的对象。
*/
export const makeCheckPathTool = (url: string, prefix?: string) => {
const { pathname } = new URL(url)
const makePath = (path: string) => `${prefix || ""}${path}`
return {
/**
* 检查路径是否与基础 URL 的路径精确匹配。
* @param {string} path - 要检查的路径。
* @returns {boolean} 如果路径精确匹配则返回 true否则返回 false。
*/
exactCheck: (path: string) => {
return pathname === makePath(path)
},
/**
* 检查路径是否以基础 URL 的路径为前缀。
* @param {string} path - 要检查的路径。
* @returns {boolean} 如果路径以基础 URL 的路径为前缀则返回 true否则返回 false。
*/
startsWithCheck: (path: string) => pathname.startsWith(makePath(path)),
/**
* 检查完整路径是否与基础 URL 的路径精确匹配。
* @param {string} path - 要检查的路径。
* @returns {boolean} 如果完整路径与基础 URL 的路径精确匹配则返回 true否则返回 false。
*/
fullCheck: (path: string) => pathname === path,
}
}
/**
* 裁剪路径字符串如果路径长度超过20个字符则只保留最后两级目录。
*
* @param {string} path - 要处理的路径字符串。
* @returns {string} - 裁剪后的路径字符串如果长度不超过20个字符则返回原路径。
*/
export const shortenPath = (path: string): string => {
if (path.length <= 20) {
return path
}
const parts = path.split("/")
if (parts.length <= 2) {
return path
}
return `.../${parts[parts.length - 2]}/${parts[parts.length - 1]}`
}
/**
* 安全地将对象转换为 JSON 字符串。
* 如果转换失败,则返回对象的字符串表示。
* @param {any} obj - 要转换的对象。
* @returns {string} - JSON 字符串或对象的字符串表示。
*/
export const safeJsonStringify = (obj: any) => {
try {
return JSON.stringify(obj)
} catch (e) {
return String(obj)
}
}