-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate-crud-config.ts
More file actions
306 lines (264 loc) · 9.17 KB
/
generate-crud-config.ts
File metadata and controls
306 lines (264 loc) · 9.17 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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
import type { OpenAPIV3_1 } from 'openapi-types'
import type { CrudConfig, CrudField } from './crud-types'
import { parseCrudConfigsFromMultiple } from './parse-crud-tags'
import { wrapInterfaceKeyGuard } from './wrap-interface-key-guard'
/**
* Convert string to PascalCase for component names
*/
function toPascalCase(str: string): string {
return str
.split(/[-_]/)
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join('')
}
/**
* Convert string to title case for labels
*/
function toTitleCase(str: string): string {
return str
.replace(/([A-Z])/g, ' $1')
.replace(/[-_]/g, ' ')
.trim()
.split(' ')
.map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
.join(' ')
}
/**
* Get input type from field type and format
*/
function getInputType(field: CrudField): string {
if (field.format === 'email') return 'email'
if (field.format === 'uri' || field.format === 'url') return 'url'
if (field.format === 'date') return 'date'
if (field.format === 'date-time') return 'datetime-local'
if (field.format === 'time') return 'time'
if (field.format === 'password') return 'password'
if (field.type === 'number' || field.type === 'integer') return 'number'
return 'text'
}
/**
* Generate register options for a field
*/
function generateRegisterOptions(field: CrudField): string {
const options: string[] = []
if (field.required) options.push('required: true')
if (field.minLength !== undefined)
options.push(`minLength: ${field.minLength}`)
if (field.maxLength !== undefined)
options.push(`maxLength: ${field.maxLength}`)
if (field.minimum !== undefined) options.push(`min: ${field.minimum}`)
if (field.maximum !== undefined) options.push(`max: ${field.maximum}`)
if (field.pattern) options.push(`pattern: /${field.pattern}/`)
if (field.type === 'number' || field.type === 'integer') {
options.push('valueAsNumber: true')
}
return options.length > 0 ? `{ ${options.join(', ')} }` : ''
}
/**
* Generate JSX for a single field using useFormContext
*/
function generateFieldJsx(field: CrudField, indent: string): string[] {
const lines: string[] = []
const inputType = getInputType(field)
const label = toTitleCase(field.name)
const registerOpts = generateRegisterOptions(field)
const registerCall = registerOpts
? `register('${field.name}', ${registerOpts})`
: `register('${field.name}')`
// Handle select for enum fields
if (field.enum && field.enum.length > 0) {
lines.push(`${indent}<div>`)
lines.push(`${indent} <label htmlFor="${field.name}">${label}</label>`)
lines.push(`${indent} <select id="${field.name}" {...${registerCall}}>`)
lines.push(`${indent} <option value="">Select...</option>`)
for (const value of field.enum) {
lines.push(
`${indent} <option value="${value}">${toTitleCase(value)}</option>`,
)
}
lines.push(`${indent} </select>`)
lines.push(`${indent} {errors.${field.name} && <span>Invalid</span>}`)
lines.push(`${indent}</div>`)
return lines
}
// Handle boolean as checkbox
if (field.type === 'boolean') {
lines.push(`${indent}<div>`)
lines.push(`${indent} <label>`)
lines.push(`${indent} <input type="checkbox" {...${registerCall}} />`)
lines.push(`${indent} ${label}`)
lines.push(`${indent} </label>`)
lines.push(`${indent} {errors.${field.name} && <span>Invalid</span>}`)
lines.push(`${indent}</div>`)
return lines
}
// Default input
lines.push(`${indent}<div>`)
lines.push(`${indent} <label htmlFor="${field.name}">${label}</label>`)
lines.push(`${indent} <input`)
lines.push(`${indent} id="${field.name}"`)
lines.push(`${indent} type="${inputType}"`)
lines.push(`${indent} {...${registerCall}}`)
if (field.description) {
lines.push(`${indent} placeholder="${field.description}"`)
}
lines.push(`${indent} />`)
lines.push(
`${indent} {errors.${field.name} && <span>${field.required ? 'Required' : 'Invalid'}</span>}`,
)
lines.push(`${indent}</div>`)
return lines
}
/**
* Generate the Fields component for a CRUD group
*/
function generateFieldsComponent(
componentName: string,
fields: CrudField[],
): string[] {
const lines: string[] = []
const fieldsComponentName = `${componentName}Fields`
lines.push(`function ${fieldsComponentName}() {`)
lines.push(` const { register, formState: { errors } } = useFormContext();`)
lines.push('')
lines.push(' return (')
lines.push(' <>')
// Generate fields
if (fields.length > 0) {
for (const field of fields) {
const fieldLines = generateFieldJsx(field, ' ')
lines.push(...fieldLines)
}
} else {
lines.push(' {/* No fields defined in OpenAPI schema */}')
}
// Submit button
lines.push('')
lines.push(' <button type="submit">Submit</button>')
lines.push(' </>')
lines.push(' );')
lines.push('}')
return lines
}
/**
* Generate the main CRUD component using ApiForm
*/
function generateCrudComponent(name: string, config: CrudConfig): string[] {
const lines: string[] = []
const componentName = `${toPascalCase(name)}Crud`
const fieldsComponentName = `${componentName}Fields`
// Determine edit method and operationId
const editEndpoint = config.edit ?? config.fix
const editMethod = editEndpoint?.method ?? 'put'
const editOperationId = editEndpoint?.operationId
lines.push(`export function ${componentName}({`)
lines.push(' apiClient,')
lines.push(' params,')
lines.push(' onSuccess,')
lines.push(' onError,')
lines.push('}) {')
lines.push(' const isEdit = !!params;')
lines.push('')
// Build ApiForm props dynamically
lines.push(' return (')
lines.push(' <ApiForm')
lines.push(' api={apiClient}')
lines.push(` method={isEdit ? '${editMethod}' : 'post'}`)
// Path uses operationId
if (editOperationId) {
lines.push(
` path={isEdit ? '${editOperationId}' : '${config.create.operationId}'}`,
)
} else {
lines.push(` path={'${config.create.operationId}'}`)
}
lines.push(' requestOptions={isEdit ? { params } : undefined}')
// Fetch default values for edit mode
lines.push(' fetchDefaultValues={isEdit ? {')
lines.push(` path: '${config.one.operationId}',`)
lines.push(' options: { params },')
lines.push(' } : undefined}')
lines.push(' onSuccess={onSuccess}')
lines.push(' onError={onError}')
lines.push(' >')
lines.push(` <${fieldsComponentName} />`)
lines.push(' </ApiForm>')
lines.push(' );')
lines.push('}')
return lines
}
/**
* Generate the virtual module code for CRUD components with full UI
*/
export function generateCrudConfigCode(
schemas: Record<string, OpenAPIV3_1.Document>,
): string {
const configs = parseCrudConfigsFromMultiple(schemas)
const lines: string[] = []
// Header
lines.push('// Auto-generated CRUD components from OpenAPI specs')
lines.push('// Do not edit this file directly')
lines.push("'use client';")
lines.push('')
// Imports - use @devup-api/hookform
lines.push("import { ApiForm, useFormContext } from '@devup-api/hookform';")
lines.push('')
// Generate component for each CRUD group
for (const [name, config] of Object.entries(configs)) {
const componentName = `${toPascalCase(name)}Crud`
// Get fields from create endpoint (primary form fields)
const fields = config.create.fields ?? []
lines.push(`// ============================================`)
lines.push(`// ${componentName}`)
lines.push(`// ============================================`)
lines.push('')
// Generate Fields component
const fieldsLines = generateFieldsComponent(componentName, fields)
lines.push(...fieldsLines)
lines.push('')
// Generate main CRUD component
const componentLines = generateCrudComponent(name, config)
lines.push(...componentLines)
lines.push('')
}
// Default export
lines.push('export default {')
for (const name of Object.keys(configs)) {
const componentName = `${toPascalCase(name)}Crud`
lines.push(` ${name}: ${componentName},`)
}
lines.push('};')
return lines.join('\n')
}
/**
* Generate TypeScript type declarations for CRUD components
* Uses module augmentation to extend DevupCrudApiNames in @devup-api/ui
*/
export function generateCrudConfigTypes(
schemas: Record<string, OpenAPIV3_1.Document>,
): string {
const configs = parseCrudConfigsFromMultiple(schemas)
const apiNames = Object.keys(configs)
const lines: string[] = []
lines.push("import '@devup-api/ui'")
lines.push('')
// Module augmentation for DevupCrudApiNames
if (apiNames.length > 0) {
lines.push("declare module '@devup-api/ui' {")
lines.push(' interface DevupCrudApiNames {')
for (const name of apiNames) {
lines.push(` ${wrapInterfaceKeyGuard(name)}: true`)
}
lines.push(' }')
lines.push('}')
lines.push('')
}
// Virtual module declaration
lines.push("declare module '@devup-api/ui/crud' {")
lines.push(" import type { CrudComponents } from '@devup-api/ui'")
lines.push('')
lines.push(' const crudComponents: CrudComponents')
lines.push(' export default crudComponents')
lines.push('}')
return lines.join('\n')
}