返回 AiToEarn
url.util.ts
根目录 / project / aitoearn-backend / libs / common / src / utils / url.util.ts
1 import { z } from 'zod'
2
3 export function buildUrl(endpoint: string, objectPath: string) {
4 const normalizedPath = String(objectPath ?? '').trim()
5
6 if (normalizedPath && (normalizedPath.startsWith('http://') || normalizedPath.startsWith('https://'))) {
7 return normalizedPath
8 }
9
10 const trimmedEndpoint = endpoint.trim().replace(/\/+$/g, '')
11
12 const pathWithoutLeadingSlash = normalizedPath.replace(/^\/+/, '')
13
14 const encodedPath = pathWithoutLeadingSlash
15 ? pathWithoutLeadingSlash
16 .split('/')
17 .map(segment => encodeURIComponent(segment))
18 .join('/')
19 : ''
20
21 return encodedPath ? `${trimmedEndpoint}/${encodedPath}` : trimmedEndpoint
22 }
23
24 export function zodBuildUrl(getEndpoint: () => string) {
25 return z
26 .string()
27 .optional()
28 .transform((objectPath) => {
29 if (!objectPath) {
30 return objectPath
31 }
32 const endpoint = getEndpoint()
33 if (!endpoint) {
34 return objectPath
35 }
36 return buildUrl(endpoint, objectPath)
37 })
38 }
39
40 export function zodTrimHost(getEndpoint: () => string) {
41 return z
42 .string()
43 .transform((url) => {
44 if (!url) {
45 return url
46 }
47 const endpoint = getEndpoint()
48 if (!endpoint) {
49 return url
50 }
51 return url.replace(endpoint, '').replace(/^\/+/, '')
52 })
53 }
54
54 lines TYPESCRIPT