@azure-tools/typespec-go 0.16.0-dev.9 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/dist/src/codegen/core/cloud-config.js +1 -0
  3. package/dist/src/codegen/core/cloud-config.js.map +1 -1
  4. package/dist/src/codegen/core/errors.d.ts +1 -1
  5. package/dist/src/codegen/core/errors.d.ts.map +1 -1
  6. package/dist/src/codegen/core/example.d.ts.map +1 -1
  7. package/dist/src/codegen/core/example.js +179 -19
  8. package/dist/src/codegen/core/example.js.map +1 -1
  9. package/dist/src/codegen/core/gomod.js +2 -1
  10. package/dist/src/codegen/core/gomod.js.map +1 -1
  11. package/dist/src/codegen/core/helpers.d.ts +16 -4
  12. package/dist/src/codegen/core/helpers.d.ts.map +1 -1
  13. package/dist/src/codegen/core/helpers.js +163 -23
  14. package/dist/src/codegen/core/helpers.js.map +1 -1
  15. package/dist/src/codegen/core/index.d.ts +17 -0
  16. package/dist/src/codegen/core/index.d.ts.map +1 -0
  17. package/dist/src/codegen/core/index.js +21 -0
  18. package/dist/src/codegen/core/index.js.map +1 -0
  19. package/dist/src/codegen/core/interfaces.js +1 -0
  20. package/dist/src/codegen/core/interfaces.js.map +1 -1
  21. package/dist/src/codegen/core/license.js +1 -0
  22. package/dist/src/codegen/core/license.js.map +1 -1
  23. package/dist/src/codegen/core/metadata.js +1 -0
  24. package/dist/src/codegen/core/metadata.js.map +1 -1
  25. package/dist/src/codegen/core/models.d.ts.map +1 -1
  26. package/dist/src/codegen/core/models.js +62 -14
  27. package/dist/src/codegen/core/models.js.map +1 -1
  28. package/dist/src/codegen/core/operations.d.ts +0 -1
  29. package/dist/src/codegen/core/operations.d.ts.map +1 -1
  30. package/dist/src/codegen/core/operations.js +84 -1172
  31. package/dist/src/codegen/core/operations.js.map +1 -1
  32. package/dist/src/codegen/core/request-handler.d.ts +14 -0
  33. package/dist/src/codegen/core/request-handler.d.ts.map +1 -0
  34. package/dist/src/codegen/core/request-handler.js +912 -0
  35. package/dist/src/codegen/core/request-handler.js.map +1 -0
  36. package/dist/src/codegen/core/response-handler.d.ts +12 -0
  37. package/dist/src/codegen/core/response-handler.d.ts.map +1 -0
  38. package/dist/src/codegen/core/response-handler.js +288 -0
  39. package/dist/src/codegen/core/response-handler.js.map +1 -0
  40. package/dist/src/codegen/core/version.js +1 -0
  41. package/dist/src/codegen/core/version.js.map +1 -1
  42. package/dist/src/codegen/core/xml-additional-props.js +1 -0
  43. package/dist/src/codegen/core/xml-additional-props.js.map +1 -1
  44. package/dist/src/codegen/emitter.d.ts.map +1 -1
  45. package/dist/src/codegen/emitter.js +21 -37
  46. package/dist/src/codegen/emitter.js.map +1 -1
  47. package/dist/src/codegen/fake/index.d.ts +3 -0
  48. package/dist/src/codegen/fake/index.d.ts.map +1 -0
  49. package/dist/src/codegen/fake/index.js +7 -0
  50. package/dist/src/codegen/fake/index.js.map +1 -0
  51. package/dist/src/codegen/fake/internal.js +1 -0
  52. package/dist/src/codegen/fake/internal.js.map +1 -1
  53. package/dist/src/codegen/fake/servers.d.ts.map +1 -1
  54. package/dist/src/codegen/fake/servers.js +17 -16
  55. package/dist/src/codegen/fake/servers.js.map +1 -1
  56. package/dist/src/codemodel/client.d.ts +2 -0
  57. package/dist/src/codemodel/client.d.ts.map +1 -1
  58. package/dist/src/codemodel/client.js +7 -0
  59. package/dist/src/codemodel/client.js.map +1 -1
  60. package/dist/src/codemodel/code-model.js +2 -0
  61. package/dist/src/codemodel/code-model.js.map +1 -1
  62. package/dist/src/codemodel/docs.d.ts +9 -0
  63. package/dist/src/codemodel/docs.d.ts.map +1 -0
  64. package/dist/src/codemodel/docs.js +40 -0
  65. package/dist/src/codemodel/docs.js.map +1 -0
  66. package/dist/src/codemodel/examples.js +4 -0
  67. package/dist/src/codemodel/examples.js.map +1 -1
  68. package/dist/src/codemodel/index.d.ts +1 -0
  69. package/dist/src/codemodel/index.d.ts.map +1 -1
  70. package/dist/src/codemodel/index.js +1 -0
  71. package/dist/src/codemodel/index.js.map +1 -1
  72. package/dist/src/codemodel/method.js +2 -0
  73. package/dist/src/codemodel/method.js.map +1 -1
  74. package/dist/src/codemodel/module.js +3 -0
  75. package/dist/src/codemodel/module.js.map +1 -1
  76. package/dist/src/codemodel/param.js +1 -0
  77. package/dist/src/codemodel/param.js.map +1 -1
  78. package/dist/src/codemodel/result.js +3 -0
  79. package/dist/src/codemodel/result.js.map +1 -1
  80. package/dist/src/codemodel/type.d.ts +7 -2
  81. package/dist/src/codemodel/type.d.ts.map +1 -1
  82. package/dist/src/codemodel/type.js +3 -0
  83. package/dist/src/codemodel/type.js.map +1 -1
  84. package/dist/src/emitter.d.ts +2 -2
  85. package/dist/src/emitter.d.ts.map +1 -1
  86. package/dist/src/emitter.js +33 -3
  87. package/dist/src/emitter.js.map +1 -1
  88. package/dist/src/lib.js.map +1 -1
  89. package/dist/src/tcgcadapter/adapter.d.ts +1 -1
  90. package/dist/src/tcgcadapter/adapter.d.ts.map +1 -1
  91. package/dist/src/tcgcadapter/adapter.js +6 -1
  92. package/dist/src/tcgcadapter/adapter.js.map +1 -1
  93. package/dist/src/tcgcadapter/clients.d.ts +8 -0
  94. package/dist/src/tcgcadapter/clients.d.ts.map +1 -1
  95. package/dist/src/tcgcadapter/clients.js +46 -7
  96. package/dist/src/tcgcadapter/clients.js.map +1 -1
  97. package/dist/src/tcgcadapter/errors.d.ts +1 -1
  98. package/dist/src/tcgcadapter/errors.d.ts.map +1 -1
  99. package/dist/src/tcgcadapter/helpers.d.ts +5 -3
  100. package/dist/src/tcgcadapter/helpers.d.ts.map +1 -1
  101. package/dist/src/tcgcadapter/helpers.js +19 -4
  102. package/dist/src/tcgcadapter/helpers.js.map +1 -1
  103. package/dist/src/tcgcadapter/metadata.js +1 -0
  104. package/dist/src/tcgcadapter/metadata.js.map +1 -1
  105. package/dist/src/tcgcadapter/types.d.ts.map +1 -1
  106. package/dist/src/tcgcadapter/types.js +16 -8
  107. package/dist/src/tcgcadapter/types.js.map +1 -1
  108. package/package.json +34 -34
@@ -7,6 +7,8 @@ import * as naming from "../../naming/naming.js";
7
7
  import { CodegenError } from "./errors.js";
8
8
  import * as helpers from "./helpers.js";
9
9
  import { ImportManager } from "./imports.js";
10
+ import { createRequestHandler } from "./request-handler.js";
11
+ import { createResponseHandler } from "./response-handler.js";
10
12
  // represents the generated content for an operation group
11
13
  export class OperationGroupContent {
12
14
  name;
@@ -160,10 +162,11 @@ export function generateOperations(pkg, target, options) {
160
162
  opText += generateLROBeginMethod(method, options, imports, indent);
161
163
  }
162
164
  opText += generateOperation(method, options, imports, indent);
163
- opText += createProtocolRequest(azureARM, method, imports, indent);
164
- if (method.kind !== "lroMethod") {
165
- // LRO responses are handled elsewhere, with the exception of pageable LROs
166
- opText += createProtocolResponse(method, imports, indent);
165
+ opText += createRequestHandler(azureARM, method, imports, indent);
166
+ if (needsResponseHandler(method) && method.kind !== "lroMethod") {
167
+ // we don't emit the response handler for vanilla LROs as the Poller[T]
168
+ // handles that. we do need it for pageable LROs though.
169
+ opText += createResponseHandler(method, imports, indent);
167
170
  }
168
171
  if (go.isPageableMethod(method) &&
169
172
  method.strategy?.kind === "nextLink" &&
@@ -174,7 +177,7 @@ export function generateOperations(pkg, target, options) {
174
177
  }
175
178
  }
176
179
  for (const method of nextPageMethods) {
177
- opText += createProtocolRequest(azureARM, method, imports, indent);
180
+ opText += createRequestHandler(azureARM, method, imports, indent);
178
181
  }
179
182
  // stitch it all together
180
183
  let text = helpers.contentPreamble(pkg);
@@ -434,136 +437,23 @@ function generateConstructors(client, type, imports, indent) {
434
437
  }
435
438
  return ctorText;
436
439
  }
437
- // use this to generate the code that will help process values returned in response headers
438
- function formatHeaderResponseValue(method, headerResp, respObj, zeroResp, imports, indent) {
439
- // dictionaries are handled slightly different so we do that first
440
- if (headerResp.kind === "headerMapResponse") {
441
- imports.add("github.com/Azure/azure-sdk-for-go/sdk/azcore/to");
442
- imports.add("strings");
443
- const headerPrefix = headerResp.headerName;
444
- let text = `${indent.get()}for hh := range resp.Header {\n`;
445
- text += `${indent.push().get()}if len(hh) > len("${headerPrefix}") && strings.EqualFold(hh[:len("${headerPrefix}")], "${headerPrefix}") {\n`;
446
- text += `${indent.push().get()}if ${respObj}.${headerResp.fieldName} == nil {\n`;
447
- text += `${indent.push().get()}${respObj}.${headerResp.fieldName} = map[string]*string{}\n`;
448
- text += `${indent.pop().get()}}\n`;
449
- text += `${indent.get()}${respObj}.${headerResp.fieldName}[hh[len("${headerPrefix}"):]] = to.Ptr(resp.Header.Get(hh))\n`;
450
- text += `${indent.pop().get()}}\n`;
451
- text += `${indent.pop().get()}}\n`;
452
- return text;
453
- }
454
- let text = `${indent.get()}if val := resp.Header.Get("${headerResp.headerName}"); val != "" {\n`;
455
- indent.push();
456
- let name = naming.uncapitalize(headerResp.fieldName);
457
- let byRef = "&";
458
- switch (headerResp.type.kind) {
459
- case "constant":
460
- case "etag":
461
- text += `${indent.get()}${respObj}.${headerResp.fieldName} = (*${go.getTypeDeclaration(headerResp.type, method.receiver.type.pkg)})(&val)\n`;
462
- indent.pop();
463
- text += `${indent.get()}}\n`;
464
- return text;
465
- case "encodedBytes":
466
- // a base-64 encoded value in string format
467
- imports.add("encoding/base64");
468
- text += `${indent.get()}${name}, err := base64.${helpers.formatBytesEncoding(headerResp.type.encoding)}Encoding.DecodeString(val)\n`;
469
- byRef = "";
470
- break;
471
- case "literal":
472
- text += `${indent.get()}${respObj}.${headerResp.fieldName} = &val\n`;
473
- indent.pop();
474
- text += `${indent.get()}}\n`;
475
- return text;
476
- case "scalar":
477
- text += emitScalarParsing(headerResp.type, "val", name, imports, indent);
478
- break;
479
- case "string":
480
- text += `${indent.get()}${respObj}.${headerResp.fieldName} = &val\n`;
481
- text += `${indent.pop().get()}}\n`;
482
- return text;
483
- case "time":
484
- imports.add("time");
485
- switch (headerResp.type.format) {
486
- case "RFC1123":
487
- case "RFC3339":
488
- case "RFC7231":
489
- text += `${indent.get()}${name}, err := time.Parse(${headerResp.type.format === "RFC3339" ? helpers.RFC3339Format : helpers.RFC1123Format}, val)\n`;
490
- break;
491
- case "PlainDate":
492
- text += `${indent.get()}${name}, err := time.Parse(${helpers.plainDateFormat}, val)\n`;
493
- break;
494
- case "PlainTime":
495
- text += `${indent.get()}${name}, err := time.Parse(${helpers.plainTimeFormat}, val)\n`;
496
- break;
497
- case "Unix":
498
- imports.add("strconv");
499
- imports.add("github.com/Azure/azure-sdk-for-go/sdk/azcore/to");
500
- text += `${indent.get()}sec, err := strconv.ParseInt(val, 10, 64)\n`;
501
- name = "to.Ptr(time.Unix(sec, 0))";
502
- byRef = "";
503
- break;
504
- default:
505
- headerResp.type.format;
506
- }
507
- }
508
- // NOTE: only cases that required parsing will fall through to here
509
- text += `${indent.get()}if err != nil {\n`;
510
- text += `${indent.push().get()}return ${zeroResp}, err\n`;
511
- text += `${indent.pop().get()}}\n`;
512
- text += `${indent.get()}${respObj}.${headerResp.fieldName} = ${byRef}${name}\n`;
513
- text += `${indent.pop().get()}}\n`;
514
- return text;
515
- }
516
- /**
517
- * emits the code for parsing scalar types from a string.
518
- * note that the parsing error result is placed into a
519
- * local var named "err".
520
- *
521
- * @param scalar the type of scalar to parse
522
- * @param src the source var that contains the scalar in string format
523
- * @param dst the destination var that contains the result
524
- * @param imports the import manager currently in scope
525
- * @param indent the indentation helper currently in scope
526
- * @returns the scalar parsing code
527
- */
528
- function emitScalarParsing(scalar, src, dst, imports, indent) {
529
- imports.add("strconv");
530
- switch (scalar.type) {
531
- case "bool":
532
- return `${indent.get()}${dst}, err := strconv.ParseBool(${src})\n`;
533
- case "float32":
534
- return (`${indent.get()}${dst}32, err := strconv.ParseFloat(${src}, 32)\n` +
535
- `${indent.get()}${dst} := float32(${dst}32)\n`);
536
- case "float64":
537
- return `${indent.get()}${dst}, err := strconv.ParseFloat(${src}, 64)\n`;
538
- case "int32":
539
- return (`${indent.get()}${dst}32, err := strconv.ParseInt(${src}, 10, 32)\n` +
540
- `${indent.get()}${dst} := int32(${dst}32)\n`);
541
- case "int64":
542
- return `${indent.get()}${dst}, err := strconv.ParseInt(${src}, 10, 64)\n`;
543
- default:
544
- throw new CodegenError("InternalError", `unhandled scalar type ${scalar.type}`);
545
- }
546
- }
547
440
  /**
548
441
  * returns the zero value for the specified method.
549
442
  * note that the zero value will be different depending
550
443
  * on which API for the method is being called.
551
444
  *
552
445
  * @param method the method to determine the zero value
553
- * @param apiType the method's API that's being invoked
554
- * lro - the exported LRO API
555
- * op - the operation method. for sync methods this is the exported API. for LROs it's the internal method called by Begin*
556
- * handler - the internal response handler method
557
446
  * @returns the zero value
558
447
  */
559
- function getZeroReturnValue(method, apiType) {
448
+ function getZeroReturnValue(method, forFetcher) {
449
+ // NOTE: we need more context when attempting to determine the zero value for pageable LROs:
450
+ // - in the fetcher, return the response envelope type
451
+ // - outside the fetcher return nil
560
452
  let returnType = `${method.returns.name}{}`;
561
- if (go.isLROMethod(method)) {
562
- if (apiType === "lro" || apiType === "op") {
563
- // the api returns a *Poller[T]
564
- // the operation returns an *http.Response
565
- returnType = "nil";
566
- }
453
+ if (go.isLROMethod(method) && !forFetcher) {
454
+ // the api returns a *Poller[T]
455
+ // the operation returns an *http.Response
456
+ returnType = "nil";
567
457
  }
568
458
  return returnType;
569
459
  }
@@ -600,7 +490,9 @@ function generateNilChecks(segments, varName = "page", omitLastSegment = false)
600
490
  */
601
491
  function emitPagerDefinition(method, options, imports, indent) {
602
492
  imports.add("context");
493
+ // BEGIN runtime.NewPager
603
494
  let text = `runtime.NewPager(runtime.PagingHandler[${method.returns.name}]{\n`;
495
+ // BEGIN More func
604
496
  text += `${indent.push().get()}More: func(page ${method.returns.name}) bool {\n`;
605
497
  indent.push();
606
498
  if (method.strategy) {
@@ -636,22 +528,16 @@ function emitPagerDefinition(method, options, imports, indent) {
636
528
  // there is no advancer for single-page pagers
637
529
  text += `${indent.get()}return false\n`;
638
530
  }
639
- text += `${indent.pop().get()}},\n`; // end More func
531
+ text += `${indent.pop().get()}},\n`;
532
+ // END More func
533
+ // BEGIN Fetcher func
640
534
  text += `${indent.get()}Fetcher: func(ctx context.Context, page *${method.returns.name}) (${method.returns.name}, error) {\n`;
641
535
  indent.push();
642
- const reqParams = helpers.getCreateRequestParameters(method);
643
536
  if (options.generateFakes) {
644
- text += `${indent.get()}ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "${method.receiver.type.name}.${fixUpMethodName(method)}")\n`;
537
+ text += `${indent.get()}ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "${method.receiver.type.name}.${helpers.fixUpMethodName(method)}")\n`;
645
538
  }
646
- /** emits code to check the HTTP status code and conditionally call the response handler */
647
- const emitStatusCodeCheckAndResponse = function (respVarName, indent) {
648
- let content = `${indent.get()}${helpers.buildIfBlock(indent, {
649
- condition: `!runtime.HasStatusCode(${respVarName}, http.StatusOK)`,
650
- body: (indent) => `${indent.get()}return ${getZeroReturnValue(method, "op")}, runtime.NewResponseError(${respVarName})\n`,
651
- })}\n`;
652
- content += `${indent.get()}return client.${method.naming.responseMethod}(${respVarName})\n`;
653
- return content;
654
- };
539
+ let nextLinkParam;
540
+ let optionsParam;
655
541
  if (method.strategy) {
656
542
  switch (method.strategy.kind) {
657
543
  case "continuationToken": {
@@ -681,110 +567,37 @@ function emitPagerDefinition(method, options, imports, indent) {
681
567
  condition: `page != nil${nestedNilChecks}`,
682
568
  body: (indent) => `${indent.get()}${optionsCopy}.${ms.requestToken.name} = page.${respToken}\n`,
683
569
  })}\n`;
684
- text += callCreateRequestWithErrCheck(method, "req", indent, `&${optionsCopy}`);
685
- text += callPipelineDoWithErrCheck(method, "req", "resp", indent);
686
- text += emitStatusCodeCheckAndResponse("resp", indent);
570
+ optionsParam = `&${optionsCopy}`;
687
571
  break;
688
572
  }
689
573
  case "nextLink": {
690
574
  const nextLinkPath = helpers.buildNextLinkPath(method.strategy);
691
- let nextLinkVar;
692
575
  if (method.kind === "pageableMethod") {
693
576
  text += `${indent.get()}nextLink := ""\n`;
694
- nextLinkVar = "nextLink";
577
+ nextLinkParam = "nextLink";
695
578
  text += `${indent.get()}if page != nil {\n`;
696
579
  text += `${indent.push().get()}nextLink = *page.${nextLinkPath}\n`;
697
580
  text += `${indent.pop().get()}}\n`;
698
581
  }
699
582
  else {
700
- nextLinkVar = `*page.${nextLinkPath}`;
583
+ nextLinkParam = `*page.${nextLinkPath}`;
701
584
  }
702
- text += `${indent.get()}resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), ${nextLinkVar}, func(ctx context.Context) (*policy.Request, error) {\n`;
703
- text += `${indent.push().get()}return client.${method.naming.requestMethod}(${reqParams})\n`;
704
- text += `${indent.pop().get()}}, `;
705
- // nextPageMethod might be absent in some cases, see https://github.com/Azure/autorest/issues/4393
706
- if (method.strategy.method) {
707
- const nextOpParams = helpers
708
- .getCreateRequestParametersSig(method.strategy.method)
709
- .split(",");
710
- // keep the parameter names from the name/type tuples and find nextLink param
711
- for (let i = 0; i < nextOpParams.length; ++i) {
712
- const paramName = nextOpParams[i].trim().split(" ")[0];
713
- const paramType = nextOpParams[i].trim().split(" ")[1];
714
- if (paramName.startsWith("next") && paramType === "string") {
715
- nextOpParams[i] = "encodedNextLink";
716
- }
717
- else {
718
- nextOpParams[i] = paramName;
719
- }
720
- }
721
- // add a definition for the nextReq func that uses the nextLinkOperation
722
- indent.push();
723
- text += `&runtime.FetcherForNextLinkOptions{\n`;
724
- text += `${indent.get()}NextReq: func(ctx context.Context, encodedNextLink string) (*policy.Request, error) {\n`;
725
- text += `${indent.push().get()}return client.${method.strategy.method.name}(${nextOpParams.join(", ")})\n`;
726
- text += `${indent.pop().get()}},\n`;
727
- text += `${indent.pop().get()}})\n`;
728
- }
729
- else if (method.nextLinkVerb !== "get") {
730
- text += `&runtime.FetcherForNextLinkOptions{\n`;
731
- text += `${indent.push().get()}HTTPVerb: http.Method${naming.capitalize(method.nextLinkVerb)},\n`;
732
- text += `${indent.pop().get()}})\n`;
733
- }
734
- else {
735
- text += "nil)\n";
736
- }
737
- text += `${indent.get()}if err != nil {\n`;
738
- text += `${indent.push().get()}return ${method.returns.name}{}, err\n`;
739
- text += `${indent.pop().get()}}\n`;
740
- text += `${indent.get()}return client.${method.naming.responseMethod}(resp)\n`;
741
585
  }
742
586
  }
743
587
  }
744
- else {
745
- // this is the singular page case, no fetcher helper required
746
- text += callCreateRequestWithErrCheck(method, "req", indent);
747
- text += callPipelineDoWithErrCheck(method, "req", "resp", indent);
748
- text += emitStatusCodeCheckAndResponse("resp", indent);
749
- }
750
- text += `${indent.pop().get()}},\n`; // end Fetcher func
588
+ const reqParams = helpers.getCreateRequestParameters(method, nextLinkParam, optionsParam);
589
+ text += `${indent.get()}req, err := client.${method.naming.requestMethod}(${reqParams})\n`;
590
+ text += `${indent.get()}${helpers.buildErrCheck(indent, "err", getZeroReturnValue(method, true))}\n`;
591
+ text += `${indent.get()}resp, err := client.internal.Pipeline().Do(req)\n`;
592
+ text += `${indent.get()}${helpers.buildErrCheck(indent, "err", getZeroReturnValue(method, true))}\n`;
593
+ text += `${indent.get()}return client.${method.naming.responseMethod}(resp, ${helpers.formatStatusCodes(method.httpStatusCodes)})\n`;
594
+ text += `${indent.pop().get()}},\n`;
595
+ // END Fetcher func
751
596
  if (options.injectSpans) {
752
597
  text += `${indent.get()}Tracer: client.internal.Tracer(),\n`;
753
598
  }
754
- text += `${indent.pop().get()}})\n`; // end runtime.NewPager
755
- return text;
756
- }
757
- /**
758
- * emits the call to the *CreateRequest method for an SDK method.
759
- * if the call returns an error, the error is propagated to the caller.
760
- *
761
- * @param method the method to call its *CreateRequest method
762
- * @param reqVarName the var name of the resultant *policy.Request
763
- * @param indent the indentation helper currently in scope
764
- * @param optionsParam optional custom param name for the method options param
765
- * @returns the call to *CreateRequest with an error check
766
- */
767
- function callCreateRequestWithErrCheck(method, reqVarName, indent, optionsParam) {
768
- const reqParams = helpers.getCreateRequestParameters(method, optionsParam);
769
- let text = `${indent.get()}${reqVarName}, err := client.${method.naming.requestMethod}(${reqParams})\n`;
770
- const zeroResp = getZeroReturnValue(method, "op");
771
- text += `${indent.get()}${helpers.buildErrCheck(indent, "err", zeroResp)}\n`;
772
- return text;
773
- }
774
- /**
775
- * emits the call to the pipeline's Do() method on the internal client.
776
- * if the call returns an error, the error is propagated to the caller.
777
- *
778
- * @param method the method that's making the call
779
- * @param reqVarName the var name of the *policy.Request
780
- * @param respVarName the var name of the *http.Response
781
- * @param indent the indentation helper currently in scope
782
- * @returns the call to Do() with an error check
783
- */
784
- function callPipelineDoWithErrCheck(method, reqVarName, respVarName, indent) {
785
- let text = `${indent.get()}${respVarName}, err := client.internal.Pipeline().Do(${reqVarName})\n`;
786
- const zeroResp = getZeroReturnValue(method, "op");
787
- text += `${indent.get()}${helpers.buildErrCheck(indent, "err", zeroResp)}\n`;
599
+ text += `${indent.pop().get()}})\n`;
600
+ // END runtime.NewPager
788
601
  return text;
789
602
  }
790
603
  function genRespErrorDoc(method) {
@@ -795,21 +608,12 @@ function genRespErrorDoc(method) {
795
608
  }
796
609
  return "";
797
610
  }
798
- /**
799
- * returns the receiver definition for a client
800
- *
801
- * @param receiver the receiver for which to emit the definition
802
- * @returns the receiver definition
803
- */
804
- function getClientReceiverDefinition(receiver) {
805
- return `(${receiver.name} ${receiver.byValue ? "" : "*"}${receiver.type.name})`;
806
- }
807
611
  function generateOperation(method, options, imports, indent) {
808
612
  const params = getAPIParametersSig(method, imports);
809
613
  const returns = generateReturnsInfo(method, "op");
810
614
  let methodName = method.name;
811
615
  if (method.kind === "pageableMethod") {
812
- methodName = fixUpMethodName(method);
616
+ methodName = helpers.fixUpMethodName(method);
813
617
  }
814
618
  let text = "";
815
619
  const respErrDoc = genRespErrorDoc(method);
@@ -831,7 +635,7 @@ function generateOperation(method, options, imports, indent) {
831
635
  text += helpers.formatCommentAsBulletItem(param.name, param.docs);
832
636
  }
833
637
  }
834
- text += `func ${getClientReceiverDefinition(method.receiver)} ${methodName}(${params}) (${returns.join(", ")}) {\n`;
638
+ text += `func ${helpers.getClientReceiverDefinition(method.receiver)} ${methodName}(${params}) (${returns.join(", ")}) {\n`;
835
639
  if (method.kind === "pageableMethod") {
836
640
  text += `${indent.get()}return `;
837
641
  text += emitPagerDefinition(method, options, imports, indent);
@@ -839,7 +643,7 @@ function generateOperation(method, options, imports, indent) {
839
643
  return text;
840
644
  }
841
645
  text += `${indent.get()}var err error\n`;
842
- let operationName = `"${method.receiver.type.name}.${fixUpMethodName(method)}"`;
646
+ let operationName = `"${method.receiver.type.name}.${helpers.fixUpMethodName(method)}"`;
843
647
  if (options.generateFakes && options.injectSpans) {
844
648
  text += `${indent.get()}const operationName = ${operationName}\n`;
845
649
  operationName = "operationName";
@@ -851,921 +655,62 @@ function generateOperation(method, options, imports, indent) {
851
655
  text += `${indent.get()}ctx, endSpan := runtime.StartSpan(ctx, ${operationName}, client.internal.Tracer(), nil)\n`;
852
656
  text += `${indent.get()}defer func() { endSpan(err) }()\n`;
853
657
  }
854
- const zeroResp = getZeroReturnValue(method, "op");
855
- text += callCreateRequestWithErrCheck(method, "req", indent);
856
- text += callPipelineDoWithErrCheck(method, "req", "httpResp", indent);
857
- text += `${indent.get()}if !runtime.HasStatusCode(httpResp, ${helpers.formatStatusCodes(method.httpStatusCodes)}) {\n`;
858
- indent.push();
859
- text += `${indent.get()}err = runtime.NewResponseError(httpResp)\n`;
860
- text += `${indent.get()}return ${zeroResp}, err\n`;
861
- text += `${indent.pop().get()}}\n`;
862
- // HAB with headers response is handled in protocol responder
863
- if (method.returns.result?.kind === "headAsBooleanResult" &&
864
- method.returns.headers.length === 0) {
865
- text += `${indent.get()}return ${method.returns.name}{${method.returns.result.fieldName}: httpResp.StatusCode >= 200 && httpResp.StatusCode < 300}, nil\n`;
658
+ const reqParams = helpers.getCreateRequestParameters(method, method.kind === "lroPageableMethod" ? `""` : undefined);
659
+ text += `${indent.get()}req, err := client.${method.naming.requestMethod}(${reqParams})\n`;
660
+ text += `${indent.get()}${helpers.buildErrCheck(indent, "err", getZeroReturnValue(method, false))}\n`;
661
+ text += `${indent.get()}httpResp, err := client.internal.Pipeline().Do(req)\n`;
662
+ text += `${indent.get()}${helpers.buildErrCheck(indent, "err", getZeroReturnValue(method, false))}\n`;
663
+ // NOTE: for an LRO's op method we never invoke the response handler.
664
+ // for vanilla LRO's we don't emit one, only for pageable LROs and in
665
+ // that case the response handler is invoked by the fetcher.
666
+ if (needsResponseHandler(method) && !go.isLROMethod(method)) {
667
+ // methods that return a modeled type, headers, or both call the method's response handler
668
+ text += `${indent.get()}return client.${method.naming.responseMethod}(httpResp, ${helpers.formatStatusCodes(method.httpStatusCodes)})\n`;
866
669
  }
867
670
  else {
671
+ // no response handler so we emit the status code check here
672
+ const zeroResp = getZeroReturnValue(method, false);
673
+ text += `${indent.get()}${helpers.buildIfBlock(indent, {
674
+ condition: `!runtime.HasStatusCode(httpResp, ${helpers.formatStatusCodes(method.httpStatusCodes)})`,
675
+ body: (indent) => `${indent.get()}return ${zeroResp}, runtime.NewResponseError(httpResp)\n`,
676
+ })}\n`;
868
677
  if (go.isLROMethod(method)) {
869
678
  text += `${indent.get()}return httpResp, nil\n`;
870
679
  }
871
- else if (needsResponseHandler(method)) {
872
- // also cheating here as at present the only param to the responder is an http.Response
873
- text += `${indent.get()}resp, err := client.${method.naming.responseMethod}(httpResp)\n`;
874
- text += `${indent.get()}return resp, err\n`;
875
- }
876
- else if (method.returns.result?.kind === "binaryResult") {
877
- text += `${indent.get()}return ${method.returns.name}{${method.returns.result.fieldName}: httpResp.Body}, nil\n`;
878
- }
879
- else {
880
- text += `${indent.get()}return ${method.returns.name}{}, nil\n`;
881
- }
882
- }
883
- text += "}\n\n";
884
- return text;
885
- }
886
- /**
887
- * emits Go code to set ContentType on a MultipartContent variable if it has a fixed content type.
888
- * handles both direct MultipartContent and slices of MultipartContent.
889
- * returns the empty string if there's nothing to set.
890
- *
891
- * @param paramName the name of the multipart param
892
- * @param wireType the underlying type of the multipart param
893
- * @param indent the indentation helper currently in scope
894
- * @returns setter code or the empty string
895
- */
896
- function emitMultipartContentTypeSetter(paramName, wireType, indent) {
897
- let text = "";
898
- const unwrapped = helpers.recursiveUnwrapMapSlice(wireType);
899
- if (unwrapped.kind !== "multipartContent" || !unwrapped.contentType) {
900
- return text;
901
- }
902
- switch (wireType.kind) {
903
- case "multipartContent":
904
- text += `${indent.get()}${paramName}.ContentType = ${unwrapped.contentType.literal}\n`;
905
- break;
906
- case "slice":
907
- text += `${indent.get()}for i := range ${paramName} {\n`;
908
- text += `${indent.push().get()}${paramName}[i].ContentType = ${unwrapped.contentType.literal}\n`;
909
- text += `${indent.pop().get()}}\n`;
910
- break;
911
- }
912
- return text;
913
- }
914
- function createProtocolRequest(azureARM, method, imports, indent) {
915
- let name = method.name;
916
- if (method.kind !== "nextPageMethod") {
917
- name = method.naming.requestMethod;
918
- }
919
- for (const param of method.parameters) {
920
- if (param.location !== "method" || !go.isRequiredParameter(param.style)) {
921
- continue;
922
- }
923
- imports.addForType(param.type);
924
- }
925
- const returns = ["*policy.Request", "error"];
926
- let text = `${helpers.comment(name, "// ")} creates the ${method.name} request.\n`;
927
- text += `func ${getClientReceiverDefinition(method.receiver)} ${name}(${helpers.getCreateRequestParametersSig(method)}) (${returns.join(", ")}) {\n`;
928
- const hostParams = new Array();
929
- for (const parameter of method.receiver.type.parameters) {
930
- if (parameter.kind === "uriParam") {
931
- hostParams.push(parameter);
932
- }
933
- }
934
- let hostParam;
935
- if (azureARM) {
936
- hostParam = "client.internal.Endpoint()";
937
- }
938
- else if (method.receiver.type.instance?.kind === "templatedHost") {
939
- imports.add("strings");
940
- // we have a templated host
941
- text += `${indent.get()}host := "${method.receiver.type.instance.path}"\n`;
942
- // get all the host params on the client
943
- for (const hostParam of hostParams) {
944
- text += `${indent.get()}host = strings.ReplaceAll(host, "{${hostParam.uriPathSegment}}", ${helpers.formatValue(`client.${hostParam.name}`, hostParam.type, imports)})\n`;
945
- }
946
- // check for any method local host params
947
- for (const param of method.parameters) {
948
- if (param.location === "method" && param.kind === "uriParam") {
949
- text += `${indent.get()}host = strings.ReplaceAll(host, "{${param.uriPathSegment}}", ${helpers.formatValue(helpers.getParamName(param), param.type, imports)})\n`;
950
- }
951
- }
952
- hostParam = "host";
953
- }
954
- else if (hostParams.length === 1) {
955
- // simple parameterized host case
956
- hostParam = "client." + hostParams[0].name;
957
- }
958
- else {
959
- throw new CodegenError("InternalError", `no host or endpoint defined for method ${method.receiver.type.name}.${method.name}`);
960
- }
961
- const methodParamGroups = helpers.getMethodParamGroups(method);
962
- const hasPathParams = methodParamGroups.pathParams.length > 0;
963
- // storage needs the client.u to be the source-of-truth for the full path.
964
- // however, swagger requires that all operations specify a path, which is at odds with storage.
965
- // to work around this, storage specifies x-ms-path paths with path params but doesn't
966
- // actually reference the path params (i.e. no params with which to replace the tokens).
967
- // so, if a path contains tokens but there are no path params, skip emitting the path.
968
- const pathStr = method.httpPath;
969
- const pathContainsParms = pathStr.includes("{");
970
- if (hasPathParams || (!pathContainsParms && pathStr.length > 1)) {
971
- // there are path params, or the path doesn't contain tokens and is not "/" so emit it
972
- text += `${indent.get()}urlPath := "${method.httpPath}"\n`;
973
- hostParam = `runtime.JoinPaths(${hostParam}, urlPath)`;
974
- }
975
- // helper to build nil checks for param groups
976
- const emitParamGroupCheck = function (param) {
977
- if (!param.group) {
978
- throw new CodegenError("InternalError", `emitParamGroupCheck called for ungrouped parameter ${param.name}`);
979
- }
980
- let client = "";
981
- if (param.location === "client") {
982
- client = "client.";
983
- }
984
- const paramGroupName = naming.uncapitalize(param.group.name);
985
- let optionalParamGroupCheck = `${client}${paramGroupName} != nil && `;
986
- if (param.group.required) {
987
- optionalParamGroupCheck = "";
988
- }
989
- return `${indent.get()}if ${optionalParamGroupCheck}${client}${paramGroupName}.${naming.capitalize(param.name)} != nil {\n`;
990
- };
991
- if (hasPathParams) {
992
- // swagger defines path params, emit path and replace tokens
993
- imports.add("strings");
994
- // replace path parameters
995
- for (const pp of methodParamGroups.pathParams) {
996
- let paramValue;
997
- let optionalPathSep = false;
998
- if (pp.style === "literal") {
999
- // literals are always scalar types and require no empty checks
1000
- paramValue = helpers.formatParamValue(pp, imports, indent);
1001
- }
1002
- else if (pp.style === "required" || pp.location === "client") {
1003
- // NOTE: we include client params here since they behave
1004
- // like required params (i.e. not grouped).
1005
- // emit check to ensure path param isn't an empty string
1006
- if (pp.kind === "pathScalarParam") {
1007
- const choiceIsString = function (type) {
1008
- return type.kind === "constant" && type.type === "string";
1009
- };
1010
- // we only need to do this for params that have an underlying type of string
1011
- if ((pp.type.kind === "string" || choiceIsString(pp.type)) && !pp.omitEmptyStringCheck) {
1012
- const paramName = helpers.getParamName(pp);
1013
- imports.add("errors");
1014
- text += `${indent.get()}if ${paramName} == "" {\n`;
1015
- text += `${indent.push().get()}return nil, errors.New("parameter ${paramName} cannot be empty")\n`;
1016
- text += `${indent.pop().get()}}\n`;
1017
- }
1018
- }
1019
- paramValue = helpers.formatParamValue(pp, imports, indent);
1020
- // for collection-based path params, we emit the empty check
1021
- // after calling helpers.formatParamValue as that will have the
1022
- // var name that contains the slice.
1023
- if (pp.kind === "pathCollectionParam") {
1024
- const paramName = helpers.getParamName(pp);
1025
- const joinedParamName = `${paramName}Param`;
1026
- text += `${indent.get()}${joinedParamName} := ${paramValue}\n`;
1027
- imports.add("errors");
1028
- text += `${indent.get()}if len(${joinedParamName}) == 0 {\n`;
1029
- text += `${indent.push().get()}return nil, errors.New("parameter ${paramName} cannot be empty")\n`;
1030
- text += `${indent.pop().get()}}\n`;
1031
- paramValue = joinedParamName;
1032
- }
1033
- }
1034
- else if (go.isClientSideDefault(pp.style)) {
1035
- const defaultValue = naming.uncapitalize(pp.name) + "Default";
1036
- text += `${indent.get()}${defaultValue} := ${helpers.formatLiteralValue(pp.style.defaultValue, true)}\n`;
1037
- text += emitParamGroupCheck(pp);
1038
- text += `${indent.push().get()}${defaultValue} = ${helpers.getParamName(pp)}\n`;
1039
- text += `${indent.pop().get()}}\n`;
1040
- paramValue = helpers.formatValue(defaultValue, pp.type, imports);
1041
- }
1042
- else {
1043
- // param isn't required, so emit a local var with
1044
- // the correct default value, then populate it with
1045
- // the optional value when set.
1046
- paramValue = `optional${naming.capitalize(pp.name)}`;
1047
- text += `${indent.get()}${paramValue} := ""\n`;
1048
- text += emitParamGroupCheck(pp);
1049
- text += `${indent.push().get()}${paramValue} = ${helpers.formatParamValue(pp, imports, indent)}\n`;
1050
- text += `${indent.pop().get()}}\n`;
1051
- // there are two cases for optional path params.
1052
- // - /foo/bar/{optional}
1053
- // - /foo/bar{/optional}
1054
- // for the second case, we need to include a forward slash
1055
- if (method.httpPath[method.httpPath.indexOf(`{${pp.pathSegment}}`) - 1] !== "/") {
1056
- optionalPathSep = true;
1057
- }
1058
- }
1059
- const emitPathEscape = function () {
1060
- if (pp.isEncoded) {
1061
- imports.add("net/url");
1062
- return `url.PathEscape(${paramValue})`;
1063
- }
1064
- return paramValue;
1065
- };
1066
- if (optionalPathSep) {
1067
- text += `${indent.get()}if len(${paramValue}) > 0 {\n`;
1068
- text += `${indent.push().get()}${paramValue} = "/"+${emitPathEscape()}\n`;
1069
- text += `${indent.pop().get()}}\n`;
1070
- }
1071
- else {
1072
- paramValue = emitPathEscape();
1073
- }
1074
- text += `${indent.get()}urlPath = strings.ReplaceAll(urlPath, "{${pp.pathSegment}}", ${paramValue})\n`;
1075
- }
1076
- }
1077
- text += `${indent.get()}req, err := runtime.NewRequest(ctx, http.Method${naming.capitalize(method.httpMethod)}, ${hostParam})\n`;
1078
- text += `${indent.get()}if err != nil {\n`;
1079
- text += `${indent.push().get()}return nil, err\n`;
1080
- text += `${indent.pop().get()}}\n`;
1081
- // add query parameters
1082
- const encodedParams = methodParamGroups.encodedQueryParams;
1083
- const unencodedParams = methodParamGroups.unencodedQueryParams;
1084
- const emitQueryParam = function (qp, setter) {
1085
- let qpText;
1086
- if (qp.location === "method" && go.isClientSideDefault(qp.style)) {
1087
- qpText = emitClientSideDefault(qp, qp.style, (name, val) => {
1088
- return `${indent.get()}reqQP.Set(${name}, ${val})`;
1089
- }, imports, indent);
1090
- }
1091
- else if (go.isRequiredParameter(qp.style) ||
1092
- go.isLiteralParameter(qp.style) ||
1093
- (qp.location === "client" && go.isClientSideDefault(qp.style))) {
1094
- qpText = `${indent.get()}${setter}\n`;
1095
- }
1096
- else if (qp.location === "client" && !qp.group) {
1097
- // global optional param
1098
- qpText = `${indent.get()}if client.${qp.name} != nil {\n`;
1099
- qpText += `${indent.push().get()}${setter}\n`;
1100
- qpText += `${indent.pop().get()}}\n`;
1101
- }
1102
- else {
1103
- qpText = emitParamGroupCheck(qp);
1104
- qpText += `${indent.push().get()}${setter}\n`;
1105
- qpText += `${indent.pop().get()}}\n`;
1106
- }
1107
- return qpText;
1108
- };
1109
- // emit encoded params first
1110
- if (encodedParams.length > 0) {
1111
- text += `${indent.get()}reqQP := req.Raw().URL.Query()\n`;
1112
- for (const qp of encodedParams.sort((a, b) => {
1113
- return helpers.sortAscending(a.queryParameter, b.queryParameter);
1114
- })) {
1115
- let setter;
1116
- if (qp.kind === "queryCollectionParam" && qp.collectionFormat === "multi") {
1117
- setter = `for _, qv := range ${helpers.getParamName(qp)} {\n`;
1118
- // emit a type conversion for the qv based on the array's element type
1119
- let queryVal;
1120
- const arrayQP = qp.type;
1121
- switch (arrayQP.elementType.kind) {
1122
- case "constant":
1123
- switch (arrayQP.elementType.type) {
1124
- case "string":
1125
- queryVal = "string(qv)";
1126
- break;
1127
- default:
1128
- imports.add("fmt");
1129
- queryVal = 'fmt.Sprintf("%d", qv)';
1130
- }
1131
- break;
1132
- case "string":
1133
- queryVal = "qv";
1134
- break;
1135
- default:
1136
- imports.add("fmt");
1137
- queryVal = 'fmt.Sprintf("%v", qv)';
1138
- }
1139
- setter += `${indent.push().get()}reqQP.Add("${qp.queryParameter}", ${queryVal})\n`;
1140
- setter += `${indent.pop().get()}}`;
1141
- }
1142
- else {
1143
- // cannot initialize setter to this value as helpers.formatParamValue() can change imports
1144
- setter = `reqQP.Set("${qp.queryParameter}", ${helpers.formatParamValue(qp, imports, indent)})`;
1145
- }
1146
- text += emitQueryParam(qp, setter);
1147
- }
1148
- // reqQP.Encode() encodes space chars as '+' which is application/x-www-form-urlencoded
1149
- // thus not applicable for URIs. the correct URI encoding for SP is %20. note that literal '+'
1150
- // characters are encoded by reqQP.Encode() as %2B so there's no risk of replacing them.
1151
- // see https://www.rfc-editor.org/rfc/rfc3986 sections 2.1, 2.2, and 3.4
1152
- imports.add("strings");
1153
- text += `${indent.get()}req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20")\n`;
1154
- }
1155
- // tack on any unencoded params to the end
1156
- if (unencodedParams.length > 0) {
1157
- if (encodedParams.length > 0) {
1158
- text += `${indent.get()}unencodedParams := []string{req.Raw().URL.RawQuery}\n`;
1159
- }
1160
- else {
1161
- text += `${indent.get()}unencodedParams := []string{}\n`;
1162
- }
1163
- for (const qp of unencodedParams.sort((a, b) => {
1164
- return helpers.sortAscending(a.queryParameter, b.queryParameter);
1165
- })) {
1166
- let setter;
1167
- if (qp.kind === "queryCollectionParam" && qp.collectionFormat === "multi") {
1168
- setter = `for _, qv := range ${helpers.getParamName(qp)} {\n`;
1169
- setter += `${indent.push().get()}unencodedParams = append(unencodedParams, "${qp.queryParameter}="+qv)\n`;
1170
- setter += `${indent.pop().get()}}`;
1171
- }
1172
- else {
1173
- setter = `unencodedParams = append(unencodedParams, "${qp.queryParameter}="+${helpers.formatParamValue(qp, imports, indent)})`;
1174
- }
1175
- text += emitQueryParam(qp, setter);
1176
- }
1177
- imports.add("strings");
1178
- text += `${indent.get()}req.Raw().URL.RawQuery = strings.Join(unencodedParams, "&")\n`;
1179
- }
1180
- if (method.kind !== "nextPageMethod" && method.returns.result?.kind === "binaryResult") {
1181
- // skip auto-body downloading for binary stream responses
1182
- text += `${indent.get()}runtime.SkipBodyDownload(req)\n`;
1183
- }
1184
- // add specific request headers
1185
- const emitHeaderSet = function (headerParam) {
1186
- if (headerParam.kind === "headerMapParam") {
1187
- let headerText = `${indent.get()}for k, v := range ${helpers.getParamName(headerParam)} {\n`;
1188
- headerText += `${indent.push().get()}if v != nil {\n`;
1189
- headerText += `${indent.push().get()}req.Raw().Header["${headerParam.headerName}"+k] = []string{*v}\n`;
1190
- headerText += `${indent.pop().get()}}\n`;
1191
- headerText += `${indent.pop().get()}}\n`;
1192
- return headerText;
1193
- }
1194
- else if (headerParam.location === "method" && go.isClientSideDefault(headerParam.style)) {
1195
- return emitClientSideDefault(headerParam, headerParam.style, (name, val) => {
1196
- return `${indent.get()}req.Raw().Header[${name}] = []string{${val}}`;
1197
- }, imports, indent);
1198
- }
1199
- else {
1200
- return `${indent.get()}req.Raw().Header["${headerParam.headerName}"] = []string{${helpers.formatParamValue(headerParam, imports, indent)}}\n`;
1201
- }
1202
- };
1203
- let contentType;
1204
- for (const param of methodParamGroups.headerParams.sort((a, b) => {
1205
- return helpers.sortAscending(a.headerName, b.headerName);
1206
- })) {
1207
- if (param.headerName.match(/^content-type$/i)) {
1208
- // canonicalize content-type as req.SetBody checks for it via its canonicalized name :(
1209
- param.headerName = "Content-Type";
1210
- // there's a corner case where we have a content-type param with no body
1211
- // param. for this case we still need to set the header inline.
1212
- const bodyParam = methodParamGroups.bodyParam;
1213
- if (bodyParam?.bodyFormat === "binary" || bodyParam?.bodyFormat === "Text") {
1214
- // if the content-type is from a param, then the param will be passed
1215
- // explicitly to runtime.SetBody() so don't emit code to set it inline.
1216
- // NOTE: only binary/text payloads call runtime.SetBody().
1217
- if (go.isClientSideDefault(param.style)) {
1218
- text += emitClientSideDefault(param, param.style, () => "", imports, indent);
1219
- continue;
1220
- }
1221
- else if (param.style === "required") {
1222
- continue;
1223
- }
1224
- }
1225
- }
1226
- if (param.headerName === "Content-Type" && param.style === "literal") {
1227
- // the content-type header will be set as part of emitSetBodyWithErrCheck
1228
- // to handle cases where the body param is optional. we don't want to set
1229
- // the content-type if the body is nil.
1230
- // we do it like this as tsp specifies content-type while swagger does not.
1231
- contentType = helpers.formatParamValue(param, imports, indent);
1232
- }
1233
- else if (go.isRequiredParameter(param.style) ||
1234
- go.isLiteralParameter(param.style) ||
1235
- go.isClientSideDefault(param.style)) {
1236
- text += emitHeaderSet(param);
1237
- }
1238
- else if (param.location === "client" && !param.group) {
1239
- // global optional param
1240
- text += `${indent.get()}if client.${param.name} != nil {\n`;
1241
- indent.push();
1242
- text += emitHeaderSet(param);
1243
- indent.pop();
1244
- text += `${indent.get()}}\n`;
1245
- }
1246
- else {
1247
- text += emitParamGroupCheck(param);
1248
- indent.push();
1249
- text += emitHeaderSet(param);
1250
- indent.pop();
1251
- text += `${indent.get()}}\n`;
1252
- }
1253
- }
1254
- // note that these are mutually exclusive
1255
- const bodyParam = methodParamGroups.bodyParam;
1256
- const formBodyParams = methodParamGroups.formBodyParams;
1257
- const multipartBodyParams = methodParamGroups.multipartBodyParams;
1258
- const partialBodyParams = methodParamGroups.partialBodyParams;
1259
- const emitSetBodyWithErrCheck = function (setBodyParam, contentType) {
1260
- let content = "";
1261
- if (contentType) {
1262
- content += `${indent.get()}req.Raw().Header["Content-Type"] = []string{${contentType}}\n`;
1263
- }
1264
- content += `${indent.get()}if err := ${setBodyParam}; err != nil {\n`;
1265
- content += `${indent.push().get()}return nil, err\n`;
1266
- content += `${indent.pop().get()}}\n`;
1267
- return content;
1268
- };
1269
- if (bodyParam) {
1270
- /** returns the source value for the content type */
1271
- const getContentTypeValue = function (src) {
1272
- switch (src.kind) {
1273
- case "literal":
1274
- return helpers.formatLiteralValue(src, false);
1275
- case "parameterRef": {
1276
- // find the param
1277
- for (const param of method.parameters) {
1278
- if (param.kind === "headerScalarParam" && param.name === src.name) {
1279
- if (go.isClientSideDefault(param.style)) {
1280
- return getClientSideDefaultVarName(param);
1281
- }
1282
- let paramName = helpers.getParamName(param);
1283
- if (param.type.kind === "constant") {
1284
- paramName = `string(${paramName})`;
1285
- }
1286
- return paramName;
1287
- }
1288
- }
1289
- throw new CodegenError("InternalError", `didn't find parameter reference ${src.name}`);
1290
- }
1291
- }
1292
- };
1293
- if (bodyParam.bodyFormat === "JSON" || bodyParam.bodyFormat === "XML") {
1294
- // default to the body param name
1295
- let body = helpers.getParamName(bodyParam);
1296
- if (bodyParam.type.kind === "literal") {
1297
- // if the value is constant, embed it directly
1298
- body = helpers.formatLiteralValue(bodyParam.type, true);
1299
- }
1300
- else if (bodyParam.bodyFormat === "XML" && bodyParam.type.kind === "slice") {
1301
- // for XML payloads, create a wrapper type if the payload is an array
1302
- imports.add("encoding/xml");
1303
- text += `${indent.get()}type wrapper struct {\n`;
1304
- indent.push();
1305
- let tagName;
1306
- if (bodyParam.xml?.wrapper) {
1307
- tagName = bodyParam.xml.wrapper;
1308
- }
1309
- else {
1310
- tagName = go.getTypeDeclaration(bodyParam.type, method.receiver.type.pkg);
1311
- }
1312
- text += `${indent.get()}XMLName xml.Name \`xml:"${tagName}"\`\n`;
1313
- const fieldName = naming.capitalize(bodyParam.name);
1314
- let tag = go.getTypeDeclaration(bodyParam.type.elementType, method.receiver.type.pkg);
1315
- if (bodyParam.type.elementType.kind === "model" && bodyParam.type.elementType.xml?.name) {
1316
- tag = bodyParam.type.elementType.xml.name;
1317
- }
1318
- text += `${indent.get()}${fieldName} *${go.getTypeDeclaration(bodyParam.type, method.receiver.type.pkg)} \`xml:"${tag}"\`\n`;
1319
- text += `${indent.pop().get()}}\n`;
1320
- let addr = "&";
1321
- if (!go.isRequiredParameter(bodyParam.style) && !bodyParam.byValue) {
1322
- addr = "";
1323
- }
1324
- body = `wrapper{${fieldName}: ${addr}${body}}`;
1325
- }
1326
- else if (bodyParam.type.kind === "time" && bodyParam.type.format !== "RFC3339") {
1327
- // wrap the body in the internal time type
1328
- // no need for RFC3339 as the JSON marshaler defaults to that.
1329
- imports.add("github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime");
1330
- body = `datetime.${bodyParam.type.format}(${body})`;
1331
- }
1332
- else if (isArrayOfDateTimeForMarshalling(bodyParam.type)) {
1333
- const timeInfo = isArrayOfDateTimeForMarshalling(bodyParam.type);
1334
- let elementPtr = "*";
1335
- if (timeInfo?.elemByVal) {
1336
- elementPtr = "";
1337
- }
1338
- imports.add("github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime");
1339
- text += `${indent.get()}aux := make([]${elementPtr}datetime.${timeInfo?.format}, len(${body}))\n`;
1340
- text += `${indent.get()}for i := 0; i < len(${body}); i++ {\n`;
1341
- text += `${indent.push().get()}aux[i] = (${elementPtr}datetime.${timeInfo?.format})(${body}[i])\n`;
1342
- text += `${indent.pop().get()}}\n`;
1343
- body = "aux";
1344
- }
1345
- else if (isMapOfDateTime(bodyParam.type)) {
1346
- const timeType = isMapOfDateTime(bodyParam.type);
1347
- imports.add("github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime");
1348
- text += `${indent.get()}aux := map[string]*datetime.${timeType}{}\n`;
1349
- text += `${indent.get()}for k, v := range ${body} {\n`;
1350
- text += `${indent.push().get()}aux[k] = (*datetime.${timeType})(v)\n`;
1351
- text += `${indent.pop().get()}}\n`;
1352
- body = "aux";
1353
- }
1354
- let setBody = `runtime.MarshalAs${getMediaFormat(bodyParam.type, bodyParam.bodyFormat, `req, ${body}`)}`;
1355
- if (bodyParam.type.kind === "rawJSON") {
1356
- imports.add("bytes");
1357
- imports.add("github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming");
1358
- setBody = `req.SetBody(streaming.NopCloser(bytes.NewReader(${body})), "application/${bodyParam.bodyFormat.toLowerCase()}")`;
1359
- }
1360
- if (go.isRequiredParameter(bodyParam.style) || go.isLiteralParameter(bodyParam.style)) {
1361
- text += emitSetBodyWithErrCheck(setBody, contentType);
1362
- text += `${indent.get()}return req, nil\n`;
1363
- }
1364
- else {
1365
- text += emitParamGroupCheck(bodyParam);
1366
- indent.push();
1367
- text += emitSetBodyWithErrCheck(setBody, contentType);
1368
- text += `${indent.get()}return req, nil\n`;
1369
- indent.pop();
1370
- text += `${indent.get()}}\n`;
1371
- text += `${indent.get()}return req, nil\n`;
1372
- }
1373
- }
1374
- else if (bodyParam.bodyFormat === "binary") {
1375
- if (go.isRequiredParameter(bodyParam.style)) {
1376
- text += emitSetBodyWithErrCheck(`req.SetBody(${bodyParam.name}, ${getContentTypeValue(bodyParam.contentType)})`, contentType);
1377
- text += `${indent.get()}return req, nil\n`;
1378
- }
1379
- else {
1380
- text += emitParamGroupCheck(bodyParam);
1381
- indent.push();
1382
- text += emitSetBodyWithErrCheck(`req.SetBody(${helpers.getParamName(bodyParam)}, ${getContentTypeValue(bodyParam.contentType)})`, contentType);
1383
- text += `${indent.get()}return req, nil\n`;
1384
- indent.pop();
1385
- text += `${indent.get()}}\n`;
1386
- text += `${indent.get()}return req, nil\n`;
1387
- }
1388
- }
1389
- else if (bodyParam.bodyFormat === "Text") {
1390
- imports.add("strings");
1391
- imports.add("github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming");
1392
- if (go.isRequiredParameter(bodyParam.style)) {
1393
- text += `${indent.get()}body := streaming.NopCloser(strings.NewReader(${bodyParam.name}))\n`;
1394
- text += emitSetBodyWithErrCheck(`req.SetBody(body, ${getContentTypeValue(bodyParam.contentType)})`, contentType);
1395
- text += `${indent.get()}return req, nil\n`;
1396
- }
1397
- else {
1398
- text += emitParamGroupCheck(bodyParam);
1399
- indent.push();
1400
- text += `${indent.get()}body := streaming.NopCloser(strings.NewReader(${helpers.getParamName(bodyParam)}))\n`;
1401
- text += emitSetBodyWithErrCheck(`req.SetBody(body, ${getContentTypeValue(bodyParam.contentType)})`, contentType);
1402
- text += `${indent.get()}return req, nil\n`;
1403
- indent.pop();
1404
- text += `${indent.get()}}\n`;
1405
- text += `${indent.get()}return req, nil\n`;
1406
- }
1407
- }
1408
- }
1409
- else if (partialBodyParams.length > 0) {
1410
- // partial body params are discrete params that are all fields within an internal struct.
1411
- // define and instantiate an instance of the wire type, using the values from each param.
1412
- text += `${indent.get()}body := struct {\n`;
1413
- indent.push();
1414
- for (const partialBodyParam of partialBodyParams) {
1415
- text += `${indent.get()}${naming.capitalize(partialBodyParam.serializedName)} ${helpers.star(partialBodyParam.byValue)}${go.getTypeDeclaration(partialBodyParam.type, method.receiver.type.pkg)} \`${partialBodyParam.format.toLowerCase()}:"${partialBodyParam.serializedName}"\`\n`;
1416
- }
1417
- indent.pop();
1418
- text += `${indent.get()}}{\n`;
1419
- indent.push();
1420
- // required params are emitted as initializers in the struct literal
1421
- for (const partialBodyParam of partialBodyParams) {
1422
- if (go.isRequiredParameter(partialBodyParam.style)) {
1423
- text += `${indent.get()}${naming.capitalize(partialBodyParam.serializedName)}: ${naming.uncapitalize(partialBodyParam.name)},\n`;
1424
- }
1425
- }
1426
- indent.pop();
1427
- text += `${indent.get()}}\n`;
1428
- // now populate any optional params from the options type
1429
- for (const partialBodyParam of partialBodyParams) {
1430
- if (!go.isRequiredParameter(partialBodyParam.style)) {
1431
- text += emitParamGroupCheck(partialBodyParam);
1432
- text += `${indent.push().get()}body.${naming.capitalize(partialBodyParam.serializedName)} = options.${naming.capitalize(partialBodyParam.name)}\n`;
1433
- text += `${indent.pop().get()}}\n`;
1434
- }
1435
- }
1436
- // TODO: spread params are JSON only https://github.com/Azure/autorest.go/issues/1455
1437
- text += `${indent.get()}req.Raw().Header["Content-Type"] = []string{"application/json"}\n`;
1438
- text += `${indent.get()}if err := runtime.MarshalAsJSON(req, body); err != nil {\n`;
1439
- text += `${indent.push().get()}return nil, err\n`;
1440
- text += `${indent.pop().get()}}\n`;
1441
- text += `${indent.get()}return req, nil\n`;
1442
- }
1443
- else if (multipartBodyParams.length > 0) {
1444
- // emit content type setters for direct MultipartContent params with a fixed content type.
1445
- // this handles the case where the param itself is a MultipartContent or a slice of them
1446
- // (i.e. not wrapped in a model struct with toMultipartFormData()).
1447
- // note that tsp only allows homogeneous content types, which is why it's safe
1448
- // to unwrap the first param's type and check its contentType field.
1449
- text += emitMultipartContentTypeSetter(multipartBodyParams[0].name, multipartBodyParams[0].type, indent);
1450
- if (multipartBodyParams.length === 1 &&
1451
- multipartBodyParams[0].type.kind === "model" &&
1452
- multipartBodyParams[0].type.annotations.multipartFormData) {
1453
- // emit content type setters for model fields that have a fixed content type.
1454
- // toMultipartFormData() converts the model to map[string]any but doesn't set ContentType,
1455
- // so we must set it on each MultipartContent field before the conversion.
1456
- for (const field of multipartBodyParams[0].type.fields) {
1457
- text += emitMultipartContentTypeSetter(`${multipartBodyParams[0].name}.${field.name}`, field.type, indent);
680
+ else if (method.returns.result) {
681
+ switch (method.returns.result.kind) {
682
+ case "binaryResult":
683
+ text += `${indent.get()}return ${method.returns.name}{${method.returns.result.fieldName}: httpResp.Body}, nil\n`;
684
+ break;
685
+ case "headAsBooleanResult":
686
+ text += `${indent.get()}return ${method.returns.name}{${method.returns.result.fieldName}: httpResp.StatusCode >= 200 && httpResp.StatusCode < 300}, nil\n`;
687
+ break;
688
+ default:
689
+ // we should never get here as the remaining kinds are all modeled results
690
+ // thus should have been handled by the needsResponseHandler check earlier
691
+ throw new CodegenError("InternalError", `unexpected method result kind ${method.returns.result.kind}`);
1458
692
  }
1459
- text += `${indent.get()}formData, err := ${multipartBodyParams[0].name}.toMultipartFormData()\n`;
1460
- text += `${indent.get()}if err != nil {\n`;
1461
- text += `${indent.push().get()}return nil, err\n`;
1462
- text += `${indent.pop().get()}}\n`;
1463
693
  }
1464
694
  else {
1465
- text += `${indent.get()}formData := map[string]any{}\n`;
1466
- for (const param of multipartBodyParams) {
1467
- const setter = `formData["${param.name}"] = ${helpers.getParamName(param)}`;
1468
- if (go.isRequiredParameter(param.style)) {
1469
- text += `${indent.get()}${setter}\n`;
1470
- }
1471
- else {
1472
- text += emitParamGroupCheck(param);
1473
- text += `${indent.push().get()}${setter}\n`;
1474
- text += `${indent.pop().get()}}\n`;
1475
- }
1476
- }
1477
- }
1478
- text += `${indent.get()}if err := runtime.SetMultipartFormData(req, formData); err != nil {\n`;
1479
- text += `${indent.push().get()}return nil, err\n`;
1480
- text += `${indent.pop().get()}}\n`;
1481
- text += `${indent.get()}return req, nil\n`;
1482
- }
1483
- else if (formBodyParams.length > 0) {
1484
- const emitFormData = function (param, setter) {
1485
- let formDataText;
1486
- if (go.isRequiredParameter(param.style)) {
1487
- formDataText = `${indent.get()}${setter}\n`;
1488
- }
1489
- else {
1490
- formDataText = emitParamGroupCheck(param);
1491
- formDataText += `${indent.push().get()}${setter}\n`;
1492
- formDataText += `${indent.pop().get()}}\n`;
1493
- }
1494
- return formDataText;
1495
- };
1496
- imports.add("net/url");
1497
- imports.add("strings");
1498
- imports.add("github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming");
1499
- text += `${indent.get()}formData := url.Values{}\n`;
1500
- // find all the form body params
1501
- for (const param of formBodyParams) {
1502
- const setter = `formData.Set("${param.formDataName}", ${helpers.formatParamValue(param, imports, indent)})`;
1503
- text += emitFormData(param, setter);
695
+ // no result type, just response envelope
696
+ text += `${indent.get()}return ${zeroResp}, nil\n`;
1504
697
  }
1505
- text += `${indent.get()}body := streaming.NopCloser(strings.NewReader(formData.Encode()))\n`;
1506
- text += emitSetBodyWithErrCheck('req.SetBody(body, "application/x-www-form-urlencoded")');
1507
- text += `${indent.get()}return req, nil\n`;
1508
- }
1509
- else {
1510
- text += `${indent.get()}return req, nil\n`;
1511
698
  }
1512
699
  text += "}\n\n";
1513
700
  return text;
1514
701
  }
1515
- /**
1516
- * returns the var name to use for a param's client-side default value
1517
- *
1518
- * @param param the param for which to name the var
1519
- * @returns the var name
1520
- */
1521
- function getClientSideDefaultVarName(param) {
1522
- return naming.uncapitalize(param.name) + "Default";
1523
- }
1524
- function emitClientSideDefault(param, csd, setterFormat, imports, indent) {
1525
- const defaultVar = getClientSideDefaultVarName(param);
1526
- let text = `${indent.get()}${defaultVar} := ${helpers.formatLiteralValue(csd.defaultValue, true)}\n`;
1527
- text += `${indent.get()}if options != nil && options.${naming.capitalize(param.name)} != nil {\n`;
1528
- text += `${indent.push().get()}${defaultVar} = *options.${naming.capitalize(param.name)}\n`;
1529
- text += `${indent.pop().get()}}\n`;
1530
- let serializedName;
1531
- switch (param.kind) {
1532
- case "headerCollectionParam":
1533
- case "headerScalarParam":
1534
- serializedName = param.headerName;
1535
- break;
1536
- case "queryCollectionParam":
1537
- case "queryScalarParam":
1538
- serializedName = param.queryParameter;
1539
- break;
1540
- }
1541
- const setterFormatText = setterFormat(`"${serializedName}"`, helpers.formatValue(defaultVar, param.type, imports));
1542
- text += setterFormatText;
1543
- // setterFormat can return the empty string in some cases.
1544
- // if it does, there's no need for an extra new-line char.
1545
- if (setterFormatText.length > 0) {
1546
- text += "\n";
1547
- }
1548
- return text;
1549
- }
1550
- function getMediaFormat(type, mediaType, param) {
1551
- let marshaller = mediaType;
1552
- let format = "";
1553
- if (type.kind === "encodedBytes") {
1554
- marshaller = "ByteArray";
1555
- format = `, runtime.Base64${type.encoding}Format`;
1556
- }
1557
- return `${marshaller}(${param}${format})`;
1558
- }
1559
- function isArrayOfDateTimeForMarshalling(paramType) {
1560
- if (paramType.kind !== "slice") {
1561
- return undefined;
1562
- }
1563
- if (paramType.elementType.kind !== "time") {
1564
- return undefined;
1565
- }
1566
- switch (paramType.elementType.format) {
1567
- case "PlainDate":
1568
- case "RFC1123":
1569
- case "RFC7231":
1570
- case "PlainTime":
1571
- case "Unix":
1572
- return {
1573
- format: paramType.elementType.format,
1574
- elemByVal: paramType.elementTypeByValue,
1575
- };
1576
- default:
1577
- // RFC3339 uses the default marshaller
1578
- return undefined;
1579
- }
1580
- }
1581
702
  // returns true if the method requires a response handler.
1582
703
  // this is used to unmarshal the response body, parse response headers, or both.
1583
704
  function needsResponseHandler(method) {
1584
- return helpers.hasSchemaResponse(method) || method.returns.headers.length > 0;
1585
- }
1586
- function generateResponseUnmarshaller(method, type, format, unmarshalTarget, imports, indent) {
1587
- let unmarshallerText = "";
1588
- const zeroValue = getZeroReturnValue(method, "handler");
1589
- if (type.kind === "time") {
1590
- // use the designated time type for unmarshalling
1591
- imports.add("github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime");
1592
- unmarshallerText += `${indent.get()}var aux *datetime.${type.format}\n`;
1593
- unmarshallerText += `${indent.get()}if err := runtime.UnmarshalAs${format}(resp, &aux); err != nil {\n`;
1594
- unmarshallerText += `${indent.push().get()}return ${zeroValue}, err\n`;
1595
- unmarshallerText += `${indent.pop().get()}}\n`;
1596
- unmarshallerText += `${indent.get()}result.${helpers.getResultFieldName(method)} = (*time.Time)(aux)\n`;
1597
- return unmarshallerText;
1598
- }
1599
- else if (isArrayOfDateTime(type)) {
1600
- // unmarshalling arrays of date/time is a little more involved
1601
- const timeInfo = isArrayOfDateTime(type);
1602
- let elementPtr = "*";
1603
- if (timeInfo?.elemByVal) {
1604
- elementPtr = "";
1605
- }
1606
- imports.add("github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime");
1607
- unmarshallerText += `${indent.get()}var aux []${elementPtr}datetime.${timeInfo?.format}\n`;
1608
- unmarshallerText += `${indent.get()}if err := runtime.UnmarshalAs${format}(resp, &aux); err != nil {\n`;
1609
- unmarshallerText += `${indent.push().get()}return ${zeroValue}, err\n`;
1610
- unmarshallerText += `${indent.pop().get()}}\n`;
1611
- unmarshallerText += `${indent.get()}cp := make([]${elementPtr}time.Time, len(aux))\n`;
1612
- unmarshallerText += `${indent.get()}for i := 0; i < len(aux); i++ {\n`;
1613
- unmarshallerText += `${indent.push().get()}cp[i] = (${elementPtr}time.Time)(aux[i])\n`;
1614
- unmarshallerText += `${indent.pop().get()}}\n`;
1615
- unmarshallerText += `${indent.get()}result.${helpers.getResultFieldName(method)} = cp\n`;
1616
- return unmarshallerText;
1617
- }
1618
- else if (isMapOfDateTime(type)) {
1619
- const timeType = isMapOfDateTime(type);
1620
- imports.add("github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime");
1621
- unmarshallerText += `${indent.get()}aux := map[string]*datetime.${timeType}{}\n`;
1622
- unmarshallerText += `${indent.get()}if err := runtime.UnmarshalAs${format}(resp, &aux); err != nil {\n`;
1623
- unmarshallerText += `${indent.push().get()}return ${zeroValue}, err\n`;
1624
- unmarshallerText += `${indent.pop().get()}}\n`;
1625
- unmarshallerText += `${indent.get()}cp := map[string]*time.Time{}\n`;
1626
- unmarshallerText += `${indent.get()}for k, v := range aux {\n`;
1627
- unmarshallerText += `${indent.push().get()}cp[k] = (*time.Time)(v)\n`;
1628
- unmarshallerText += `${indent.pop().get()}}\n`;
1629
- unmarshallerText += `${indent.get()}result.${helpers.getResultFieldName(method)} = cp\n`;
1630
- return unmarshallerText;
1631
- }
1632
- if (format === "JSON" || format === "XML") {
1633
- if (type.kind === "rawJSON") {
1634
- unmarshallerText += `${indent.get()}body, err := runtime.Payload(resp)\n`;
1635
- unmarshallerText += `${indent.get()}if err != nil {\n`;
1636
- unmarshallerText += `${indent.push().get()}return ${zeroValue}, err\n`;
1637
- unmarshallerText += `${indent.pop().get()}}\n`;
1638
- unmarshallerText += `${indent.get()}${unmarshalTarget} = body\n`;
1639
- }
1640
- else {
1641
- unmarshallerText += `${indent.get()}if err := runtime.UnmarshalAs${getMediaFormat(type, format, `resp, &${unmarshalTarget}`)}; err != nil {\n`;
1642
- unmarshallerText += `${indent.push().get()}return ${zeroValue}, err\n`;
1643
- unmarshallerText += `${indent.pop().get()}}\n`;
1644
- }
1645
- }
1646
- else if (format === "Text") {
1647
- unmarshallerText += `${indent.get()}body, err := runtime.Payload(resp)\n`;
1648
- unmarshallerText += `${indent.get()}if err != nil {\n`;
1649
- unmarshallerText += `${indent.push().get()}return ${zeroValue}, err\n`;
1650
- unmarshallerText += `${indent.pop().get()}}\n`;
1651
- let resultVar;
1652
- switch (type.kind) {
1653
- case "scalar":
1654
- resultVar = "parsedBody";
1655
- unmarshallerText += emitScalarParsing(type, "string(body)", resultVar, imports, indent);
1656
- unmarshallerText += `${indent.get()}${helpers.buildErrCheck(indent, "err", zeroValue)}\n`;
1657
- break;
1658
- case "string":
1659
- resultVar = "txt";
1660
- unmarshallerText += `${indent.get()}${resultVar} := string(body)\n`;
1661
- break;
1662
- default:
1663
- throw new CodegenError("UnsupportedTsp", `unsupported text return kind ${type.kind} for method ${method.receiver.type.name}.${method.name}`);
1664
- }
1665
- unmarshallerText += `${indent.get()}${unmarshalTarget} = &${resultVar}\n`;
1666
- }
1667
- else {
1668
- // the remaining formats should have been handled elsewhere
1669
- throw new CodegenError("InternalError", `unhandled format ${format} for operation ${method.receiver.type.name}.${method.name}`);
1670
- }
1671
- return unmarshallerText;
1672
- }
1673
- function createProtocolResponse(method, imports, indent) {
1674
- if (!needsResponseHandler(method)) {
1675
- return "";
1676
- }
1677
- const name = method.naming.responseMethod;
1678
- let text = `${helpers.comment(name, "// ")} handles the ${method.name} response.\n`;
1679
- text += `func ${getClientReceiverDefinition(method.receiver)} ${name}(resp *http.Response) (${generateReturnsInfo(method, "handler").join(", ")}) {\n`;
1680
- const addHeaders = function (headers) {
1681
- for (const header of headers) {
1682
- text += formatHeaderResponseValue(method, header, "result", `${method.returns.name}{}`, imports, indent);
1683
- }
1684
- };
1685
- const result = method.returns.result;
1686
- if (!result) {
1687
- // only headers
1688
- text += `${indent.get()}result := ${method.returns.name}{}\n`;
1689
- addHeaders(method.returns.headers);
1690
- }
1691
- else {
1692
- switch (result.kind) {
1693
- case "anyResult":
1694
- imports.add("fmt");
1695
- text += `${indent.get()}result := ${method.returns.name}{}\n`;
1696
- addHeaders(method.returns.headers);
1697
- text += `${indent.get()}switch resp.StatusCode {\n`;
1698
- for (const statusCode of method.httpStatusCodes) {
1699
- text += `${indent.get()}case ${helpers.formatStatusCodes([statusCode])}:\n`;
1700
- const resultType = result.httpStatusCodeType[statusCode];
1701
- if (!resultType) {
1702
- // the operation contains a mix of schemas and non-schema responses
1703
- continue;
1704
- }
1705
- text += `${indent.get()}var val ${go.getTypeDeclaration(resultType, method.receiver.type.pkg)}\n`;
1706
- text += generateResponseUnmarshaller(method, resultType, result.format, "val", imports, indent);
1707
- text += `${indent.get()}result.Value = val\n`;
1708
- }
1709
- text += `${indent.get()}default:\n`;
1710
- text += `${indent.push().get()}return ${getZeroReturnValue(method, "handler")}, fmt.Errorf("unhandled HTTP status code %d", resp.StatusCode)\n`;
1711
- text += `${indent.pop().get()}}\n`;
1712
- break;
1713
- case "binaryResult":
1714
- text += `${indent.get()}result := ${method.returns.name}{${result.fieldName}: resp.Body}\n`;
1715
- addHeaders(method.returns.headers);
1716
- break;
1717
- case "headAsBooleanResult":
1718
- text += `${indent.get()}result := ${method.returns.name}{${result.fieldName}: resp.StatusCode >= 200 && resp.StatusCode < 300}\n`;
1719
- addHeaders(method.returns.headers);
1720
- break;
1721
- case "modelResult":
1722
- text += `${indent.get()}result := ${method.returns.name}{}\n`;
1723
- addHeaders(method.returns.headers);
1724
- text += generateResponseUnmarshaller(method, result.modelType, result.format, `result.${helpers.getResultFieldName(method)}`, imports, indent);
1725
- break;
1726
- case "monomorphicResult":
1727
- text += `${indent.get()}result := ${method.returns.name}{}\n`;
1728
- addHeaders(method.returns.headers);
1729
- let target = `result.${helpers.getResultFieldName(method)}`;
1730
- // when unmarshalling a wrapped XML array, unmarshal into the response envelope
1731
- if (result.format === "XML" && result.monomorphicType.kind === "slice") {
1732
- target = "result";
1733
- }
1734
- text += generateResponseUnmarshaller(method, result.monomorphicType, result.format, target, imports, indent);
1735
- break;
1736
- case "polymorphicResult":
1737
- text += `${indent.get()}result := ${method.returns.name}{}\n`;
1738
- addHeaders(method.returns.headers);
1739
- text += generateResponseUnmarshaller(method, result.interface, result.format, "result", imports, indent);
1740
- break;
1741
- default:
1742
- result;
1743
- }
1744
- }
1745
- text += `${indent.get()}return result, nil\n`;
1746
- text += "}\n\n";
1747
- return text;
1748
- }
1749
- function isArrayOfDateTime(paramType) {
1750
- if (paramType.kind !== "slice") {
1751
- return undefined;
1752
- }
1753
- if (paramType.elementType.kind !== "time") {
1754
- return undefined;
1755
- }
1756
- return {
1757
- format: paramType.elementType.format,
1758
- elemByVal: paramType.elementTypeByValue,
1759
- };
1760
- }
1761
- function isMapOfDateTime(paramType) {
1762
- if (paramType.kind !== "map") {
1763
- return undefined;
1764
- }
1765
- if (paramType.valueType.kind !== "time") {
1766
- return undefined;
705
+ switch (method.returns.result?.kind) {
706
+ case "anyResult":
707
+ case "modelResult":
708
+ case "monomorphicResult":
709
+ case "polymorphicResult":
710
+ return true;
711
+ default:
712
+ return method.returns.headers.length > 0;
1767
713
  }
1768
- return paramType.valueType.format;
1769
714
  }
1770
715
  /**
1771
716
  * returns the parameters for the public API
@@ -1805,7 +750,6 @@ function getAPIParametersSig(method, imports) {
1805
750
  // apiType describes where the return sig is used.
1806
751
  // api - for the API definition
1807
752
  // op - for the operation
1808
- // handler - for the response handler
1809
753
  function generateReturnsInfo(method, apiType) {
1810
754
  let returnType = method.returns.name;
1811
755
  switch (method.kind) {
@@ -1820,25 +764,14 @@ function generateReturnsInfo(method, apiType) {
1820
764
  returnType = `*runtime.Poller[${returnType}]`;
1821
765
  }
1822
766
  break;
1823
- case "handler":
1824
- // we only have a handler for operations that return a schema
1825
- if (method.kind !== "lroPageableMethod") {
1826
- throw new CodegenError("InternalError", `handler being generated for non-pageable LRO ${method.name} which is unexpected`);
1827
- }
1828
- break;
1829
767
  case "op":
1830
768
  returnType = "*http.Response";
1831
769
  break;
1832
770
  }
1833
771
  break;
1834
772
  case "pageableMethod":
1835
- switch (apiType) {
1836
- case "api":
1837
- case "op":
1838
- // pager operations don't return an error
1839
- return [`*runtime.Pager[${returnType}]`];
1840
- }
1841
- break;
773
+ // pager operations don't return an error
774
+ return [`*runtime.Pager[${returnType}]`];
1842
775
  }
1843
776
  return [returnType, "error"];
1844
777
  }
@@ -1848,15 +781,15 @@ function generateLROBeginMethod(method, options, imports, indent) {
1848
781
  imports.add("github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime");
1849
782
  let text = "";
1850
783
  if (method.docs.summary || method.docs.description) {
1851
- text += helpers.formatDocCommentWithPrefix(fixUpMethodName(method), method.docs);
784
+ text += helpers.formatDocCommentWithPrefix(helpers.fixUpMethodName(method), method.docs);
1852
785
  text += genRespErrorDoc(method);
1853
786
  }
1854
- const zeroResp = getZeroReturnValue(method, "lro");
787
+ const zeroResp = getZeroReturnValue(method, false);
1855
788
  const methodParams = helpers.getMethodParameters(method);
1856
789
  for (const param of methodParams) {
1857
790
  text += helpers.formatCommentAsBulletItem(param.name, param.docs);
1858
791
  }
1859
- text += `func ${getClientReceiverDefinition(method.receiver)} ${fixUpMethodName(method)}(${params}) (${returns.join(", ")}) {\n`;
792
+ text += `func ${helpers.getClientReceiverDefinition(method.receiver)} ${helpers.fixUpMethodName(method)}(${params}) (${returns.join(", ")}) {\n`;
1860
793
  let pollerType = "nil";
1861
794
  let pollerTypeParam = `[${method.returns.name}]`;
1862
795
  if (method.kind === "lroPageableMethod") {
@@ -1958,25 +891,4 @@ function generateLROBeginMethod(method, options, imports, indent) {
1958
891
  text += "}\n\n";
1959
892
  return text;
1960
893
  }
1961
- export function fixUpMethodName(method) {
1962
- switch (method.kind) {
1963
- case "lroMethod":
1964
- case "lroPageableMethod":
1965
- return `Begin${method.name}`;
1966
- case "pageableMethod": {
1967
- let N = "N";
1968
- let name = method.name;
1969
- if (method.name[0] !== method.name[0].toUpperCase()) {
1970
- // the method isn't exported; don't export the pager ctor
1971
- N = "n";
1972
- // ensure correct casing of the emitted function name e.g.,
1973
- // "listThings" -> "newListThingsPager"
1974
- name = name[0].toUpperCase() + name.substring(1);
1975
- }
1976
- return `${N}ew${name}Pager`;
1977
- }
1978
- case "method":
1979
- return method.name;
1980
- }
1981
- }
1982
894
  //# sourceMappingURL=operations.js.map