(
typeName: string,
discriminator: GoRequiredFieldDiscriminatorInfo,
ctx: GoCodegenCtx,
description?: string,
experimental = false
)
| 1984 | } |
| 1985 | |
| 1986 | function emitGoRequiredFieldDiscriminatedUnion( |
| 1987 | typeName: string, |
| 1988 | discriminator: GoRequiredFieldDiscriminatorInfo, |
| 1989 | ctx: GoCodegenCtx, |
| 1990 | description?: string, |
| 1991 | experimental = false |
| 1992 | ): void { |
| 1993 | if (ctx.generatedNames.has(typeName)) return; |
| 1994 | ctx.generatedNames.add(typeName); |
| 1995 | |
| 1996 | const unionVariants = [...discriminator.variants].sort((left, right) => compareGoTypeNames(left.typeName, right.typeName)); |
| 1997 | const unmarshalFuncName = goUnexportedFunctionName("unmarshal", typeName); |
| 1998 | const rawDataName = `Raw${typeName}${ctx.discriminatedUnionRawVariantSuffix ?? "Data"}`; |
| 1999 | const markerName = toGoUnexportedIdentifier(typeName); |
| 2000 | ctx.discriminatedUnions.set(typeName, { typeName, unmarshalFuncName }); |
| 2001 | |
| 2002 | const lines: string[] = []; |
| 2003 | if (description) { |
| 2004 | pushGoCommentForContext(lines, description, ctx); |
| 2005 | } |
| 2006 | if (experimental) { |
| 2007 | pushGoExperimentalTypeComment(lines, typeName, ctx); |
| 2008 | } |
| 2009 | lines.push(`type ${typeName} interface {`); |
| 2010 | lines.push(`\t${markerName}()`); |
| 2011 | lines.push(`}`); |
| 2012 | lines.push(``); |
| 2013 | |
| 2014 | for (const variant of unionVariants) { |
| 2015 | pushGoEncodingBlock(goVariantMatchFunctionLines(variant, unionVariants, "", ctx), ctx); |
| 2016 | } |
| 2017 | |
| 2018 | const unmarshalLines: string[] = []; |
| 2019 | unmarshalLines.push(`func ${unmarshalFuncName}(data []byte) (${typeName}, error) {`); |
| 2020 | unmarshalLines.push(`\tif string(data) == "null" {`); |
| 2021 | unmarshalLines.push(`\t\treturn nil, nil`); |
| 2022 | unmarshalLines.push(`\t}`); |
| 2023 | for (const variant of unionVariants) { |
| 2024 | unmarshalLines.push(`\tif ${goVariantMatchFuncName(variant.typeName)}(data) {`); |
| 2025 | unmarshalLines.push(`\t\tvar d ${variant.typeName}`); |
| 2026 | unmarshalLines.push(`\t\tif err := json.Unmarshal(data, &d); err != nil {`); |
| 2027 | unmarshalLines.push(`\t\t\treturn nil, err`); |
| 2028 | unmarshalLines.push(`\t\t}`); |
| 2029 | unmarshalLines.push(`\t\treturn &d, nil`); |
| 2030 | unmarshalLines.push(`\t}`); |
| 2031 | } |
| 2032 | unmarshalLines.push(`\treturn &${rawDataName}{Raw: data}, nil`); |
| 2033 | unmarshalLines.push(`}`); |
| 2034 | pushGoEncodingBlock(unmarshalLines, ctx); |
| 2035 | |
| 2036 | lines.push(`type ${rawDataName} struct {`); |
| 2037 | lines.push(`\tRaw json.RawMessage`); |
| 2038 | lines.push(`}`); |
| 2039 | lines.push(``); |
| 2040 | lines.push(`func (${rawDataName}) ${markerName}() {}`); |
| 2041 | pushGoEncodingBlock([ |
| 2042 | `func (r ${rawDataName}) MarshalJSON() ([]byte, error) {`, |
| 2043 | `\tif r.Raw != nil {`, |
no test coverage detected
searching dependent graphs…