(typeName: string, schema: JSONSchema7, ctx: GoCodegenCtx, variants?: GoPrimitiveUnionVariant[])
| 2553 | } |
| 2554 | |
| 2555 | function emitGoPrimitiveUnionInterface(typeName: string, schema: JSONSchema7, ctx: GoCodegenCtx, variants?: GoPrimitiveUnionVariant[]): boolean { |
| 2556 | if (ctx.generatedNames.has(typeName)) return true; |
| 2557 | variants ??= goPrimitiveUnionVariants(typeName, schema, ctx); |
| 2558 | if (!variants) return false; |
| 2559 | |
| 2560 | ctx.generatedNames.add(typeName); |
| 2561 | const unmarshalFuncName = goUnexportedFunctionName("unmarshal", typeName); |
| 2562 | const markerName = toGoUnexportedIdentifier(typeName); |
| 2563 | ctx.discriminatedUnions.set(typeName, { typeName, unmarshalFuncName }); |
| 2564 | |
| 2565 | const lines: string[] = []; |
| 2566 | if (schema.description) { |
| 2567 | pushGoCommentForContext(lines, schema.description, ctx); |
| 2568 | } |
| 2569 | if (isSchemaExperimental(schema)) { |
| 2570 | pushGoExperimentalTypeComment(lines, typeName, ctx); |
| 2571 | } |
| 2572 | if (isSchemaDeprecated(schema)) { |
| 2573 | pushGoCommentForContext(lines, `Deprecated: ${typeName} is deprecated and will be removed in a future version.`, ctx); |
| 2574 | } |
| 2575 | lines.push(`type ${typeName} interface {`); |
| 2576 | lines.push(`\t${markerName}()`); |
| 2577 | lines.push(`}`); |
| 2578 | |
| 2579 | for (const variant of [...variants].sort((left, right) => compareGoTypeNames(left.typeName, right.typeName))) { |
| 2580 | lines.push(``); |
| 2581 | lines.push(`type ${variant.typeName} ${variant.goType}`); |
| 2582 | lines.push(``); |
| 2583 | lines.push(`func (${variant.typeName}) ${markerName}() {}`); |
| 2584 | } |
| 2585 | |
| 2586 | const unmarshalLines: string[] = []; |
| 2587 | unmarshalLines.push(`func ${unmarshalFuncName}(data []byte) (${typeName}, error) {`); |
| 2588 | unmarshalLines.push(`\tif string(data) == "null" {`); |
| 2589 | unmarshalLines.push(`\t\treturn nil, nil`); |
| 2590 | unmarshalLines.push(`\t}`); |
| 2591 | for (const variant of variants) { |
| 2592 | unmarshalLines.push(`\t{`); |
| 2593 | unmarshalLines.push(`\t\tvar value ${variant.goType}`); |
| 2594 | unmarshalLines.push(`\t\tif err := json.Unmarshal(data, &value); err == nil {`); |
| 2595 | unmarshalLines.push(`\t\t\treturn ${variant.typeName}(value), nil`); |
| 2596 | unmarshalLines.push(`\t\t}`); |
| 2597 | unmarshalLines.push(`\t}`); |
| 2598 | } |
| 2599 | unmarshalLines.push(`\treturn nil, errors.New("data did not match any union variant for ${typeName}")`); |
| 2600 | unmarshalLines.push(`}`); |
| 2601 | pushGoEncodingBlock(unmarshalLines, ctx); |
| 2602 | |
| 2603 | ctx.structs.push(lines.join("\n")); |
| 2604 | return true; |
| 2605 | } |
| 2606 | |
| 2607 | function goSchemaJSONKind(schema: JSONSchema7, ctx: GoCodegenCtx): string | undefined { |
| 2608 | const resolved = resolveGoUnionMember(schema, ctx.definitions); |
no test coverage detected
searching dependent graphs…