Skip to content

Commit

Permalink
cmd: update project generator
Browse files Browse the repository at this point in the history
  • Loading branch information
agungdwiprasetyo committed May 4, 2023
1 parent d8eca02 commit a7d7946
Show file tree
Hide file tree
Showing 11 changed files with 198 additions and 145 deletions.
8 changes: 4 additions & 4 deletions cmd/candi/template_cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,8 @@ func main() {
switch args[0] {
case "create":
migrationType := "sql"
if len(args) > 2 && args[2] == "init_table" {
migrationType = "go"
if len(args) > 2 {
migrationType = args[2]
}
if err := goose.Create(sqlDeps.WriteDB(), dir, args[1], migrationType); err != nil {
log.Fatalf("goose %v: %v", args[1], err)
Expand All @@ -99,7 +99,7 @@ func main() {
log.Fatal(err)
}
tx := gormWrite.Begin()
if err := gormWrite.AutoMigrate(migrateTables...); err != nil {
if err := tx.AutoMigrate(migrateTables...); err != nil {
tx.Rollback()
log.Fatal(err)
}
Expand All @@ -125,7 +125,7 @@ func GetMigrateTables() []interface{} {
templateCmdMigrationInitModule = `-- +goose Up
-- +goose StatementBegin
CREATE TABLE IF NOT EXISTS {{plural .ModuleName}} (
"id" VARCHAR(255) NOT NULL PRIMARY KEY,
"id" SERIAL NOT NULL PRIMARY KEY,
"field" VARCHAR(255),
"created_at" TIMESTAMPTZ(6),
"updated_at" TIMESTAMPTZ(6)
Expand Down
1 change: 1 addition & 0 deletions cmd/candi/template_configs.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ func LoadServiceConfigs(baseCfg *config.Config) (deps dependency.Dependency) {
middleware.SetUserIDExtractor(func(tokenClaim *candishared.TokenClaim) (userID string) {
return tokenClaim.Subject
}),
{{if not .RedisDeps}}// {{end}}middleware.SetCache(deps.GetRedisPool().Cache(), middleware.DefaultCacheAge),
))
return deps
Expand Down
38 changes: 20 additions & 18 deletions cmd/candi/template_delivery_graphql.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ func (q *GraphQLHandler) GetAll{{upper (camel .ModuleName)}}(ctx context.Context
}
// GetDetail{{upper (camel .ModuleName)}} resolver
func (q *GraphQLHandler) GetDetail{{upper (camel .ModuleName)}}(ctx context.Context, input struct{ ID string }) (data domain.Response{{upper (camel .ModuleName)}}, err error) {
func (q *GraphQLHandler) GetDetail{{upper (camel .ModuleName)}}(ctx context.Context, input struct{ ID {{if and .MongoDeps (not .SQLDeps)}}string{{else}}int{{end}} }) (data domain.Response{{upper (camel .ModuleName)}}, err error) {
trace, ctx := tracer.StartTraceWithContext(ctx, "{{upper (camel .ModuleName)}}DeliveryGraphQL:GetDetail{{upper (camel .ModuleName)}}")
defer trace.Finish()
Expand All @@ -101,24 +101,21 @@ import (
)
// Create{{upper (camel .ModuleName)}} resolver
func (m *GraphQLHandler) Create{{upper (camel .ModuleName)}}(ctx context.Context, input struct{ Data domain.Request{{upper (camel .ModuleName)}} }) (ok string, err error) {
func (m *GraphQLHandler) Create{{upper (camel .ModuleName)}}(ctx context.Context, input struct{ Data domain.Request{{upper (camel .ModuleName)}} }) (data domain.Response{{upper (camel .ModuleName)}}, err error) {
trace, ctx := tracer.StartTraceWithContext(ctx, "{{upper (camel .ModuleName)}}DeliveryGraphQL:Create{{upper (camel .ModuleName)}}")
defer trace.Finish()
// tokenClaim := candishared.ParseTokenClaimFromContext(ctx) // must using GraphQLBearerAuth in middleware for this resolver
if err := m.validator.ValidateDocument("{{cleanPathModule .ModuleName}}/save", input.Data); err != nil {
return "", err
}
if err := m.uc.{{upper (camel .ModuleName)}}().Create{{upper (camel .ModuleName)}}(ctx, &input.Data); err != nil {
return ok, err
return data, err
}
return "Success", nil
return m.uc.{{upper (camel .ModuleName)}}().Create{{upper (camel .ModuleName)}}(ctx, &input.Data)
}
// Update{{upper (camel .ModuleName)}} resolver
func (m *GraphQLHandler) Update{{upper (camel .ModuleName)}}(ctx context.Context, input struct {
ID string
ID {{if and .MongoDeps (not .SQLDeps)}}string{{else}}int{{end}}
Data domain.Request{{upper (camel .ModuleName)}}
}) (ok string, err error) {
trace, ctx := tracer.StartTraceWithContext(ctx, "{{upper (camel .ModuleName)}}DeliveryGraphQL:Update{{upper (camel .ModuleName)}}")
Expand All @@ -137,7 +134,7 @@ func (m *GraphQLHandler) Update{{upper (camel .ModuleName)}}(ctx context.Context
}
// Delete{{upper (camel .ModuleName)}} resolver
func (m *GraphQLHandler) Delete{{upper (camel .ModuleName)}}(ctx context.Context, input struct{ ID string }) (ok string, err error) {
func (m *GraphQLHandler) Delete{{upper (camel .ModuleName)}}(ctx context.Context, input struct{ ID {{if and .MongoDeps (not .SQLDeps)}}string{{else}}int{{end}} }) (ok string, err error) {
trace, ctx := tracer.StartTraceWithContext(ctx, "{{upper (camel .ModuleName)}}DeliveryGraphQL:Delete{{upper (camel .ModuleName)}}")
defer trace.Finish()
Expand All @@ -159,9 +156,9 @@ import (
"{{$.PackagePrefix}}/internal/modules/{{cleanPathModule .ModuleName}}/domain"
"{{.LibraryName}}/logger"
"{{.LibraryName}}/logger"{{if and .MongoDeps (not .SQLDeps)}}
"github.com/google/uuid"
"github.com/google/uuid"{{end}}
)
// ListenData resolver, broadcast event to client
Expand All @@ -178,7 +175,7 @@ func (s *GraphQLHandler) ListenData(ctx context.Context) <-chan domain.Response{
CreatedAt: time.Now().Format(time.RFC3339),
UpdatedAt: time.Now().Format(time.RFC3339),
}
data.ID = uuid.NewString()
data.ID = {{if and .MongoDeps (not .SQLDeps)}}uuid.NewString(){{else}}1{{end}}
output <- data
case <-ctx.Done():
tick.Stop()
Expand Down Expand Up @@ -247,7 +244,12 @@ schema {
subscription: Subscription
}
directive @auth(authType: String!) on FIELD_DEFINITION
enum AuthTypeDirective {
BASIC
BEARER
MULTIPLE
}
directive @auth(authType: AuthTypeDirective!) on FIELD_DEFINITION
directive @permissionACL(permissionCode: String!) on FIELD_DEFINITION
type Query {
Expand All @@ -268,13 +270,13 @@ type Subscription {
# {{upper (camel .ModuleName)}}Module Resolver Area
type {{upper (camel .ModuleName)}}QueryResolver {
getAll{{upper (camel .ModuleName)}}(filter: FilterListInputResolver): {{upper (camel .ModuleName)}}ListResolver! @permissionACL(permissionCode: getAll{{upper (camel .ModuleName)}})
getDetail{{upper (camel .ModuleName)}}(id: String!): {{upper (camel .ModuleName)}}Resolver! @permissionACL(permissionCode: getDetail{{upper (camel .ModuleName)}})
getDetail{{upper (camel .ModuleName)}}(id: {{if and .MongoDeps (not .SQLDeps)}}String{{else}}Int{{end}}!): {{upper (camel .ModuleName)}}Resolver! @permissionACL(permissionCode: getDetail{{upper (camel .ModuleName)}})
}
type {{upper (camel .ModuleName)}}MutationResolver {
create{{upper (camel .ModuleName)}}(data: {{upper (camel .ModuleName)}}InputResolver!): String! @permissionACL(permissionCode: create{{upper (camel .ModuleName)}})
update{{upper (camel .ModuleName)}}(id: String!, data: {{upper (camel .ModuleName)}}InputResolver!): String! @permissionACL(permissionCode: update{{upper (camel .ModuleName)}})
delete{{upper (camel .ModuleName)}}(id: String!): String! @permissionACL(permissionCode: delete{{upper (camel .ModuleName)}})
create{{upper (camel .ModuleName)}}(data: {{upper (camel .ModuleName)}}InputResolver!): {{upper (camel .ModuleName)}}Resolver! @permissionACL(permissionCode: create{{upper (camel .ModuleName)}})
update{{upper (camel .ModuleName)}}(id: {{if and .MongoDeps (not .SQLDeps)}}String{{else}}Int{{end}}!, data: {{upper (camel .ModuleName)}}InputResolver!): String! @permissionACL(permissionCode: update{{upper (camel .ModuleName)}})
delete{{upper (camel .ModuleName)}}(id: {{if and .MongoDeps (not .SQLDeps)}}String{{else}}Int{{end}}!): String! @permissionACL(permissionCode: delete{{upper (camel .ModuleName)}})
}
type {{upper (camel .ModuleName)}}SubscriptionResolver {
Expand All @@ -287,7 +289,7 @@ type {{upper (camel .ModuleName)}}ListResolver {
}
type {{upper (camel .ModuleName)}}Resolver {
id: String!
id: {{if and .MongoDeps (not .SQLDeps)}}String{{else}}Int{{end}}!
field: String!
createdAt: String!
updatedAt: String!
Expand Down
30 changes: 16 additions & 14 deletions cmd/candi/template_delivery_grpc.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ func (h *GRPCHandler) GetAll{{upper (camel .ModuleName)}}(ctx context.Context, r
for _, d := range data {
data := &proto.{{upper (camel .ModuleName)}}Model{
ID: d.ID, Field: d.Field, CreatedAt: d.CreatedAt, UpdatedAt: d.UpdatedAt,
ID: {{if and .MongoDeps (not .SQLDeps)}}d.ID{{else}}int64(d.ID){{end}}, Field: d.Field, CreatedAt: d.CreatedAt, UpdatedAt: d.UpdatedAt,
}
resp.Data = append(resp.Data, data)
}
Expand All @@ -93,19 +93,19 @@ func (h *GRPCHandler) GetDetail{{upper (camel .ModuleName)}}(ctx context.Context
// tokenClaim := candishared.ParseTokenClaimFromContext(ctx) // must using GRPCBearerAuth in middleware for this handler
data, err := h.uc.{{upper (camel .ModuleName)}}().GetDetail{{upper (camel .ModuleName)}}(ctx, req.ID)
data, err := h.uc.{{upper (camel .ModuleName)}}().GetDetail{{upper (camel .ModuleName)}}(ctx, {{if and .MongoDeps (not .SQLDeps)}}req.ID{{else}}int(req.ID){{end}})
if err != nil {
return nil, grpc.Errorf(codes.FailedPrecondition, err.Error())
}
resp := &proto.{{upper (camel .ModuleName)}}Model{
ID: data.ID, Field: data.Field, CreatedAt: data.CreatedAt, UpdatedAt: data.UpdatedAt,
ID: {{if and .MongoDeps (not .SQLDeps)}}data.ID{{else}}int64(data.ID){{end}}, Field: data.Field, CreatedAt: data.CreatedAt, UpdatedAt: data.UpdatedAt,
}
return resp, nil
}
// Create{{upper (camel .ModuleName)}} rpc method
func (h *GRPCHandler) Create{{upper (camel .ModuleName)}}(ctx context.Context, req *proto.Request{{upper (camel .ModuleName)}}Model) (resp *proto.BaseResponse, err error) {
func (h *GRPCHandler) Create{{upper (camel .ModuleName)}}(ctx context.Context, req *proto.Request{{upper (camel .ModuleName)}}Model) (resp *proto.{{upper (camel .ModuleName)}}Model, err error) {
trace, ctx := tracer.StartTraceWithContext(ctx, "{{upper (camel .ModuleName)}}DeliveryGRPC:Create{{upper (camel .ModuleName)}}")
defer trace.Finish()
Expand All @@ -116,13 +116,15 @@ func (h *GRPCHandler) Create{{upper (camel .ModuleName)}}(ctx context.Context, r
if err := h.validator.ValidateDocument("{{cleanPathModule .ModuleName}}/save", payload); err != nil {
return nil, grpc.Errorf(codes.InvalidArgument, err.Error())
}
if err := h.uc.{{upper (camel .ModuleName)}}().Create{{upper (camel .ModuleName)}}(ctx, &payload); err != nil {
data, err := h.uc.{{upper (camel .ModuleName)}}().Create{{upper (camel .ModuleName)}}(ctx, &payload)
if err != nil {
return nil, grpc.Errorf(codes.FailedPrecondition, err.Error())
}
return &proto.BaseResponse{
Message: "Success",
}, nil
resp = &proto.{{upper (camel .ModuleName)}}Model{
ID: {{if and .MongoDeps (not .SQLDeps)}}data.ID{{else}}int64(data.ID){{end}}, Field: data.Field, CreatedAt: data.CreatedAt, UpdatedAt: data.UpdatedAt,
}
return resp, nil
}
// Update{{upper (camel .ModuleName)}} rpc method
Expand All @@ -133,7 +135,7 @@ func (h *GRPCHandler) Update{{upper (camel .ModuleName)}}(ctx context.Context, r
// tokenClaim := candishared.ParseTokenClaimFromContext(ctx) // must using GRPCBearerAuth in middleware for this handler
var payload domain.Request{{upper (camel .ModuleName)}}
payload.ID = req.ID
payload.ID = {{if and .MongoDeps (not .SQLDeps)}}req.ID{{else}}int(req.ID){{end}}
payload.Field = req.Field
if err := h.validator.ValidateDocument("{{cleanPathModule .ModuleName}}/save", payload); err != nil {
return nil, grpc.Errorf(codes.InvalidArgument, err.Error())
Expand All @@ -154,7 +156,7 @@ func (h *GRPCHandler) Delete{{upper (camel .ModuleName)}}(ctx context.Context, r
// tokenClaim := candishared.ParseTokenClaimFromContext(ctx) // must using GRPCBearerAuth in middleware for this handler
if err := h.uc.{{upper (camel .ModuleName)}}().Delete{{upper (camel .ModuleName)}}(ctx, req.ID); err != nil {
if err := h.uc.{{upper (camel .ModuleName)}}().Delete{{upper (camel .ModuleName)}}(ctx, {{if and .MongoDeps (not .SQLDeps)}}req.ID{{else}}int(req.ID){{end}}); err != nil {
return nil, grpc.Errorf(codes.FailedPrecondition, err.Error())
}
Expand All @@ -171,7 +173,7 @@ option go_package = "{{.PackagePrefix}}/api/proto/{{.ModuleName}}";
service {{upper (camel .ModuleName)}}Handler {
rpc GetAll{{upper (camel .ModuleName)}}(GetAll{{upper (camel .ModuleName)}}Request) returns (GetAll{{upper (camel .ModuleName)}}Response);
rpc GetDetail{{upper (camel .ModuleName)}}(GetDetail{{upper (camel .ModuleName)}}Request) returns ({{upper (camel .ModuleName)}}Model);
rpc Create{{upper (camel .ModuleName)}}(Request{{upper (camel .ModuleName)}}Model) returns (BaseResponse);
rpc Create{{upper (camel .ModuleName)}}(Request{{upper (camel .ModuleName)}}Model) returns ({{upper (camel .ModuleName)}}Model);
rpc Update{{upper (camel .ModuleName)}}(Request{{upper (camel .ModuleName)}}Model) returns (BaseResponse);
rpc Delete{{upper (camel .ModuleName)}}(Request{{upper (camel .ModuleName)}}Model) returns (BaseResponse);
}
Expand Down Expand Up @@ -200,16 +202,16 @@ message GetAll{{upper (camel .ModuleName)}}Response {
}
message GetDetail{{upper (camel .ModuleName)}}Request {
string ID=1;
{{if and .MongoDeps (not .SQLDeps)}}string{{else}}int64{{end}} ID=1;
}
message Request{{upper (camel .ModuleName)}}Model {
string ID=1;
{{if and .MongoDeps (not .SQLDeps)}}string{{else}}int64{{end}} ID=1;
string Field=2;
}
message {{upper (camel .ModuleName)}}Model {
string ID=1;
{{if and .MongoDeps (not .SQLDeps)}}string{{else}}int64{{end}} ID=1;
string Field=2;
string CreatedAt=3;
string UpdatedAt=4;
Expand Down
30 changes: 17 additions & 13 deletions cmd/candi/template_delivery_rest.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ package resthandler
import (
"encoding/json"
"io"
"net/http"
"net/http"{{if and .MongoDeps (not .SQLDeps)}}{{else}}
"strconv"{{end}}
"github.com/labstack/echo"
Expand All @@ -17,6 +18,7 @@ import (
"{{.LibraryName}}/candihelper"
"{{.LibraryName}}/candishared"
restserver "{{.LibraryName}}/codebase/app/rest_server"
"{{.LibraryName}}/codebase/factory/dependency"
"{{.LibraryName}}/codebase/interfaces"
"{{.LibraryName}}/tracer"
Expand All @@ -42,12 +44,12 @@ func NewRestHandler(uc usecase.Usecase, deps dependency.Dependency) *RestHandler
func (h *RestHandler) Mount(root *echo.Group) {
v1Root := root.Group(candihelper.V1)
{{camel .ModuleName}} := v1Root.Group("/{{kebab .ModuleName}}", echo.WrapMiddleware(h.mw.HTTPBearerAuth))
{{camel .ModuleName}}.GET("", h.getAll{{upper (camel .ModuleName)}}, echo.WrapMiddleware(h.mw.HTTPPermissionACL("getAll{{upper (camel .ModuleName)}}")))
{{camel .ModuleName}}.GET("/:id", h.getDetail{{upper (camel .ModuleName)}}ByID, echo.WrapMiddleware(h.mw.HTTPPermissionACL("getDetail{{upper (camel .ModuleName)}}")))
{{camel .ModuleName}}.POST("", h.create{{upper (camel .ModuleName)}}, echo.WrapMiddleware(h.mw.HTTPPermissionACL("create{{upper (camel .ModuleName)}}")))
{{camel .ModuleName}}.PUT("/:id", h.update{{upper (camel .ModuleName)}}, echo.WrapMiddleware(h.mw.HTTPPermissionACL("update{{upper (camel .ModuleName)}}")))
{{camel .ModuleName}}.DELETE("/:id", h.delete{{upper (camel .ModuleName)}}, echo.WrapMiddleware(h.mw.HTTPPermissionACL("delete{{upper (camel .ModuleName)}}")))
{{camel .ModuleName}} := v1Root.Group("/{{kebab .ModuleName}}", restserver.EchoWrapMiddleware(h.mw.HTTPBearerAuth))
{{camel .ModuleName}}.GET("", h.getAll{{upper (camel .ModuleName)}}, restserver.EchoWrapMiddleware(h.mw.HTTPPermissionACL("getAll{{upper (camel .ModuleName)}}")))
{{camel .ModuleName}}.GET("/:id", h.getDetail{{upper (camel .ModuleName)}}ByID, restserver.EchoWrapMiddleware(h.mw.HTTPPermissionACL("getDetail{{upper (camel .ModuleName)}}")))
{{camel .ModuleName}}.POST("", h.create{{upper (camel .ModuleName)}}, restserver.EchoWrapMiddleware(h.mw.HTTPPermissionACL("create{{upper (camel .ModuleName)}}")))
{{camel .ModuleName}}.PUT("/:id", h.update{{upper (camel .ModuleName)}}, restserver.EchoWrapMiddleware(h.mw.HTTPPermissionACL("update{{upper (camel .ModuleName)}}")))
{{camel .ModuleName}}.DELETE("/:id", h.delete{{upper (camel .ModuleName)}}, restserver.EchoWrapMiddleware(h.mw.HTTPPermissionACL("delete{{upper (camel .ModuleName)}}")))
}
func (h *RestHandler) getAll{{upper (camel .ModuleName)}}(c echo.Context) error {
Expand Down Expand Up @@ -78,7 +80,8 @@ func (h *RestHandler) getDetail{{upper (camel .ModuleName)}}ByID(c echo.Context)
trace, ctx := tracer.StartTraceWithContext(c.Request().Context(), "{{upper (camel .ModuleName)}}DeliveryREST:GetDetail{{upper (camel .ModuleName)}}ByID")
defer trace.Finish()
data, err := h.uc.{{upper (camel .ModuleName)}}().GetDetail{{upper (camel .ModuleName)}}(ctx, c.Param("id"))
{{if and .MongoDeps (not .SQLDeps)}}id := c.Param("id"){{else}}id, _ := strconv.Atoi(c.Param("id")){{end}}
data, err := h.uc.{{upper (camel .ModuleName)}}().GetDetail{{upper (camel .ModuleName)}}(ctx, id)
if err != nil {
return wrapper.NewHTTPResponse(http.StatusBadRequest, err.Error()).JSON(c.Response())
}
Expand All @@ -100,12 +103,12 @@ func (h *RestHandler) create{{upper (camel .ModuleName)}}(c echo.Context) error
return wrapper.NewHTTPResponse(http.StatusBadRequest, err.Error()).JSON(c.Response())
}
err := h.uc.{{upper (camel .ModuleName)}}().Create{{upper (camel .ModuleName)}}(ctx, &payload)
res, err := h.uc.{{upper (camel .ModuleName)}}().Create{{upper (camel .ModuleName)}}(ctx, &payload)
if err != nil {
return wrapper.NewHTTPResponse(http.StatusBadRequest, err.Error()).JSON(c.Response())
}
return wrapper.NewHTTPResponse(http.StatusCreated, "Success").JSON(c.Response())
return wrapper.NewHTTPResponse(http.StatusCreated, "Success", res).JSON(c.Response())
}
func (h *RestHandler) update{{upper (camel .ModuleName)}}(c echo.Context) error {
Expand All @@ -122,7 +125,7 @@ func (h *RestHandler) update{{upper (camel .ModuleName)}}(c echo.Context) error
return wrapper.NewHTTPResponse(http.StatusBadRequest, err.Error()).JSON(c.Response())
}
payload.ID = c.Param("id")
{{if and .MongoDeps (not .SQLDeps)}}payload.ID = c.Param("id"){{else}}payload.ID, _ = strconv.Atoi(c.Param("id")){{end}}
err := h.uc.{{upper (camel .ModuleName)}}().Update{{upper (camel .ModuleName)}}(ctx, &payload)
if err != nil {
return wrapper.NewHTTPResponse(http.StatusBadRequest, err.Error()).JSON(c.Response())
Expand All @@ -134,8 +137,9 @@ func (h *RestHandler) update{{upper (camel .ModuleName)}}(c echo.Context) error
func (h *RestHandler) delete{{upper (camel .ModuleName)}}(c echo.Context) error {
trace, ctx := tracer.StartTraceWithContext(c.Request().Context(), "{{upper (camel .ModuleName)}}DeliveryREST:Delete{{upper (camel .ModuleName)}}")
defer trace.Finish()
if err := h.uc.{{upper (camel .ModuleName)}}().Delete{{upper (camel .ModuleName)}}(ctx, c.Param("id")); err != nil {
{{if and .MongoDeps (not .SQLDeps)}}id := c.Param("id"){{else}}id, _ := strconv.Atoi(c.Param("id")){{end}}
if err := h.uc.{{upper (camel .ModuleName)}}().Delete{{upper (camel .ModuleName)}}(ctx, id); err != nil {
return wrapper.NewHTTPResponse(http.StatusBadRequest, err.Error()).JSON(c.Response())
}
Expand Down
Loading

0 comments on commit a7d7946

Please sign in to comment.