Skip to content

Commit

Permalink
feat(go): parameter arguments for request creation improved with all … (
Browse files Browse the repository at this point in the history
#1535)

…required params

## 🧭 What and Why

🎟 JIRA Ticket: https://algolia.atlassian.net/browse/APIC-676

When creating a request instance to pass we are expecting only path params and some required params was needed set with ".With{{Param}}()" syntax.  

### Changes included:

- Instead of just path parameters we are expecting all required params when instantiating.
- For some rare requests, there is no param at all. It is handled to not expect an empty request instance.
- Playground examples are updated with the new generation. 

## 🧪 Test

CI should pass and playground examples can be tried without an issue.
  • Loading branch information
mehmetaligok authored May 11, 2023
1 parent 966491b commit fe7057d
Show file tree
Hide file tree
Showing 9 changed files with 43 additions and 20 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ public void run(Map<String, CodegenModel> models, Map<String, CodegenOperation>
test.put("request", req.request);
test.put("hasParameters", req.parameters.size() != 0);
test.put("extras", req.extras);
test.put("hasOperationParams", ope.hasParams);

if (req.requestOptions != null) {
test.put("hasRequestOptions", true);
Expand Down
2 changes: 1 addition & 1 deletion playground/go/analytics.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ func testAnalytics(appID, apiKey string) int {
analyticsClient := analytics.NewClient(appID, apiKey, analytics.US)

getTopFilterForAttributeResponse, err := analyticsClient.GetTopFilterForAttribute(
analyticsClient.NewApiGetTopFilterForAttributeRequest("myAttribute1,myAttribute2").WithIndex(indexName),
analyticsClient.NewApiGetTopFilterForAttributeRequest("myAttribute1,myAttribute2", indexName),
)
if err != nil {
fmt.Printf("request error with GetTopFilterForAttribute: %v\n", err)
Expand Down
21 changes: 21 additions & 0 deletions playground/go/ingestion.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,34 @@ package main

import (
"fmt"
"time"

"github.com/algolia/algoliasearch-client-go/v4/algolia/ingestion"
)

func testIngestion(appID, apiKey string) int {
ingestionClient := ingestion.NewClient(appID, apiKey, ingestion.US)

// another example to generate payload for a request.
createAuthenticationResponse, err := ingestionClient.CreateAuthentication(ingestionClient.NewApiCreateAuthenticationRequest(
&ingestion.AuthenticationCreate{
Type: ingestion.AUTHENTICATIONTYPE_BASIC,
Name: fmt.Sprintf("my-authentication-%d", time.Now().Unix()),
Input: ingestion.AuthInput{
AuthBasic: &ingestion.AuthBasic{
Username: "username",
Password: "password",
},
},
}))

if err != nil {
fmt.Printf("request error with CreateAuthentication: %v\n", err)
return 1
}

printResponse(createAuthenticationResponse)

listAuthenticationsResponse, err := ingestionClient.GetAuthentications(
ingestionClient.NewApiGetAuthenticationsRequest().WithItemsPerPage(2),
)
Expand Down
2 changes: 1 addition & 1 deletion playground/go/insights.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ func testInsights(appID, apiKey string) int {
insights.WithInsightEventQueryID("myQueryID")),
})
pushEventsResponse, err := insightsClient.PushEvents(
insightsClient.NewApiPushEventsRequest().WithInsightEvents(events),
insightsClient.NewApiPushEventsRequest(events),
)
if err != nil {
fmt.Printf("request error with PushEvents: %v\n", err)
Expand Down
2 changes: 1 addition & 1 deletion playground/go/predict.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ func testPredict(appID, apiKey string) int {
predict.WithAllParamsTypesToRetrieve(predict.AllowedTypesToRetrieveEnumValues),
))
userProfile, err := predictClient.FetchUserProfile(
predictClient.NewApiFetchUserProfileRequest("userId").WithParams(&params),
predictClient.NewApiFetchUserProfileRequest("userId", &params),
)
if err != nil {
fmt.Printf("request error with FetchUserProfile: %v\n", err)
Expand Down
5 changes: 2 additions & 3 deletions playground/go/query-suggestions.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,8 @@ import (
func testQuerySuggestions(appID, apiKey string) int {
suggestionsClient := suggestions.NewClient(appID, apiKey, suggestions.US)

querySuggestionsIndex, err := suggestionsClient.GetAllConfigs(
suggestionsClient.NewApiGetAllConfigsRequest(),
)
// if there is no params for the requests, we don't need to give empty request instance such as `suggestionsClient.NewApiGetAllConfigsRequest()`.
querySuggestionsIndex, err := suggestionsClient.GetAllConfigs()
if err != nil {
fmt.Printf("request error with GetAllConfigs: %v\n", err)
return 1
Expand Down
4 changes: 2 additions & 2 deletions playground/go/recommend.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ func testRecommend(appID, apiKey string) int {
})
*/
// alternative way to create the payloads, a similar approach can be used with any of the other clients
params := recommend.GetRecommendationsParams{
params := &recommend.GetRecommendationsParams{
Requests: []recommend.RecommendationsRequest{
{
RecommendationRequest: &recommend.RecommendationRequest{
Expand All @@ -29,7 +29,7 @@ func testRecommend(appID, apiKey string) int {
}

searchResponse, err := recommendClient.GetRecommendations(
recommendClient.NewApiGetRecommendationsRequest().WithGetRecommendationsParams(&params),
recommendClient.NewApiGetRecommendationsRequest(params),
)
if err != nil {
fmt.Printf("request error with SearchSingleIndex: %v\n", err)
Expand Down
22 changes: 11 additions & 11 deletions templates/go/api.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ func HeaderParamOption(name string, val any) Option {
}

{{#operation}}

{{#hasParams}}
type {{#structPrefix}}{{&classname}}{{/structPrefix}}{{^structPrefix}}Api{{/structPrefix}}{{operationId}}Request struct {
{{#allParams}}
{{paramName}} {{^isPathParam}}{{^isFreeFormObject}}{{^isArray}}{{^isPrimitiveType}}*{{/isPrimitiveType}}{{/isArray}}{{/isFreeFormObject}}{{/isPathParam}}{{{dataType}}}
Expand All @@ -51,7 +51,7 @@ func (r *{{#structPrefix}}{{&classname}}{{/structPrefix}}{{^structPrefix}}Api{{/
return err
}
{{#allParams}}
if v, ok := req["{{#isQueryParam}}{{baseName}}{{/isQueryParam}}{{^isQueryParam}}{{paramName}}{{/isQueryParam}}"]; ok { //{{paramName}}
if v, ok := req["{{#isQueryParam}}{{baseName}}{{/isQueryParam}}{{^isQueryParam}}{{paramName}}{{/isQueryParam}}"]; ok {
err = json.Unmarshal(v, &r.{{paramName}})
if err != nil {
err = json.Unmarshal(b, &r.{{paramName}})
Expand All @@ -71,7 +71,7 @@ func (r *{{#structPrefix}}{{&classname}}{{/structPrefix}}{{^structPrefix}}Api{{/
}

{{#allParams}}
{{^isPathParam}}
{{^required}}
{{#description}}
// {{.}}
{{/description}}
Expand All @@ -83,34 +83,34 @@ func (r {{#structPrefix}}{{&classname}}{{/structPrefix}}{{^structPrefix}}Api{{/s
return r
}

{{/isPathParam}}
{{/required}}
{{/allParams}}
{{#isDeprecated}}
// Deprecated
{{/isDeprecated}}
//@return {{#structPrefix}}{{&classname}}{{/structPrefix}}{{^structPrefix}}Api{{/structPrefix}}{{operationId}}Request
func (c *APIClient) NewApi{{{nickname}}}Request({{#pathParams}} {{paramName}} {{{dataType}}} {{^-last}},{{/-last}}{{/pathParams}}) {{#structPrefix}}{{&classname}}{{/structPrefix}}{{^structPrefix}}Api{{/structPrefix}}{{operationId}}Request {
func (c *APIClient) NewApi{{{nickname}}}Request({{#requiredParams}} {{paramName}} {{^isPathParam}}{{^isFreeFormObject}}{{^isArray}}{{^isPrimitiveType}}*{{/isPrimitiveType}}{{/isArray}}{{/isFreeFormObject}}{{/isPathParam}}{{{dataType}}} {{^-last}},{{/-last}}{{/requiredParams}}) {{#structPrefix}}{{&classname}}{{/structPrefix}}{{^structPrefix}}Api{{/structPrefix}}{{operationId}}Request {
return {{#structPrefix}}{{&classname}}{{/structPrefix}}{{^structPrefix}}Api{{/structPrefix}}{{operationId}}Request{
{{#pathParams}}
{{#requiredParams}}
{{paramName}}: {{paramName}},
{{/pathParams}}
{{/requiredParams}}
}
}

{{/hasParams}}
// {{nickname}} wraps {{nickname}}WithContext using context.Background.
{{#isDeprecated}}
// Deprecated
{{/isDeprecated}}
func (c *APIClient) {{nickname}}(r {{#structPrefix}}{{&classname}}{{/structPrefix}}{{^structPrefix}}Api{{/structPrefix}}{{operationId}}Request, opts ...Option) ({{#returnType}}{{^isArray}}{{^returnTypeIsPrimitive}}*{{/returnTypeIsPrimitive}}{{/isArray}}{{{.}}}, {{/returnType}}error) {
return c.{{nickname}}WithContext(context.Background(), r, opts...)
func (c *APIClient) {{nickname}}({{#hasParams}}r {{#structPrefix}}{{&classname}}{{/structPrefix}}{{^structPrefix}}Api{{/structPrefix}}{{operationId}}Request,{{/hasParams}} opts ...Option) ({{#returnType}}{{^isArray}}{{^returnTypeIsPrimitive}}*{{/returnTypeIsPrimitive}}{{/isArray}}{{{.}}}, {{/returnType}}error) {
return c.{{nickname}}WithContext(context.Background(), {{#hasParams}}r,{{/hasParams}} opts...)
}

// {{{description}}}{{#returnType}}
// @return {{{.}}}{{/returnType}}
{{#isDeprecated}}
// Deprecated
{{/isDeprecated}}
func (c *APIClient) {{nickname}}WithContext(ctx context.Context, r {{#structPrefix}}{{&classname}}{{/structPrefix}}{{^structPrefix}}Api{{/structPrefix}}{{operationId}}Request, opts ...Option) ({{#returnType}}{{^isArray}}{{^returnTypeIsPrimitive}}*{{/returnTypeIsPrimitive}}{{/isArray}}{{{.}}}, {{/returnType}}error) {
func (c *APIClient) {{nickname}}WithContext(ctx context.Context, {{#hasParams}}r {{#structPrefix}}{{&classname}}{{/structPrefix}}{{^structPrefix}}Api{{/structPrefix}}{{operationId}}Request,{{/hasParams}} opts ...Option) ({{#returnType}}{{^isArray}}{{^returnTypeIsPrimitive}}*{{/returnTypeIsPrimitive}}{{/isArray}}{{{.}}}, {{/returnType}}error) {
var (
postBody any
{{#returnType}}
Expand Down
4 changes: 3 additions & 1 deletion templates/go/tests/requests/requests.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,11 @@ func Test{{#lambda.titlecase}}{{clientPrefix}}{{/lambda.titlecase}}_{{#lambda.ti
name: "{{{testName}}}",
testFunc: func(t *testing.T) { {{#extras}}{{#skipForGo}}
t.Skip("skipping test for go client"){{/skipForGo}}{{/extras}}
{{#hasOperationParams}}
parametersStr := `{{{parameters}}}`
req := {{clientPrefix}}.Api{{#lambda.titlecase}}{{method}}{{/lambda.titlecase}}Request{}
require.NoError(t, json.Unmarshal([]byte(parametersStr), &req))
{{/hasOperationParams}}
{{#hasRequestOptions}}
var opts []{{clientPrefix}}.Option
{{#requestOptions.queryParameters}}
Expand All @@ -56,7 +58,7 @@ func Test{{#lambda.titlecase}}{{clientPrefix}}{{/lambda.titlecase}}_{{#lambda.ti
}
{{/requestOptions.headers}}
{{/hasRequestOptions}}
_, err := client.{{#lambda.titlecase}}{{method}}{{/lambda.titlecase}}(req{{#hasRequestOptions}}, opts...{{/hasRequestOptions}})
_, err := client.{{#lambda.titlecase}}{{method}}{{/lambda.titlecase}}({{#hasOperationParams}}req{{/hasOperationParams}}{{#hasRequestOptions}}{{#hasOperationParams}},{{/hasOperationParams}} opts...{{/hasRequestOptions}})
require.NoError(t, err)

expectedPath, err := url.QueryUnescape("{{{request.path}}}")
Expand Down

0 comments on commit fe7057d

Please sign in to comment.