Skip to content

Commit f7398b8

Browse files
authored
refactor(cosmosgen): wire ts generic template (#4725)
1 parent 40bbde0 commit f7398b8

File tree

8 files changed

+44
-138
lines changed

8 files changed

+44
-138
lines changed

changelog.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
### Fixes
1111

12-
- [#4691](https://github.com/ignite/cli/pull/4691), [#4706](https://github.com/ignite/cli/pull/4706) Fix ts-client query template and solely Go template for `ts-client` generation.
12+
- [#4691](https://github.com/ignite/cli/pull/4691), [#4706](https://github.com/ignite/cli/pull/4706), [#4725](https://github.com/ignite/cli/pull/4725) Fix ts-client query template and solely Go template for `ts-client` generation.
1313

1414
## [`v29.0.0`](https://github.com/ignite/cli/releases/tag/v29.0.0)
1515

ignite/pkg/cosmosanalysis/module/module.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,9 @@ type HTTPQuery struct {
5858
// Name of the RPC func.
5959
Name string `json:"name,omitempty"`
6060

61+
// RequestType is the type of the request.
62+
RequestType string `json:"request_type,omitempty"`
63+
6164
// ResponseType is the type of the response.
6265
ResponseType string `json:"response_type,omitempty"`
6366

@@ -303,6 +306,7 @@ func (d *moduleDiscoverer) discover(pkg protoanalysis.Package) (Module, error) {
303306
Rules: q.HTTPRules,
304307
Paginated: isPaginated,
305308
FilePath: pkgmsg.Path,
309+
RequestType: q.RequestType,
306310
ResponseType: q.ReturnsType,
307311
})
308312
}

ignite/pkg/cosmosanalysis/module/module_test.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,7 @@ func newModule(relChainPath, goImportPath string) module.Module {
156156
{
157157
Name: "MyQuery",
158158
FullName: "QueryMyQuery",
159+
RequestType: "QueryMyQueryRequest",
159160
ResponseType: "QueryMyQueryResponse",
160161
Rules: []protoanalysis.HTTPRule{
161162
{
@@ -174,6 +175,7 @@ func newModule(relChainPath, goImportPath string) module.Module {
174175
{
175176
Name: "Foo",
176177
FullName: "QueryFoo",
178+
RequestType: "QueryFooRequest",
177179
ResponseType: "QueryFooResponse",
178180
Rules: []protoanalysis.HTTPRule{
179181
{

ignite/pkg/cosmosgen/template.go

Lines changed: 9 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,8 @@ package cosmosgen
22

33
import (
44
"embed"
5-
"fmt"
65
"os"
76
"path/filepath"
8-
"sort"
97
"strings"
108
"text/template"
119

@@ -87,50 +85,17 @@ func (t templateWriter) Write(destDir, protoPath string, data interface{}) error
8785
path = strings.ReplaceAll(path, "=**}", "}")
8886
return path
8987
},
90-
"mapToTypeScriptObject": func(m map[string]string) string {
91-
// mapToTypeScriptObject converts a map to a TypeScript object string.
92-
// e.g. {"key1"?: value1; "key2"?: value2}
93-
94-
sortedKeys := make([]string, 0, len(m))
95-
for k := range m {
96-
sortedKeys = append(sortedKeys, k)
88+
"transformParamsToUnion": func(params []string) string {
89+
if len(params) == 0 {
90+
return `""`
9791
}
98-
sort.Strings(sortedKeys)
99-
100-
var sb strings.Builder
101-
sb.WriteString("{")
102-
sb.WriteString("\n")
103-
for _, k := range sortedKeys {
104-
typeStr := m[k]
105-
106-
if strings.Contains(typeStr, ".") {
107-
// TODO(@julienrbrt): parse proto types to deepest inner type and remove hardcoded pagination types.
108-
if strings.Contains(typeStr, ".") {
109-
if strings.EqualFold(typeStr, "cosmos.base.query.v1beta1.PageRequest") {
110-
sb.WriteString(` "pagination.key"?: string;`)
111-
sb.WriteString("\n")
112-
sb.WriteString(` "pagination.offset"?: string;`)
113-
sb.WriteString("\n")
114-
sb.WriteString(` "pagination.limit"?: string;`)
115-
sb.WriteString("\n")
116-
sb.WriteString(` "pagination.count_total"?: boolean;`)
117-
sb.WriteString("\n")
118-
sb.WriteString(` "pagination.reverse"?: boolean;`)
119-
sb.WriteString("\n")
120-
continue
121-
}
122-
123-
sb.WriteString(fmt.Sprintf(` "%s"?: any /* TODO */;`, k))
124-
sb.WriteString("\n")
125-
continue
126-
}
127-
}
128-
129-
sb.WriteString(fmt.Sprintf(` "%s"?: %s;`, k, protoTypeToTypeScriptType(typeStr)))
130-
sb.WriteString("\n")
92+
93+
var quotedParams []string
94+
for _, param := range params {
95+
quotedParams = append(quotedParams, `"`+param+`"`)
13196
}
132-
sb.WriteString(" }")
133-
return sb.String()
97+
98+
return strings.Join(quotedParams, " | ")
13499
},
135100
"inc": func(i int) int {
136101
return i + 1
@@ -167,31 +132,3 @@ func (t templateWriter) Write(destDir, protoPath string, data interface{}) error
167132

168133
return nil
169134
}
170-
171-
// protoTypeToTypeScriptType converts a proto type string to a TypeScript type string.
172-
// e.g. "string" -> "string", "int32" -> "number", "bool" -> "boolean", "bytes" -> "Uint8Array", etc.
173-
func protoTypeToTypeScriptType(pt string) string {
174-
isRepeated := strings.HasPrefix(pt, "repeated ")
175-
if isRepeated {
176-
pt = strings.TrimPrefix(pt, "repeated ")
177-
}
178-
179-
var tsBaseType string
180-
switch pt {
181-
case "string":
182-
tsBaseType = "string"
183-
case "int32", "int64", "uint32", "uint64", "sint32", "sint64", "fixed32", "fixed64", "sfixed32", "sfixed64", "float", "double":
184-
tsBaseType = "number"
185-
case "bool":
186-
tsBaseType = "boolean"
187-
case "bytes":
188-
tsBaseType = "Uint8Array"
189-
default:
190-
tsBaseType = pt
191-
}
192-
193-
if isRepeated {
194-
return tsBaseType + "[]"
195-
}
196-
return tsBaseType
197-
}

ignite/pkg/cosmosgen/templates/rest/rest.ts.tpl

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, ResponseType } from "axios";
22
{{ range .HTTPQueries }}import { {{ .ResponseType }} } from "{{ resolveFile .FilePath }}";
33
{{ end }}
4-
// Import relevant Request types here
4+
{{ range .HTTPQueries }}import { {{ .RequestType }} } from "{{ resolveFile .FilePath }}";
5+
{{ end }}
56

67
import type {SnakeCasedPropertiesDeep} from 'type-fest';
78

@@ -203,9 +204,7 @@ export class Api<SecurityDataType extends unknown> extends HttpClient<SecurityDa
203204
{{- if (index .Rules 0).Params }}
204205
{{- range $i, $param := (index .Rules 0).Params }}{{ if $i }}, {{ end }}{{ $param }}: string{{- end }},
205206
{{- end }}{{- if gt (len (index .Rules 0).QueryFields) 0 }}
206-
query?: {{ mapToTypeScriptObject (index .Rules 0).QueryFields }},
207-
// query should be typed as e.g. Omit<FlattenObject<SnakeCasedPropertiesDeep<ChangeProtoToJSPrimitives<QueryAllBalancesRequest>>>,"address">
208-
// i.e. the generated Request type as menioned above and omit the keys in Params as a union (key1 | key2 | key3 etc.)
207+
query?: Omit<FlattenObject<SnakeCasedPropertiesDeep<ChangeProtoToJSPrimitives<{{ .RequestType }}>>>,{{ transformParamsToUnion (index .Rules 0).Params }}>,
209208
{{- else}}
210209
query?: Record<string, any>,
211210
{{- end}}

ignite/pkg/cosmosgen/testdata/expected_files/ts-client/mars/rest.ts

Lines changed: 12 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,12 @@ import { QueryWithPaginationResponse } from "./types/planet/mars/mars";
55
import { QueryWithQueryParamsResponse } from "./types/planet/mars/mars";
66
import { QueryWithQueryParamsWithPaginationResponse } from "./types/planet/mars/mars";
77

8-
// Import relevant Request types here
8+
import { QuerySimpleRequest } from "./types/planet/mars/mars";
9+
import { QuerySimpleParamsRequest } from "./types/planet/mars/mars";
10+
import { QueryWithPaginationRequest } from "./types/planet/mars/mars";
11+
import { QueryWithQueryParamsRequest } from "./types/planet/mars/mars";
12+
import { QueryWithQueryParamsWithPaginationRequest } from "./types/planet/mars/mars";
13+
914

1015
import type {SnakeCasedPropertiesDeep} from 'type-fest';
1116

@@ -241,15 +246,7 @@ export class Api<SecurityDataType extends unknown> extends HttpClient<SecurityDa
241246
* @request GET:/ignite/mars/query_with_params/{mytypefield}
242247
*/
243248
queryQueryParamsWithPagination = (mytypefield: string,
244-
query?: {
245-
"pagination.key"?: string;
246-
"pagination.offset"?: string;
247-
"pagination.limit"?: string;
248-
"pagination.count_total"?: boolean;
249-
"pagination.reverse"?: boolean;
250-
},
251-
// query should be typed as e.g. Omit<FlattenObject<SnakeCasedPropertiesDeep<ChangeProtoToJSPrimitives<QueryAllBalancesRequest>>>,"address">
252-
// i.e. the generated Request type as menioned above and omit the keys in Params as a union (key1 | key2 | key3 etc.)
249+
query?: Omit<FlattenObject<SnakeCasedPropertiesDeep<ChangeProtoToJSPrimitives<QueryWithPaginationRequest>>>,"mytypefield">,
253250
params: RequestParams = {},
254251
) =>
255252
this.request<SnakeCasedPropertiesDeep<ChangeProtoToJSPrimitives<QueryWithPaginationResponse>>>({
@@ -265,20 +262,14 @@ export class Api<SecurityDataType extends unknown> extends HttpClient<SecurityDa
265262
*
266263
* @tags Query
267264
* @name queryQueryWithQueryParams
268-
* @request GET:/ignite/mars/query_with_query_params/{mytypefield}
265+
* @request GET:/ignite/mars/query_with_query_params/{mytypefield}/{mybool}
269266
*/
270-
queryQueryWithQueryParams = (mytypefield: string,
271-
query?: {
272-
"mybool"?: boolean;
273-
"myrepeatedbool"?: boolean[];
274-
"query_param"?: string;
275-
},
276-
// query should be typed as e.g. Omit<FlattenObject<SnakeCasedPropertiesDeep<ChangeProtoToJSPrimitives<QueryAllBalancesRequest>>>,"address">
277-
// i.e. the generated Request type as menioned above and omit the keys in Params as a union (key1 | key2 | key3 etc.)
267+
queryQueryWithQueryParams = (mytypefield: string, mybool: string,
268+
query?: Omit<FlattenObject<SnakeCasedPropertiesDeep<ChangeProtoToJSPrimitives<QueryWithQueryParamsRequest>>>,"mytypefield" | "mybool">,
278269
params: RequestParams = {},
279270
) =>
280271
this.request<SnakeCasedPropertiesDeep<ChangeProtoToJSPrimitives<QueryWithQueryParamsResponse>>>({
281-
path: `/ignite/mars/query_with_query_params/${mytypefield}`,
272+
path: `/ignite/mars/query_with_query_params/${mytypefield}/${mybool}`,
282273
method: "GET",
283274
query: query,
284275
format: "json",
@@ -293,16 +284,7 @@ export class Api<SecurityDataType extends unknown> extends HttpClient<SecurityDa
293284
* @request GET:/ignite/mars/query_with_query_params/{mytypefield}
294285
*/
295286
queryQueryWithQueryParamsWithPagination = (mytypefield: string,
296-
query?: {
297-
"pagination.key"?: string;
298-
"pagination.offset"?: string;
299-
"pagination.limit"?: string;
300-
"pagination.count_total"?: boolean;
301-
"pagination.reverse"?: boolean;
302-
"query_param"?: string;
303-
},
304-
// query should be typed as e.g. Omit<FlattenObject<SnakeCasedPropertiesDeep<ChangeProtoToJSPrimitives<QueryAllBalancesRequest>>>,"address">
305-
// i.e. the generated Request type as menioned above and omit the keys in Params as a union (key1 | key2 | key3 etc.)
287+
query?: Omit<FlattenObject<SnakeCasedPropertiesDeep<ChangeProtoToJSPrimitives<QueryWithQueryParamsWithPaginationRequest>>>,"mytypefield">,
306288
params: RequestParams = {},
307289
) =>
308290
this.request<SnakeCasedPropertiesDeep<ChangeProtoToJSPrimitives<QueryWithQueryParamsWithPaginationResponse>>>({

ignite/pkg/cosmosgen/testdata/testchain/proto/planet/mars/mars.proto

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ service Query {
4141
}
4242

4343
rpc QueryWithQueryParams(QueryWithQueryParamsRequest) returns (QueryWithQueryParamsResponse) {
44-
option (google.api.http).get = "/ignite/mars/query_with_query_params/{mytypefield}";
44+
option (google.api.http).get = "/ignite/mars/query_with_query_params/{mytypefield}/{mybool}";
4545
}
4646

4747
rpc QueryWithQueryParamsWithPagination(QueryWithQueryParamsWithPaginationRequest) returns (QueryWithQueryParamsWithPaginationResponse) {

ignite/pkg/cosmosgen/testdata/testchain/ts-client/mars/rest.ts

Lines changed: 12 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,12 @@ import { QueryWithPaginationResponse } from "./types/planet/mars/mars";
55
import { QueryWithQueryParamsResponse } from "./types/planet/mars/mars";
66
import { QueryWithQueryParamsWithPaginationResponse } from "./types/planet/mars/mars";
77

8-
// Import relevant Request types here
8+
import { QuerySimpleRequest } from "./types/planet/mars/mars";
9+
import { QuerySimpleParamsRequest } from "./types/planet/mars/mars";
10+
import { QueryWithPaginationRequest } from "./types/planet/mars/mars";
11+
import { QueryWithQueryParamsRequest } from "./types/planet/mars/mars";
12+
import { QueryWithQueryParamsWithPaginationRequest } from "./types/planet/mars/mars";
13+
914

1015
import type {SnakeCasedPropertiesDeep} from 'type-fest';
1116

@@ -241,15 +246,7 @@ export class Api<SecurityDataType extends unknown> extends HttpClient<SecurityDa
241246
* @request GET:/ignite/mars/query_with_params/{mytypefield}
242247
*/
243248
queryQueryParamsWithPagination = (mytypefield: string,
244-
query?: {
245-
"pagination.key"?: string;
246-
"pagination.offset"?: string;
247-
"pagination.limit"?: string;
248-
"pagination.count_total"?: boolean;
249-
"pagination.reverse"?: boolean;
250-
},
251-
// query should be typed as e.g. Omit<FlattenObject<SnakeCasedPropertiesDeep<ChangeProtoToJSPrimitives<QueryAllBalancesRequest>>>,"address">
252-
// i.e. the generated Request type as menioned above and omit the keys in Params as a union (key1 | key2 | key3 etc.)
249+
query?: Omit<FlattenObject<SnakeCasedPropertiesDeep<ChangeProtoToJSPrimitives<QueryWithPaginationRequest>>>,"mytypefield">,
253250
params: RequestParams = {},
254251
) =>
255252
this.request<SnakeCasedPropertiesDeep<ChangeProtoToJSPrimitives<QueryWithPaginationResponse>>>({
@@ -265,20 +262,14 @@ export class Api<SecurityDataType extends unknown> extends HttpClient<SecurityDa
265262
*
266263
* @tags Query
267264
* @name queryQueryWithQueryParams
268-
* @request GET:/ignite/mars/query_with_query_params/{mytypefield}
265+
* @request GET:/ignite/mars/query_with_query_params/{mytypefield}/{mybool}
269266
*/
270-
queryQueryWithQueryParams = (mytypefield: string,
271-
query?: {
272-
"mybool"?: boolean;
273-
"myrepeatedbool"?: boolean[];
274-
"query_param"?: string;
275-
},
276-
// query should be typed as e.g. Omit<FlattenObject<SnakeCasedPropertiesDeep<ChangeProtoToJSPrimitives<QueryAllBalancesRequest>>>,"address">
277-
// i.e. the generated Request type as menioned above and omit the keys in Params as a union (key1 | key2 | key3 etc.)
267+
queryQueryWithQueryParams = (mytypefield: string, mybool: string,
268+
query?: Omit<FlattenObject<SnakeCasedPropertiesDeep<ChangeProtoToJSPrimitives<QueryWithQueryParamsRequest>>>,"mytypefield" | "mybool">,
278269
params: RequestParams = {},
279270
) =>
280271
this.request<SnakeCasedPropertiesDeep<ChangeProtoToJSPrimitives<QueryWithQueryParamsResponse>>>({
281-
path: `/ignite/mars/query_with_query_params/${mytypefield}`,
272+
path: `/ignite/mars/query_with_query_params/${mytypefield}/${mybool}`,
282273
method: "GET",
283274
query: query,
284275
format: "json",
@@ -293,16 +284,7 @@ export class Api<SecurityDataType extends unknown> extends HttpClient<SecurityDa
293284
* @request GET:/ignite/mars/query_with_query_params/{mytypefield}
294285
*/
295286
queryQueryWithQueryParamsWithPagination = (mytypefield: string,
296-
query?: {
297-
"pagination.key"?: string;
298-
"pagination.offset"?: string;
299-
"pagination.limit"?: string;
300-
"pagination.count_total"?: boolean;
301-
"pagination.reverse"?: boolean;
302-
"query_param"?: string;
303-
},
304-
// query should be typed as e.g. Omit<FlattenObject<SnakeCasedPropertiesDeep<ChangeProtoToJSPrimitives<QueryAllBalancesRequest>>>,"address">
305-
// i.e. the generated Request type as menioned above and omit the keys in Params as a union (key1 | key2 | key3 etc.)
287+
query?: Omit<FlattenObject<SnakeCasedPropertiesDeep<ChangeProtoToJSPrimitives<QueryWithQueryParamsWithPaginationRequest>>>,"mytypefield">,
306288
params: RequestParams = {},
307289
) =>
308290
this.request<SnakeCasedPropertiesDeep<ChangeProtoToJSPrimitives<QueryWithQueryParamsWithPaginationResponse>>>({

0 commit comments

Comments
 (0)