|
1 |
| -import type { TAnySchema } from '@sinclair/typebox' |
| 1 | +import type { TAnySchema, TRecord } from '@sinclair/typebox' |
2 | 2 |
|
3 | 3 | const Kind = Symbol.for('TypeBox.Kind')
|
4 | 4 | const OptionalKind = Symbol.for('TypeBox.Optional')
|
5 | 5 |
|
6 | 6 | const isSpecialProperty = (name: string) => /(\ |-|\t|\n)/.test(name)
|
7 | 7 |
|
8 |
| -const joinProperty = (v1: string, v2: string) => { |
| 8 | +const joinProperty = (v1: string, v2: string | number) => { |
| 9 | + if (typeof v2 === 'number') return `${v1}[${v2}]` |
| 10 | + |
9 | 11 | if (isSpecialProperty(v2)) return `${v1}["${v2}"]`
|
10 | 12 |
|
11 | 13 | return `${v1}.${v2}`
|
@@ -188,6 +190,34 @@ const joinStringArray = (p: string) =>
|
188 | 190 | '})()' +
|
189 | 191 | '}"'
|
190 | 192 |
|
| 193 | +const handleRecord = ( |
| 194 | + schema: TRecord, |
| 195 | + property: string, |
| 196 | + instruction: Instruction |
| 197 | +) => { |
| 198 | + const child = |
| 199 | + schema.patternProperties['^(.*)$'] ?? |
| 200 | + schema.patternProperties[Object.keys(schema.patternProperties)[0]] |
| 201 | + |
| 202 | + if (!child) return property |
| 203 | + |
| 204 | + const i = instruction.array |
| 205 | + instruction.array++ |
| 206 | + |
| 207 | + return ( |
| 208 | + `\${(()=>{` + |
| 209 | + `const ar${i}s=Object.keys(${property});` + |
| 210 | + `let ar${i}v='{';` + |
| 211 | + `for(let i=0;i<ar${i}s.length;i++){` + |
| 212 | + `const ar${i}p=${property}[ar${i}s[i]];` + |
| 213 | + `if(i!==0)ar${i}v+=',';` + |
| 214 | + `ar${i}v+=\`"\${ar${i}s[i]}":${accelerate(child, `ar${i}p`, instruction)}\`` + |
| 215 | + `}` + |
| 216 | + `return ar${i}v + '}'` + |
| 217 | + `})()}` |
| 218 | + ) |
| 219 | +} |
| 220 | + |
191 | 221 | const accelerate = (
|
192 | 222 | schema: TAnySchema,
|
193 | 223 | property: string,
|
@@ -276,6 +306,21 @@ const accelerate = (
|
276 | 306 | let hasOptional = false
|
277 | 307 | let op = `op${instruction.optional}`
|
278 | 308 |
|
| 309 | + if (schema[Kind as any] === 'Record') { |
| 310 | + v = handleRecord(schema as TRecord, property, instruction) |
| 311 | + |
| 312 | + break |
| 313 | + } |
| 314 | + |
| 315 | + if ( |
| 316 | + !Object.keys(schema.properties).length && |
| 317 | + schema.patternProperties |
| 318 | + ) { |
| 319 | + v = `$\{JSON.stringify(${property})}` |
| 320 | + |
| 321 | + break |
| 322 | + } |
| 323 | + |
279 | 324 | for (const key in schema.properties)
|
280 | 325 | if (OptionalKind in schema.properties[key]) {
|
281 | 326 | instruction.optional++
|
|
0 commit comments