Skip to content

Commit

Permalink
cli: update template
Browse files Browse the repository at this point in the history
  • Loading branch information
agungdwiprasetyo committed Dec 6, 2022
1 parent cca6ebf commit cab9d8a
Show file tree
Hide file tree
Showing 6 changed files with 52 additions and 39 deletions.
4 changes: 2 additions & 2 deletions cmd/candi/template_cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ import (
service "{{.PackagePrefix}}/internal"
)
const serviceName = "{{.ServiceName}}"
func main() {
const serviceName = "{{.ServiceName}}"
defer func() {
if r := recover(); r != nil {
fmt.Printf("\x1b[31;1mFailed to start %s service: %v\x1b[0m\n", serviceName, r)
Expand Down
13 changes: 9 additions & 4 deletions cmd/candi/template_configs.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"{{.LibraryName}}/broker"
"{{.LibraryName}}/candihelper"
"{{.LibraryName}}/candishared"
"{{.LibraryName}}/codebase/factory/dependency"
"{{.LibraryName}}/codebase/interfaces"
"{{.LibraryName}}/config"
Expand Down Expand Up @@ -48,10 +49,6 @@ func LoadServiceConfigs(baseCfg *config.Config) (deps dependency.Dependency) {
// inject all service dependencies
// See all option in dependency package
deps = dependency.InitDependency(
dependency.SetMiddleware(middleware.NewMiddlewareWithOption(
middleware.SetTokenValidator(&shared.DefaultMiddleware{}),
middleware.SetACLPermissionChecker(&shared.DefaultMiddleware{}),
)),
dependency.SetValidator(validator.NewValidator()),
dependency.SetBrokers(brokerDeps.GetBrokers()),
{{if not .RedisDeps}}// {{end}}dependency.SetRedisPool(redisDeps),
Expand All @@ -72,6 +69,14 @@ func LoadServiceConfigs(baseCfg *config.Config) (deps dependency.Dependency) {
repository.SetSharedRepository(deps)
usecase.SetSharedUsecase(deps)
deps.SetMiddleware(middleware.NewMiddlewareWithOption(
middleware.SetTokenValidator(&shared.DefaultMiddleware{}),
middleware.SetACLPermissionChecker(&shared.DefaultMiddleware{}),
middleware.SetUserIDExtractor(func(tokenClaim *candishared.TokenClaim) (userID string) {
return tokenClaim.Subject
}),
))
return deps
}
`
Expand Down
5 changes: 3 additions & 2 deletions cmd/candi/template_domain.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,10 @@ import "{{.LibraryName}}/candishared"
// Filter{{upper (camel .ModuleName)}} model
type Filter{{upper (camel .ModuleName)}} struct {
candishared.Filter
ID string ` + "`json:\"id\"`" + `
ID *string ` + "`json:\"id\"`" + `
StartDate string ` + "`json:\"startDate\"`" + `
EndDate string ` + "`json:\"endDate\"`" + `
EndDate string ` + "`json:\"endDate\"`{{if .SQLUseGORM}}" + `
Preloads []string ` + "`json:\"-\"`" + `{{end}}
}
`
templateModuleRequestDomain = `package domain
Expand Down
63 changes: 35 additions & 28 deletions cmd/candi/template_repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -366,7 +366,7 @@ func New{{upper (camel .ModuleName)}}RepoMongo(readDB, writeDB *mongo.Database)
func (r *{{camel .ModuleName}}RepoMongo) FetchAll(ctx context.Context, filter *domain.Filter{{upper (camel .ModuleName)}}) (data []shareddomain.{{upper (camel .ModuleName)}}, err error) {
trace, ctx := tracer.StartTraceWithContext(ctx, "{{upper (camel .ModuleName)}}RepoMongo:FetchAll")
defer func() { trace.SetError(err); trace.Finish() }()
defer func() { trace.Finish(tracer.FinishWithError(err)) }()
where := bson.M{}
trace.SetTag("query", where)
Expand All @@ -392,11 +392,11 @@ func (r *{{camel .ModuleName}}RepoMongo) FetchAll(ctx context.Context, filter *d
func (r *{{camel .ModuleName}}RepoMongo) Find(ctx context.Context, filter *domain.Filter{{upper (camel .ModuleName)}}) (result shareddomain.{{upper (camel .ModuleName)}}, err error) {
trace, ctx := tracer.StartTraceWithContext(ctx, "{{upper (camel .ModuleName)}}RepoMongo:Find")
defer func() { trace.SetError(err); trace.Finish() }()
defer func() { trace.Finish(tracer.FinishWithError(err)) }()
bsonWhere := make(bson.M)
if filter.ID != "" {
bsonWhere["_id"], _ = primitive.ObjectIDFromHex(filter.ID)
if filter.ID != nil {
bsonWhere["_id"], _ = primitive.ObjectIDFromHex(*filter.ID)
}
trace.SetTag("query", bsonWhere)
Expand All @@ -416,7 +416,7 @@ func (r *{{camel .ModuleName}}RepoMongo) Count(ctx context.Context, filter *doma
func (r *{{camel .ModuleName}}RepoMongo) Save(ctx context.Context, data *shareddomain.{{upper (camel .ModuleName)}}) (err error) {
trace, ctx := tracer.StartTraceWithContext(ctx, "{{upper (camel .ModuleName)}}RepoMongo:Save")
defer func() { trace.SetError(err); trace.Finish() }()
defer func() { trace.Finish(tracer.FinishWithError(err)) }()
tracer.Log(ctx, "data", data)
data.UpdatedAt = time.Now()
Expand All @@ -442,7 +442,7 @@ func (r *{{camel .ModuleName}}RepoMongo) Save(ctx context.Context, data *sharedd
func (r *{{camel .ModuleName}}RepoMongo) Delete(ctx context.Context, data *shareddomain.{{upper (camel .ModuleName)}}) (err error) {
trace, ctx := tracer.StartTraceWithContext(ctx, "{{upper (camel .ModuleName)}}RepoMongo:Delete")
defer func() { trace.SetError(err); trace.Finish() }()
defer func() { trace.Finish(tracer.FinishWithError(err)) }()
_, err = r.writeDB.Collection(r.collection).DeleteOne(ctx, bson.M{"_id": data.ID})
return
Expand Down Expand Up @@ -480,14 +480,14 @@ func New{{upper (camel .ModuleName)}}RepoArango(readDB, writeDB driver.Database)
func (r *{{camel .ModuleName}}RepoArango) FetchAll(ctx context.Context, filter *domain.Filter{{upper (camel .ModuleName)}}) (data []shareddomain.{{upper (camel .ModuleName)}}, err error) {
trace, ctx := tracer.StartTraceWithContext(ctx, "{{upper (camel .ModuleName)}}RepoArango:FetchAll")
defer func() { trace.SetError(err); trace.Finish() }()
defer func() { trace.Finish(tracer.FinishWithError(err)) }()
return
}
func (r *{{camel .ModuleName}}RepoArango) Find(ctx context.Context, filter *domain.Filter{{upper (camel .ModuleName)}}) (result shareddomain.{{upper (camel .ModuleName)}}, err error) {
trace, ctx := tracer.StartTraceWithContext(ctx, "{{upper (camel .ModuleName)}}RepoArango:Find")
defer func() { trace.SetError(err); trace.Finish() }()
defer func() { trace.Finish(tracer.FinishWithError(err)) }()
return
}
Expand All @@ -503,15 +503,15 @@ func (r *{{camel .ModuleName}}RepoArango) Count(ctx context.Context, filter *dom
func (r *{{camel .ModuleName}}RepoArango) Save(ctx context.Context, data *shareddomain.{{upper (camel .ModuleName)}}) (err error) {
trace, ctx := tracer.StartTraceWithContext(ctx, "{{upper (camel .ModuleName)}}RepoArango:Save")
defer func() { trace.SetError(err); trace.Finish() }()
defer func() { trace.Finish(tracer.FinishWithError(err)) }()
tracer.Log(ctx, "data", data)
return
}
func (r *{{camel .ModuleName}}RepoArango) Delete(ctx context.Context, data *shareddomain.{{upper (camel .ModuleName)}}) (err error) {
trace, ctx := tracer.StartTraceWithContext(ctx, "{{upper (camel .ModuleName)}}RepoArango:Delete")
defer func() { trace.SetError(err); trace.Finish() }()
defer func() { trace.Finish(tracer.FinishWithError(err)) }()
return
}
Expand Down Expand Up @@ -554,15 +554,13 @@ func New{{upper (camel .ModuleName)}}RepoSQL(readDB, writeDB *{{if .SQLUseGORM}}
func (r *{{camel .ModuleName}}RepoSQL) FetchAll(ctx context.Context, filter *domain.Filter{{upper (camel .ModuleName)}}) (data []shareddomain.{{upper (camel .ModuleName)}}, err error) {
trace, ctx := tracer.StartTraceWithContext(ctx, "{{upper (camel .ModuleName)}}RepoSQL:FetchAll")
defer func() { trace.SetError(err); trace.Finish() }()
defer func() { trace.Finish(tracer.FinishWithError(err)) }()
if filter.OrderBy == "" {
filter.OrderBy = ` + `"updated_at"` + `
}
{{if .SQLUseGORM}}db := {{ if .IsMonorepo }}global{{end}}shared.SetSpanToGorm(ctx, r.readDB)
err = db.Order(clause.OrderByColumn{
{{if .SQLUseGORM}}err = r.setFilter{{upper (camel .ModuleName)}}({{ if .IsMonorepo }}global{{end}}shared.SetSpanToGorm(ctx, r.readDB), filter).Order(clause.OrderByColumn{
Column: clause.Column{Name: filter.OrderBy},
Desc: strings.ToUpper(filter.Sort) == "DESC",
}).Limit(filter.Limit).Offset(filter.CalculateOffset()).Find(&data).Error
Expand All @@ -588,10 +586,8 @@ func (r *{{camel .ModuleName}}RepoSQL) Count(ctx context.Context, filter *domain
trace, ctx := tracer.StartTraceWithContext(ctx, "{{upper (camel .ModuleName)}}RepoSQL:Count")
defer trace.Finish()
{{if .SQLUseGORM}}db := {{ if .IsMonorepo }}global{{end}}shared.SetSpanToGorm(ctx, r.readDB)
var total int64
db.Model(&shareddomain.{{upper (camel .ModuleName)}}{}).Count(&total)
{{if .SQLUseGORM}}var total int64
r.setFilter{{upper (camel .ModuleName)}}({{ if .IsMonorepo }}global{{end}}shared.SetSpanToGorm(ctx, r.readDB), filter).Model(&shareddomain.{{upper (camel .ModuleName)}}{}).Count(&total)
count = int(total)
{{else}}r.readDB.QueryRow("SELECT COUNT(*) FROM {{snake .ModuleName}}s").Scan(&count){{end}}
trace.Log("count", count)
Expand All @@ -600,22 +596,17 @@ func (r *{{camel .ModuleName}}RepoSQL) Count(ctx context.Context, filter *domain
func (r *{{camel .ModuleName}}RepoSQL) Find(ctx context.Context, filter *domain.Filter{{upper (camel .ModuleName)}}) (result shareddomain.{{upper (camel .ModuleName)}}, err error) {
trace, ctx := tracer.StartTraceWithContext(ctx, "{{upper (camel .ModuleName)}}RepoSQL:Find")
defer func() { trace.SetError(err); trace.Finish() }()
{{if .SQLUseGORM}}db := {{ if .IsMonorepo }}global{{end}}shared.SetSpanToGorm(ctx, r.readDB)
if filter.ID != "" {
db = db.Where("id = ?", filter.ID)
}
defer func() { trace.Finish(tracer.FinishWithError(err)) }()
err = db.First(&result).Error
{{if .SQLUseGORM}}err = r.setFilter{{upper (camel .ModuleName)}}({{ if .IsMonorepo }}global{{end}}shared.SetSpanToGorm(ctx, r.readDB), filter).First(&result).Error
{{else}}err = r.readDB.QueryRow("SELECT id, field, created_at, updated_at FROM {{snake .ModuleName}}s WHERE id={{if eq .SQLDriver "postgres"}}$1{{else}}?{{end}}", filter.ID).
Scan(&result.ID, &result.Field, &result.CreatedAt, &result.UpdatedAt)
{{end}}return
}
func (r *{{camel .ModuleName}}RepoSQL) Save(ctx context.Context, data *shareddomain.{{upper (camel .ModuleName)}}) (err error) {
trace, ctx := tracer.StartTraceWithContext(ctx, "{{upper (camel .ModuleName)}}RepoSQL:Save")
defer func() { trace.SetError(err); trace.Finish() }()
defer func() { trace.Finish(tracer.FinishWithError(err)) }()
trace.Log("data", data)
{{if .SQLUseGORM}}db := r.writeDB
Expand Down Expand Up @@ -664,7 +655,7 @@ func (r *{{camel .ModuleName}}RepoSQL) Save(ctx context.Context, data *shareddom
func (r *{{camel .ModuleName}}RepoSQL) Delete(ctx context.Context, data *shareddomain.{{upper (camel .ModuleName)}}) (err error) {
trace, ctx := tracer.StartTraceWithContext(ctx, "{{upper (camel .ModuleName)}}RepoSQL:Delete")
defer func() { trace.SetError(err); trace.Finish() }()
defer func() { trace.Finish(tracer.FinishWithError(err)) }()
{{if .SQLUseGORM}}db := r.writeDB
if tx, ok := candishared.GetValueFromContext(ctx, candishared.ContextKeySQLTransaction).(*gorm.DB); ok {
Expand All @@ -683,6 +674,22 @@ func (r *{{camel .ModuleName}}RepoSQL) Delete(ctx context.Context, data *sharedd
}
_, err = stmt.ExecContext(ctx, data.ID)
{{end}}return
}
}{{if .SQLUseGORM}}
func (r *{{camel .ModuleName}}RepoSQL) setFilter{{upper (camel .ModuleName)}}(db *gorm.DB, filter *domain.Filter{{upper (camel .ModuleName)}}) *gorm.DB {
if filter.ID != nil {
db = db.Where("id = ?", *filter.ID)
}
if filter.Search != "" {
db = db.Where("(field ILIKE '%%' || ? || '%%')", filter.Search)
}
for _, preload := range filter.Preloads {
db = db.Preload(preload)
}
return db
}{{end}}
`
)
4 changes: 2 additions & 2 deletions cmd/candi/template_usecase.go
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ func (uc *{{camel .ModuleName}}UsecaseImpl) GetDetail{{upper (camel .ModuleName)
defer trace.Finish()
var data shareddomain.{{upper (camel .ModuleName)}}
{{if or .SQLDeps .MongoDeps .ArangoDeps}}repoFilter := domain.Filter{{upper (camel .ModuleName)}}{ID: id}
{{if or .SQLDeps .MongoDeps .ArangoDeps}}repoFilter := domain.Filter{{upper (camel .ModuleName)}}{ID: &id}
data, err = uc.repo{{if .SQLDeps}}SQL{{else if .MongoDeps}}Mongo{{else if .ArangoDeps}}Arango{{end}}.{{upper (camel .ModuleName)}}Repo().Find(ctx, &repoFilter){{end}}
if err != nil {
return result, err
Expand Down Expand Up @@ -354,7 +354,7 @@ func (uc *{{camel .ModuleName}}UsecaseImpl) Update{{upper (camel .ModuleName)}}(
trace, ctx := tracer.StartTraceWithContext(ctx, "{{upper (camel .ModuleName)}}Usecase:Update{{upper (camel .ModuleName)}}")
defer trace.Finish()
{{if or .SQLDeps .MongoDeps .ArangoDeps}}repoFilter := domain.Filter{{upper (camel .ModuleName)}}{ID: data.ID}
{{if or .SQLDeps .MongoDeps .ArangoDeps}}repoFilter := domain.Filter{{upper (camel .ModuleName)}}{ID: &data.ID}
existing, err := uc.repo{{if .SQLDeps}}SQL{{else if .MongoDeps}}Mongo{{else if .ArangoDeps}}Arango{{end}}.{{upper (camel .ModuleName)}}Repo().Find(ctx, &repoFilter)
if err != nil {
return err
Expand Down
2 changes: 1 addition & 1 deletion init.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@ package candi

const (
// Version of this library
Version = "v1.13.9"
Version = "v1.13.10"
)

0 comments on commit cab9d8a

Please sign in to comment.