api-request.ts
TypeScript · 81 рядків
1import { buildMappedData, validateMapping } from './mapping.ts'
2
3function pathValue(object, path) {
4 return path.split('.').reduce(
5 (value, key) =>
6 value && typeof value === 'object' ? value[key] : undefined,
7 object
8 )
9}
10
11function runtimePath(expression) {
12 if (typeof expression !== 'string') return null
13 const match = expression.match(/^(data|task|event)\.(.+)$/)
14 return match
15 ? {
16 root: match[1],
17 path: match[2]
18 }
19 : null
20}
21
22function scopedValue(data, scopes, expression) {
23 const path = runtimePath(expression)
24 if (!path) return undefined
25 const source = path.root === 'data' ? data : scopes?.[path.root]
26 return pathValue(source, path.path)
27}
28
29export function validateApiRequest(config, schema, scopeSchemas: any = {}) {
30 const errors = []
31 const method = String(config?.method || 'GET').toUpperCase()
32 const url = String(config?.url || '').trim()
33
34 if (!['GET', 'POST'].includes(method)) {
35 errors.push('API method must be GET or POST')
36 }
37 if (!url) errors.push('API URL is required')
38
39 for (const match of url.matchAll(/\{\{\s*([^}]+?)\s*\}\}/g)) {
40 const expression = match[1]
41 const path = runtimePath(expression)
42 if (!path) {
43 errors.push(
44 `URL placeholder must use data.*, task.*, or event.*: ${expression}`
45 )
46 } else if (scopedValue(schema, scopeSchemas, expression) === undefined) {
47 errors.push(`Unknown URL field: ${expression}`)
48 }
49 }
50
51 if (method === 'POST') {
52 errors.push(
53 ...validateMapping(config?.requestMapping, schema, scopeSchemas).errors
54 .map(error => `POST mapping: ${error}`)
55 )
56 }
57 return {
58 valid: errors.length === 0,
59 errors
60 }
61}
62
63export function resolveApiUrl(template, data, scopes: any = {}) {
64 return template.replace(/\{\{\s*([^}]+?)\s*\}\}/g, (_, expression) => {
65 if (!runtimePath(expression)) {
66 throw new Error(`Invalid URL placeholder: ${expression}`)
67 }
68 const value = scopedValue(data, scopes, expression)
69 if (value === undefined) {
70 throw new Error(`URL value is unset: ${expression}`)
71 }
72 return encodeURIComponent(String(value))
73 })
74}
75
76export function buildRequestBody(mapping, data, scopes: any = {}) {
77 const validation = validateMapping(mapping, data, scopes)
78 if (!validation.valid) throw new Error(validation.errors[0])
79 return buildMappedData(mapping, data, scopes)
80}
81