clear tool generete bpjs
This commit is contained in:
@@ -138,7 +138,7 @@ const handlerTemplate = `
|
||||
// Service: {{.ServiceName}} ({{.Category}})
|
||||
// Description: {{.Description}}
|
||||
|
||||
package handlers
|
||||
package {{.Package}}
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -148,8 +148,7 @@ import (
|
||||
|
||||
"{{.ModuleName}}/internal/config"
|
||||
"{{.ModuleName}}/internal/models"
|
||||
"{{.ModuleName}}/internal/models/vclaim/peserta"
|
||||
"{{.ModuleName}}/internal/models/vclaim/sep"
|
||||
"{{.ModuleName}}/internal/models/vclaim/{{.Package}}"
|
||||
"{{.ModuleName}}/internal/services/bpjs"
|
||||
"{{.ModuleName}}/pkg/logger"
|
||||
|
||||
@@ -184,19 +183,15 @@ func New{{.ServiceName}}Handler(cfg {{.ServiceName}}HandlerConfig) *{{.ServiceNa
|
||||
}
|
||||
{{range .Endpoints}}
|
||||
{{if .HasGet}}
|
||||
// Get{{.NameUpper}} godoc
|
||||
// Get{{.Name}} godoc
|
||||
// @Summary Get {{.Name}} data
|
||||
// @Description {{.Description}}
|
||||
// @Tags {{join .Tags ","}}
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
{{if .RequireAuth}}
|
||||
// @Security ApiKeyAuth
|
||||
{{end}}
|
||||
// @Param X-Request-ID header string false "Request ID for tracking"
|
||||
{{range .PathParams}}
|
||||
// @Param {{.}} path string true "{{.}}" example("example_value")
|
||||
{{end}}
|
||||
// @Produce json {{if .RequireAuth}}
|
||||
// @Security ApiKeyAuth {{end}}
|
||||
// @Param X-Request-ID header string false "Request ID for tracking" {{range .PathParams}}
|
||||
// @Param {{.}} path string true "{{.}}" example("example_value") {{end}}
|
||||
// @Success 200 {object} {{.ModelPackage}}.{{.ResponseModel}} "Successfully retrieved {{.Name}} data"
|
||||
// @Failure 400 {object} models.ErrorResponseBpjs "Bad request - invalid parameters"
|
||||
// @Failure 401 {object} models.ErrorResponseBpjs "Unauthorized - invalid API credentials"
|
||||
@@ -276,15 +271,13 @@ func (h *{{$.ServiceName}}Handler) Get{{.Name}}(c *gin.Context) {
|
||||
{{end}}
|
||||
|
||||
{{if .HasPost}}
|
||||
// Create{{.NameUpper}} godoc
|
||||
// Create{{.Name}} godoc
|
||||
// @Summary Create new {{.Name}}
|
||||
// @Description {{.Description}}
|
||||
// @Tags {{join .Tags ","}}
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
{{if .RequireAuth}}
|
||||
// @Security ApiKeyAuth
|
||||
{{end}}
|
||||
// @Produce json {{if .RequireAuth}}
|
||||
// @Security ApiKeyAuth {{end}}
|
||||
// @Param X-Request-ID header string false "Request ID for tracking"
|
||||
// @Param request body {{.ModelPackage}}.{{.Model}} true "{{.Name}} data"
|
||||
// @Success 201 {object} {{.ModelPackage}}.{{.ResponseModel}} "Successfully created {{.Name}}"
|
||||
@@ -367,19 +360,15 @@ func (h *{{$.ServiceName}}Handler) Create{{.Name}}(c *gin.Context) {
|
||||
{{end}}
|
||||
|
||||
{{if .HasPut}}
|
||||
// Update{{.NameUpper}} godoc
|
||||
// Update{{.Name}} godoc
|
||||
// @Summary Update existing {{.Name}}
|
||||
// @Description {{.Description}}
|
||||
// @Tags {{join .Tags ","}}
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
{{if .RequireAuth}}
|
||||
// @Security ApiKeyAuth
|
||||
{{end}}
|
||||
// @Param X-Request-ID header string false "Request ID for tracking"
|
||||
{{range .PathParams}}
|
||||
// @Param {{.}} path string true "{{.}}" example("example_value")
|
||||
{{end}}
|
||||
// @Produce json {{if .RequireAuth}}
|
||||
// @Security ApiKeyAuth {{end}}
|
||||
// @Param X-Request-ID header string false "Request ID for tracking" {{range .PathParams}}
|
||||
// @Param {{.}} path string true "{{.}}" example("example_value") {{end}}
|
||||
// @Param request body {{.ModelPackage}}.{{.Model}} true "{{.Name}} data"
|
||||
// @Success 200 {object} {{.ModelPackage}}.{{.ResponseModel}} "Successfully updated {{.Name}}"
|
||||
// @Failure 400 {object} models.ErrorResponseBpjs "Bad request - invalid parameters or request body"
|
||||
@@ -486,19 +475,15 @@ func (h *{{$.ServiceName}}Handler) Update{{.Name}}(c *gin.Context) {
|
||||
{{end}}
|
||||
|
||||
{{if .HasDelete}}
|
||||
// Delete{{.NameUpper}} godoc
|
||||
// Delete{{.Name}} godoc
|
||||
// @Summary Delete existing {{.Name}}
|
||||
// @Description {{.Description}}
|
||||
// @Tags {{join .Tags ","}}
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
{{if .RequireAuth}}
|
||||
// @Security ApiKeyAuth
|
||||
{{end}}
|
||||
// @Param X-Request-ID header string false "Request ID for tracking"
|
||||
{{range .PathParams}}
|
||||
// @Param {{.}} path string true "{{.}}" example("example_value")
|
||||
{{end}}
|
||||
// @Produce json {{if .RequireAuth}}
|
||||
// @Security ApiKeyAuth {{end}}
|
||||
// @Param X-Request-ID header string false "Request ID for tracking" {{range .PathParams}}
|
||||
// @Param {{.}} path string true "{{.}}" example("example_value") {{end}}
|
||||
// @Success 200 {object} {{.ModelPackage}}.{{.ResponseModel}} "Successfully deleted {{.Name}}"
|
||||
// @Failure 400 {object} models.ErrorResponseBpjs "Bad request - invalid parameters"
|
||||
// @Failure 401 {object} models.ErrorResponseBpjs "Unauthorized - invalid API credentials"
|
||||
@@ -573,6 +558,46 @@ func (h *{{$.ServiceName}}Handler) Delete{{.Name}}(c *gin.Context) {
|
||||
{{end}}
|
||||
`
|
||||
|
||||
// Template for generating routes
|
||||
const routesTemplate = `
|
||||
package v1
|
||||
|
||||
import (
|
||||
"{{.ModuleName}}/internal/config"
|
||||
"{{.ModuleName}}/internal/middleware"
|
||||
"{{.ModuleName}}/internal/handlers/{{.Category}}/{{.Package}}"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func Register{{.ServiceName}}Routes(router *gin.RouterGroup, cfg *config.Config) {
|
||||
handler := {{.Package}}.New{{.ServiceName}}Handler({{.Package}}.{{.ServiceName}}HandlerConfig{
|
||||
BpjsConfig: cfg.Bpjs,
|
||||
Logger: *logger.Default(),
|
||||
Validator: nil,
|
||||
})
|
||||
|
||||
group := router.Group("/{{.ServiceLower}}")
|
||||
|
||||
{{range .Endpoints}}
|
||||
{{if .HasGet}}
|
||||
group.GET("{{.GetPath}}", handler.Get{{.Name}})
|
||||
{{end}}
|
||||
{{if .HasPost}}
|
||||
group.POST("{{.PostPath}}", handler.Create{{.Name}})
|
||||
{{end}}
|
||||
{{if .HasPut}}
|
||||
group.PUT("{{.PutPath}}", handler.Update{{.Name}})
|
||||
{{end}}
|
||||
{{if .HasDelete}}
|
||||
group.DELETE("{{.DeletePath}}", handler.Delete{{.Name}})
|
||||
{{end}}
|
||||
{{if .HasPatch}}
|
||||
group.PATCH("{{.PatchPath}}", handler.Patch{{.Name}})
|
||||
{{end}}
|
||||
{{end}}
|
||||
}
|
||||
`
|
||||
|
||||
func main() {
|
||||
if len(os.Args) < 2 {
|
||||
printUsage()
|
||||
@@ -614,15 +639,24 @@ func main() {
|
||||
errors++
|
||||
continue
|
||||
}
|
||||
fmt.Printf("✅ Generated handler: %s_handler.go\n", strings.ToLower(serviceName))
|
||||
fmt.Printf("✅ Generated handler: %s.go\n", strings.ToLower(serviceName))
|
||||
|
||||
// Generate routes for this service
|
||||
err = generateRoutes(serviceName, service, config.Global)
|
||||
if err != nil {
|
||||
fmt.Printf("❌ Error generating routes for %s: %v\n", serviceName, err)
|
||||
errors++
|
||||
continue
|
||||
}
|
||||
fmt.Printf("✅ Generated routes: %s_routes.go\n", strings.ToLower(serviceName))
|
||||
generated++
|
||||
}
|
||||
|
||||
// Summary
|
||||
fmt.Println("\n📊 Generation Summary:")
|
||||
fmt.Printf(" ✅ Successfully generated: %d handlers\n", generated)
|
||||
fmt.Printf(" ✅ Successfully generated: %d handlers and routes\n", generated)
|
||||
if errors > 0 {
|
||||
fmt.Printf(" ❌ Failed: %d handlers\n", errors)
|
||||
fmt.Printf(" ❌ Failed: %d handlers/routes\n", errors)
|
||||
}
|
||||
|
||||
if generated > 0 {
|
||||
@@ -675,65 +709,6 @@ func loadConfig(filename string) (*ServiceConfig, error) {
|
||||
}
|
||||
|
||||
func generateHandler(serviceName string, service Service, globalConfig GlobalConfig) error {
|
||||
// Prepare template data
|
||||
templateData := TemplateData{
|
||||
ServiceName: service.Name,
|
||||
ServiceLower: strings.ToLower(service.Name),
|
||||
ServiceUpper: strings.ToUpper(service.Name),
|
||||
Category: service.Category,
|
||||
Package: service.Package,
|
||||
Description: service.Description,
|
||||
BaseURL: service.BaseURL,
|
||||
Timeout: getOrDefault(service.Timeout, 30),
|
||||
RetryCount: getOrDefault(service.RetryCount, 3),
|
||||
Timestamp: time.Now().Format("2006-01-02 15:04:05"),
|
||||
ModuleName: globalConfig.ModuleName,
|
||||
HasValidator: true,
|
||||
HasLogger: globalConfig.EnableLogging,
|
||||
HasMetrics: globalConfig.EnableMetrics,
|
||||
HasSwagger: globalConfig.EnableSwagger,
|
||||
Dependencies: service.Dependencies, // Now []string
|
||||
Middleware: service.Middleware, // Now []string
|
||||
GlobalConfig: globalConfig,
|
||||
}
|
||||
|
||||
// Check for advanced features
|
||||
for _, subEndpoints := range service.Endpoints {
|
||||
for _, endpoint := range subEndpoints {
|
||||
if endpoint.RequireAuth {
|
||||
templateData.HasAuth = true
|
||||
}
|
||||
if endpoint.CacheEnabled {
|
||||
templateData.HasCache = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Process endpoints
|
||||
for endpointName, subEndpoints := range service.Endpoints {
|
||||
for subEndpointName, endpoint := range subEndpoints {
|
||||
// Compose full endpoint name with sub-endpoint name
|
||||
fullEndpointName := endpointName
|
||||
if subEndpointName != "" {
|
||||
fullEndpointName = fullEndpointName + strings.Title(subEndpointName)
|
||||
}
|
||||
endpointData := processEndpoint(fullEndpointName, endpoint, endpointName)
|
||||
templateData.Endpoints = append(templateData.Endpoints, endpointData)
|
||||
}
|
||||
}
|
||||
|
||||
// Create output directory
|
||||
outputDir := globalConfig.OutputDir
|
||||
if outputDir == "" {
|
||||
outputDir = "internal/handlers"
|
||||
}
|
||||
if err := os.MkdirAll(outputDir, 0755); err != nil {
|
||||
return fmt.Errorf("failed to create output directory: %w", err)
|
||||
}
|
||||
|
||||
// Generate handler file
|
||||
filename := filepath.Join(outputDir, fmt.Sprintf("%s_handler.go", strings.ToLower(serviceName)))
|
||||
|
||||
// Create template with custom functions
|
||||
tmpl := template.New("handler").Funcs(template.FuncMap{
|
||||
"contains": strings.Contains,
|
||||
@@ -747,17 +722,207 @@ func generateHandler(serviceName string, service Service, globalConfig GlobalCon
|
||||
return fmt.Errorf("failed to parse template: %w", err)
|
||||
}
|
||||
|
||||
file, err := os.Create(filename)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create file: %w", err)
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
err = tmpl.Execute(file, templateData)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to execute template: %w", err)
|
||||
outputDir := globalConfig.OutputDir
|
||||
if outputDir == "" {
|
||||
outputDir = "internal/handlers"
|
||||
}
|
||||
|
||||
generatedFiles := 0
|
||||
errorsCount := 0
|
||||
|
||||
// Loop over each module group in service.Endpoints
|
||||
for groupName, subEndpoints := range service.Endpoints {
|
||||
// Prepare template data for this group
|
||||
templateData := TemplateData{
|
||||
ServiceName: service.Name,
|
||||
ServiceLower: strings.ToLower(service.Name),
|
||||
ServiceUpper: strings.ToUpper(service.Name),
|
||||
Category: service.Category,
|
||||
Package: groupName, // package name is group name
|
||||
Description: service.Description,
|
||||
BaseURL: service.BaseURL,
|
||||
Timeout: getOrDefault(service.Timeout, 30),
|
||||
RetryCount: getOrDefault(service.RetryCount, 3),
|
||||
Timestamp: time.Now().Format("2006-01-02 15:04:05"),
|
||||
ModuleName: globalConfig.ModuleName,
|
||||
HasValidator: true,
|
||||
HasLogger: globalConfig.EnableLogging,
|
||||
HasMetrics: globalConfig.EnableMetrics,
|
||||
HasSwagger: globalConfig.EnableSwagger,
|
||||
Dependencies: service.Dependencies,
|
||||
Middleware: service.Middleware,
|
||||
GlobalConfig: globalConfig,
|
||||
}
|
||||
|
||||
// Check for advanced features in this group
|
||||
for _, endpoint := range subEndpoints {
|
||||
if endpoint.RequireAuth {
|
||||
templateData.HasAuth = true
|
||||
}
|
||||
if endpoint.CacheEnabled {
|
||||
templateData.HasCache = true
|
||||
}
|
||||
}
|
||||
|
||||
// Process endpoints for this group
|
||||
for subEndpointName, endpoint := range subEndpoints {
|
||||
fullEndpointName := groupName
|
||||
if subEndpointName != "" {
|
||||
fullEndpointName = fullEndpointName + strings.Title(subEndpointName)
|
||||
}
|
||||
endpointData := processEndpoint(fullEndpointName, endpoint, groupName)
|
||||
templateData.Endpoints = append(templateData.Endpoints, endpointData)
|
||||
}
|
||||
|
||||
// Create output directory for this group: outputDir/service.Package/groupName
|
||||
groupOutputDir := filepath.Join(outputDir, service.Package, groupName)
|
||||
if err := os.MkdirAll(groupOutputDir, 0755); err != nil {
|
||||
errorsCount++
|
||||
fmt.Printf("❌ Failed to create directory %s: %v\n", groupOutputDir, err)
|
||||
continue
|
||||
}
|
||||
|
||||
// Generate handler file for this group
|
||||
filename := filepath.Join(groupOutputDir, fmt.Sprintf("%s.go", groupName))
|
||||
|
||||
// Check if file already exists, skip generation if so
|
||||
if _, err := os.Stat(filename); err == nil {
|
||||
fmt.Printf("⚠️ Skipping generation for existing file: %s\n", filename)
|
||||
continue
|
||||
}
|
||||
|
||||
file, err := os.Create(filename)
|
||||
if err != nil {
|
||||
errorsCount++
|
||||
fmt.Printf("❌ Failed to create file %s: %v\n", filename, err)
|
||||
continue
|
||||
}
|
||||
|
||||
err = tmpl.Execute(file, templateData)
|
||||
file.Close()
|
||||
if err != nil {
|
||||
errorsCount++
|
||||
fmt.Printf("❌ Failed to execute template for %s: %v\n", filename, err)
|
||||
continue
|
||||
}
|
||||
|
||||
fmt.Printf("✅ Generated handler: %s\n", filename)
|
||||
generatedFiles++
|
||||
}
|
||||
|
||||
if errorsCount > 0 {
|
||||
return fmt.Errorf("generation completed with %d errors", errorsCount)
|
||||
}
|
||||
|
||||
if generatedFiles == 0 {
|
||||
return fmt.Errorf("no handlers generated")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func generateRoutes(serviceName string, service Service, globalConfig GlobalConfig) error {
|
||||
// Read the main routes.go file
|
||||
routesFilePath := "internal/routes/v1/routes.go"
|
||||
routesContent, err := ioutil.ReadFile(routesFilePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read routes file: %w", err)
|
||||
}
|
||||
|
||||
routesContentStr := string(routesContent)
|
||||
|
||||
// Check if routes are already registered
|
||||
if strings.Contains(routesContentStr, fmt.Sprintf("Register%sRoutes", service.Name)) {
|
||||
fmt.Printf("⚠️ Routes for %s already registered in main routes file\n", service.Name)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Prepare template data for all groups
|
||||
var allRoutes []string
|
||||
|
||||
// Loop over each module group in service.Endpoints
|
||||
for groupName, subEndpoints := range service.Endpoints {
|
||||
// Prepare template data for this group
|
||||
templateData := TemplateData{
|
||||
ServiceName: service.Name,
|
||||
ServiceLower: strings.ToLower(service.Name),
|
||||
ServiceUpper: strings.ToUpper(service.Name),
|
||||
Category: service.Category,
|
||||
Package: groupName, // package name is group name
|
||||
Description: service.Description,
|
||||
BaseURL: service.BaseURL,
|
||||
Timeout: getOrDefault(service.Timeout, 30),
|
||||
RetryCount: getOrDefault(service.RetryCount, 3),
|
||||
Timestamp: time.Now().Format("2006-01-02 15:04:05"),
|
||||
ModuleName: globalConfig.ModuleName,
|
||||
HasValidator: true,
|
||||
HasLogger: globalConfig.EnableLogging,
|
||||
HasMetrics: globalConfig.EnableMetrics,
|
||||
HasSwagger: globalConfig.EnableSwagger,
|
||||
Dependencies: service.Dependencies,
|
||||
Middleware: service.Middleware,
|
||||
GlobalConfig: globalConfig,
|
||||
}
|
||||
|
||||
// Process endpoints for this group
|
||||
for subEndpointName, endpoint := range subEndpoints {
|
||||
fullEndpointName := groupName
|
||||
if subEndpointName != "" {
|
||||
fullEndpointName = fullEndpointName + strings.Title(subEndpointName)
|
||||
}
|
||||
endpointData := processEndpoint(fullEndpointName, endpoint, groupName)
|
||||
templateData.Endpoints = append(templateData.Endpoints, endpointData)
|
||||
}
|
||||
|
||||
// Generate routes code for this group
|
||||
var routesCode strings.Builder
|
||||
|
||||
routesCode.WriteString(fmt.Sprintf("\n\t// %s routes\n", strings.Title(groupName)))
|
||||
routesCode.WriteString(fmt.Sprintf("\t%sHandler := %s.New%sHandler(%s.%sHandlerConfig{\n", groupName, groupName, service.Name, groupName, service.Name))
|
||||
routesCode.WriteString("\t\tBpjsConfig: cfg.Bpjs,\n")
|
||||
routesCode.WriteString("\t\tLogger: *logger.Default(),\n")
|
||||
routesCode.WriteString("\t\tValidator: nil,\n")
|
||||
routesCode.WriteString("\t})\n")
|
||||
routesCode.WriteString(fmt.Sprintf("\t%sGroup := v1.Group(\"/%s\")\n", groupName, groupName))
|
||||
|
||||
for _, endpoint := range templateData.Endpoints {
|
||||
if endpoint.HasGet {
|
||||
routesCode.WriteString(fmt.Sprintf("\t%sGroup.GET(\"%s\", %sHandler.Get%s)\n", groupName, endpoint.GetPath, groupName, endpoint.Name))
|
||||
}
|
||||
if endpoint.HasPost {
|
||||
routesCode.WriteString(fmt.Sprintf("\t%sGroup.POST(\"%s\", %sHandler.Create%s)\n", groupName, endpoint.PostPath, groupName, endpoint.Name))
|
||||
}
|
||||
if endpoint.HasPut {
|
||||
routesCode.WriteString(fmt.Sprintf("\t%sGroup.PUT(\"%s\", %sHandler.Update%s)\n", groupName, endpoint.PutPath, groupName, endpoint.Name))
|
||||
}
|
||||
if endpoint.HasDelete {
|
||||
routesCode.WriteString(fmt.Sprintf("\t%sGroup.DELETE(\"%s\", %sHandler.Delete%s)\n", groupName, endpoint.DeletePath, groupName, endpoint.Name))
|
||||
}
|
||||
if endpoint.HasPatch {
|
||||
routesCode.WriteString(fmt.Sprintf("\t%sGroup.PATCH(\"%s\", %sHandler.Patch%s)\n", groupName, endpoint.PatchPath, groupName, endpoint.Name))
|
||||
}
|
||||
}
|
||||
|
||||
allRoutes = append(allRoutes, routesCode.String())
|
||||
}
|
||||
|
||||
// Find the PUBLISHED ROUTES section and insert the routes
|
||||
publishedRoutesMarker := "// ============= PUBLISHED ROUTES ==============================================="
|
||||
if !strings.Contains(routesContentStr, publishedRoutesMarker) {
|
||||
return fmt.Errorf("PUBLISHED ROUTES marker not found in routes.go")
|
||||
}
|
||||
|
||||
// Insert the routes after the marker
|
||||
insertionPoint := strings.Index(routesContentStr, publishedRoutesMarker) + len(publishedRoutesMarker)
|
||||
newRoutesContent := routesContentStr[:insertionPoint] + "\n" + strings.Join(allRoutes, "\n") + "\n" + routesContentStr[insertionPoint:]
|
||||
|
||||
// Write back the modified routes file
|
||||
err = ioutil.WriteFile(routesFilePath, []byte(newRoutesContent), 0644)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to write updated routes file: %w", err)
|
||||
}
|
||||
|
||||
fmt.Printf("✅ Updated main routes file with %s routes\n", service.Name)
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user