-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtmpl.go
More file actions
219 lines (197 loc) · 9.14 KB
/
Copy pathtmpl.go
File metadata and controls
219 lines (197 loc) · 9.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
package main
// TemplateData is the data passed to the template for generating the TypeScript file
type TemplateData struct {
Version string
Timestamp string
Types []TypeInfo
Handlers []HandlerInfo
AuthToken string
AuthTokenStorage string
UseHooks bool
UseReactQuery bool
UseDateObject bool
}
const headerTemplate = `// This file is auto-generated. DO NOT EDIT.
// Generated by go2type {{.Version}} on {{.Timestamp}}
{{$useDateObject := .UseDateObject}}
{{if .UseReactQuery}}
import { useQuery, useMutation, UseQueryOptions, UseMutationOptions, UseMutationResult, UseQueryResult } from '@tanstack/react-query'
{{else if .UseHooks}}
import { useState, useEffect, useCallback } from 'react'
{{end}}
{{if $useDateObject}}// Utility function to parse dates
const parseDate = (dateString: string): Date => new Date(dateString);
{{end}}
// Custom error class for API errors
export class APIError extends Error {
constructor(public status: number, public statusText: string, public data: Record<string, unknown> | string) {
super(` + "`API Error ${status}: ${statusText}`" + `);
this.name = 'APIError';
}
}
`
// Update the template to use the new IsOptional field
const typesTemplate = `{{range .Types}}export type {{firstWord .Name}} = { {{range .Fields}}
{{.Name}}{{if .IsOptional}}?{{end}}: {{.Type}};{{end}}
}
{{end}}
`
const queryFunctionTemplate = `{{$authToken := .AuthToken}}
{{$authTokenStorage := .AuthTokenStorage}}
{{$useDateObject := .UseDateObject}}
// Generic query factory
async function createQuery<TInput, TOutput>(
method: string,
url: string,
input?: TInput,
headers: Record<string, string> = {}
): Promise<TOutput> {
const token = {{$authTokenStorage}}.getItem("{{$authToken}}");
const defaultHeaders: Record<string, string> = {
'Content-Type': 'application/json',
};
if (token) {
headers['Authorization'] = ` + "`Bearer ${token}`" + `;
}
const requestHeaders = { ...defaultHeaders, ...headers };
const requestOptions: RequestInit = {
method,
headers: requestHeaders,
};
if (method !== 'GET' && input) {
requestOptions.body = JSON.stringify(input);
}
try {
const response = await fetch(url, requestOptions);
if (!response.ok) {
let errorData;
try {
errorData = await response.json();
} catch {
errorData = await response.text();
}
throw new APIError(response.status, response.statusText, errorData);
}
const data = await response.json();
{{if $useDateObject}}
// Parse dates in the response
return JSON.parse(JSON.stringify(data), (_, value) =>
typeof value === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(value) ? parseDate(value) : value
) as TOutput;
{{else}}
return data as TOutput;
{{end}}
} catch (error) {
if (error instanceof APIError) {
throw error;
} else if (error instanceof Error) {
throw new APIError(0, 'Network Error', error.message);
} else {
throw new APIError(0, 'Unknown Error', String(error));
}
}
}
{{range .Handlers}}
export const {{.Name}}Query = async ({{if .URLParams}}{{range $index, $param := .URLParams}}{{if $index}}, {{end}}{{$param}}: string{{end}}{{if or .InputType (inputHeaders .Headers)}}, {{end}}{{end}}{{if .InputType}}input: {{.InputType}}{{if inputHeaders .Headers}}, {{end}}{{end}}{{range $index, $header := inputHeaders .Headers}}{{if $index}}, {{end}}{{$header.SafeName}}: string{{end}}): Promise<{{.OutputType}}> => {
{{if .URLParams}}let{{else}}const{{end}} url = '{{.Path}}'
{{range .URLParams}}
url = url.replace(':{{.}}', encodeURIComponent({{.}}))
{{end}}
{{if and (eq .Method "GET") .InputType}}
url += '?' + new URLSearchParams(input as any)
{{end}}
const headers: Record<string, string> = {};
{{range .Headers}}
{{if eq .Source "input"}}
if ({{.SafeName}}) {
headers['{{.HeaderKey}}'] = {{.SafeName}};
}
{{else}}
const {{.SafeName}}Value = {{.Source}}.getItem('{{.StorageKey}}');
if (!{{.SafeName}}Value || {{.SafeName}}Value === "") {
throw new Error('Missing required header: {{.HeaderKey}}');
}
headers['{{.HeaderKey}}'] = {{.SafeName}}Value;
{{end}}
{{end}}
return createQuery<{{if .InputType}}{{.InputType}}{{else}}void{{end}}, {{.OutputType}}>('{{.Method}}', url, {{if .InputType}}input{{else}}undefined{{end}}, headers);
};
{{end}}
`
const reactQueryHookTemplate = `{{range .Handlers}}
// React Query hook
{{if eq .Method "GET"}}
export const use{{.Name}} = (
{{if .URLParams}}{{range $index, $param := .URLParams}}{{if $index}}, {{end}}{{$param}}: string{{end}}{{if or .InputType (inputHeaders .Headers)}}, {{end}}{{end}}{{if .InputType}}input: {{.InputType}}{{if inputHeaders .Headers}}, {{end}}{{end}}
{{range $index, $header := inputHeaders .Headers}}{{if $index}}, {{end}}{{$header.SafeName}}: string{{end}}{{if or .URLParams .InputType (inputHeaders .Headers)}}, {{end}}
options?: Omit<UseQueryOptions<{{.OutputType}}, APIError, {{.OutputType}}, [string{{if .URLParams}}{{range .URLParams}}, string{{end}}{{end}}{{if .InputType}}, {{.InputType}}{{end}}{{range inputHeaders .Headers}}, string{{end}}]>, 'queryKey' | 'queryFn'>
): UseQueryResult<{{.OutputType}}, APIError> =>
useQuery<{{.OutputType}}, APIError, {{.OutputType}}, [string{{if .URLParams}}{{range .URLParams}}, string{{end}}{{end}}{{if .InputType}}, {{.InputType}}{{end}}{{range inputHeaders .Headers}}, string{{end}}]>({
queryKey: ['{{.Name}}'{{if .URLParams}}{{range .URLParams}}, {{.}}{{end}}{{end}}{{if .InputType}}, input{{end}}{{range inputHeaders .Headers}}, {{.SafeName}}{{end}}],
queryFn: () => {{.Name}}Query({{if .URLParams}}{{range $index, $param := .URLParams}}{{if $index}}, {{end}}{{$param}}{{end}}{{if and .URLParams .InputType}}, {{end}}{{end}}{{if .InputType}}input{{if inputHeaders .Headers}}, {{end}}{{end}}{{range $index, $header := inputHeaders .Headers}}{{if $index}}, {{end}}{{$header.SafeName}}{{end}}),
...options,
});
{{else}}
export const use{{.Name}} = (
{{range $index, $param := .URLParams}}{{if $index}}, {{end}}{{$param}}: string{{end}}
{{if inputHeaders .Headers}}{{if .URLParams}}, {{end}}{{range $index, $header := inputHeaders .Headers}}{{if $index}}, {{end}}{{$header.SafeName}}: string{{end}}{{end}}
{{if or .URLParams (inputHeaders .Headers)}}, {{end}}
options?: Omit<UseMutationOptions<{{.OutputType}}, APIError, {{if .InputType}}{{.InputType}}{{else}}void{{end}}, unknown>, 'mutationFn'>
): UseMutationResult<{{.OutputType}}, APIError, {{if .InputType}}{{.InputType}}{{else}}void{{end}}, unknown> =>
useMutation<{{.OutputType}}, APIError, {{if .InputType}}{{.InputType}}{{else}}void{{end}}, unknown>({
mutationFn: ({{if .InputType}}input{{end}}) => {{.Name}}Query(
{{range $index, $param := .URLParams}}{{if $index}}, {{end}}{{$param}}{{end}}
{{if and .URLParams .InputType}}, {{end}}
{{if .InputType}}input{{end}}
{{if inputHeaders .Headers}}{{if or .URLParams .InputType}}, {{end}}{{range $index, $header := inputHeaders .Headers}}{{if $index}}, {{end}}{{$header.SafeName}}{{end}}{{end}}
),
...options,
});
{{end}}
{{end}}
`
const reactHookTemplate = `{{range .Handlers}}
// Custom React hook
export const use{{.Name}} = (
{{if eq .Method "GET"}}{{if .InputType}}input: {{.InputType}},{{end}}{{end}}
{{if .URLParams}}{{range $index, $param := .URLParams}}{{if $index}}, {{end}}{{$param}}: string{{end}}{{if or .InputType (inputHeaders .Headers)}}, {{end}}{{end}}
{{range $index, $header := inputHeaders .Headers}}{{if $index}}, {{end}}{{$header.SafeName}}: string{{end}}
) => {
const [data, setData] = useState<{{.OutputType}} | null>(null);
const [error, setError] = useState<APIError | null>(null);
const [isLoading, setIsLoading] = useState(false);
const {{if eq .Method "GET"}}query = useCallback(async () => {{ "{" }}{{else}}mutate = useCallback(async ({{if .InputType}}input: {{.InputType}},{{end}}) => {{ "{" }}{{end}}
setIsLoading(true);
try {
const result = await {{.Name}}Query(
{{if .URLParams}}{{range $index, $param := .URLParams}}{{if $index}}, {{end}}{{$param}}{{end}}{{if or .InputType (inputHeaders .Headers)}}, {{end}}{{end}}
{{if .InputType}}input{{end}}{{if inputHeaders .Headers}}, {{end}}
{{range $index, $header := inputHeaders .Headers}}{{if $index}}, {{end}}{{$header.SafeName}}{{end}}
);
setData(result);
setError(null);
return result;
} catch (e) {
setError(e as APIError);
setData(null);
throw e;
} finally {
setIsLoading(false);
}
}, [{{if .URLParams}}{{range $index, $param := .URLParams}}{{if $index}}, {{end}}{{$param}}{{end}}{{if or .InputType (inputHeaders .Headers)}}, {{end}}{{end}}{{if and .InputType (eq .Method "GET")}}input{{if inputHeaders .Headers}}, {{end}}{{end}}{{range $index, $header := inputHeaders .Headers}}{{if $index}}, {{end}}{{$header.SafeName}}{{end}}]);
{{if eq .Method "GET"}}
useEffect(() => {
query();
}, [query]);
{{end}}
return { data, error, isLoading, {{if eq .Method "GET"}}query{{else}}mutate{{end}} };
};
{{end}}
`
const queryDictionaryTemplate = `
// Query dictionary
export const queries = {
{{range .Handlers}}{{.Name}}: {{.Name}}Query,
{{end}}
} as const;
`