Skip to content

Commit

Permalink
增加gen model api 接口
Browse files Browse the repository at this point in the history
  • Loading branch information
jianfengye committed Mar 13, 2023
1 parent 453dbd9 commit 4ff1dab
Show file tree
Hide file tree
Showing 4 changed files with 166 additions and 13 deletions.
67 changes: 65 additions & 2 deletions docs/guide/model.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,47 @@

## 指南

hade 提供了自动生成数据库模型的命令行工具
hade model 提供了自动生成数据库模型的命令行工具,如果你已经定义好你的model,这里的系列工具能帮助你节省不少时间。

```shell
> ./hade model
数据库模型相关的命令

Usage:
hade model [flags]
hade model [command]

Available Commands:
api 通过数据库生成api
gen 生成模型
test 测试数据库

Flags:
-h, --help help for model
```

包含三个命令:

* ./hade model api 通过数据表自动生成api代码
* ./hade model gen 通过数据表自动生成model代码
* ./hade model test 测试某个数据库是否可以连接

## ./hade test

当你想测试下你的某个配置好的数据库是否能连接上,都有哪些表的时候,这个命令能帮助你。

```shell
> ./hade model test --database="database.default"
数据库连接:database.default成功
一共存在1张表
student
```

## ./hade model gen

这个命令帮助你生成数据表对应的gorm的model

```shell
✘  ~/Documents/workspace/gohade/hade   feature/model-gen ●  ./hade model gen
Error: required flag(s) "output" not set
Usage:
Expand All @@ -23,7 +61,7 @@ database: 这个参数可选,用来表示模型连接的数据库配置地址

output:这个参数必填,用来表示模型文件的输出地址,如果填写相对路径,会在前面填充当前执行路径来补充为绝对路径。

## 使用方式
### 使用方式

第一步,使用 `./hade model gen --output=app/model`

Expand All @@ -45,4 +83,29 @@ output:这个参数必填,用来表示模型文件的输出地址,如果

![image-20220215091735434](http://tuchuang.funaio.cn/img/image-20220215091735434.png)

## ./hade model api

```shell
> ./hade model api --database=database.default --output=/Users/jianfengye/Documents/workspace/gohade/hade/app/http/module/student/
```

![](http://tuchuang.funaio.cn/markdown/202303140005210.png)

它会在目标文件夹中生成对这个数据表的5个接口文件

* gen_[table]_api_create.go
* gen_[table]_api_delete.go
* gen_[table]_api_list.go
* gen_[table]_api_show.go
* gen_[table]_api_update.go

还有另外两个文件

* gen_[table]_model.go // 数据表对应的模型结构
* gen_[table]_router.go // 5个接口对应的默认路由

> 这里的每个文件都是可以修改的。
>
> 但是注意,如果重新生成,会覆盖原先的文件。
>
> 执行命令的时候切记保存已经改动的代码文件。
16 changes: 14 additions & 2 deletions framework/command/model/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,16 @@ package model

import (
"fmt"
"os"
"path/filepath"
"strings"

"github.com/AlecAivazis/survey/v2"
"github.com/gohade/hade/framework/cobra"
"github.com/gohade/hade/framework/contract"
"github.com/gohade/hade/framework/provider/orm"
"github.com/gohade/hade/framework/util"
"github.com/pkg/errors"
"path/filepath"
"strings"
)

// modelApiCommand 生成api
Expand Down Expand Up @@ -113,6 +115,12 @@ var modelApiCommand = &cobra.Command{
// get folder last string split by path separator
apiGenerator.SetPackageName(strings.ToLower(filepath.Base(folder)))

if !util.Exists(folder) {
if err := os.Mkdir(folder, 0755); err != nil {
return errors.Wrap(err, "create folder error")
}
}

if err := apiGenerator.GenModelFile(ctx, modelFile); err != nil {
return errors.Wrap(err, "GenModelFile error")
}
Expand Down Expand Up @@ -149,6 +157,10 @@ var modelApiCommand = &cobra.Command{
fmt.Println(getFileTip(apiUpdateFile))
}

fmt.Println("=======================")
fmt.Println("生成结束,请记得挂载路由到route.go中")
fmt.Println("!!! hade代码生成器按照既定程序生成文件,请自行仔细检查代码逻辑 !!!")
fmt.Println("=======================")
return nil
},
}
94 changes: 86 additions & 8 deletions framework/command/model/api_gen.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
package model

import (
"context"
"github.com/dave/jennifer/jen"
"github.com/gohade/hade/framework/contract"
"github.com/gohade/hade/framework/util/word"
"github.com/pkg/errors"
"os"
"strings"
"context"
"os"
"strings"

"github.com/dave/jennifer/jen"
"github.com/gohade/hade/framework/contract"
"github.com/gohade/hade/framework/util/word"
"github.com/pkg/errors"
)

type ApiGenerator struct {
Expand Down Expand Up @@ -136,8 +137,21 @@ func (gen *ApiGenerator) GenApiCreateFile(ctx context.Context, file string) erro
tableApi := tableCamel + "Api"
tableModel := tableCamel + "Model"

comment := ` Create create ${table}
@Summary create ${table}
@Produce json
@Tags ${table}
@Param ${table} body ${tableModel} true "${tableModel}"
@Success 200 {object} ${tableModel}
@Failure 400 {object} gin.H
@Failure 500 {object} gin.H
@Router /${table}/create [post]`
comment = strings.ReplaceAll(comment, "${tableModel}", tableModel)
comment = strings.ReplaceAll(comment, "${table}", tableLower)

f := jen.NewFile(gen.packageName)

f.Comment(comment)
f.Func().Params(
jen.Id("api").Op("*").Id(tableApi),
).Id("Create").Params(
Expand Down Expand Up @@ -204,6 +218,22 @@ func (gen *ApiGenerator) GenApiDeleteFile(ctx context.Context, file string) erro

f := jen.NewFile(gen.packageName)

comment := ` Delete godoc
@Summary Delete a ${table} by ID
@Description Delete a ${table} by ID
@Tags ${table}
@Accept json
@Produce json
@Param id query int true "ID"
@Success 200 {string} string "success"
@Failure 400 {object} ErrorResponse "Invalid parameter"
@Failure 404 {object} ErrorResponse "Record not found"
@Failure 500 {object} ErrorResponse "Server error"
@Router /${table}/delete [post]`
comment = strings.ReplaceAll(comment, "${tableModel}", tableModel)
comment = strings.ReplaceAll(comment, "${table}", tableLower)

f.Comment(comment)
f.Func().Params(
jen.Id("api").Op("*").Id(tableApi),
).Id("Delete").Params(
Expand Down Expand Up @@ -269,6 +299,22 @@ func (gen *ApiGenerator) GenApiListFile(ctx context.Context, file string) error

f := jen.NewFile(gen.packageName)

comment := ` List godoc
@Summary Get a list of ${table}
@Description Get a list of ${table} with pagination support
@Tags ${table}
@Accept json
@Produce json
@Param offset query integer true "offset"
@Param size query integer true "size"
@Success 200 {object} gin.H
@Failure 400 {object} gin.H
@Failure 500 {object} gin.H
@Router /${table}/list [get]`
comment = strings.ReplaceAll(comment, "${tableModel}", tableModel)
comment = strings.ReplaceAll(comment, "${table}", tableLower)

f.Comment(comment)
f.Func().Params(jen.Id("api").Op("*").Id(tableApi)).Id("List").Params(jen.Id("c").Op("*").Qual("github.com/gohade/hade/framework/gin", "Context")).Block(
jen.List(jen.Id("offset"), jen.Id("err")).Op(":=").Qual("strconv",
"Atoi").Call(jen.Id("c").Dot("Query").Call(jen.Lit("offset"))),
Expand Down Expand Up @@ -332,6 +378,22 @@ func (gen *ApiGenerator) GenApiShowFile(ctx context.Context, file string) error

f := jen.NewFile(gen.packageName)

comment := ` Show godoc
@Summary Get a ${table} by ID
@Description Get a ${table} by ID
@Tags ${table}
@Accept json
@Produce json
@Param id query integer true "${table} ID"
@Success 200 {object} ${tableModel}
@Failure 400 {object} gin.H
@Failure 404 {object} gin.H
@Failure 500 {object} gin.H
@Router /${table}/{id} [get]`
comment = strings.ReplaceAll(comment, "${tableModel}", tableModel)
comment = strings.ReplaceAll(comment, "${table}", tableLower)

f.Comment(comment)
f.Func().Params(jen.Id("api").Op("*").Id(tableApi)).Id("Show").Params(jen.Id("c").Op("*").Qual("github.com/gohade/hade/framework/gin", "Context")).Block(

jen.List(jen.Id("id"), jen.Id("err")).Op(":=").Qual("strconv", "Atoi").Call(jen.Id("c").Dot("Query").Call(jen.Lit("id"))),
Expand Down Expand Up @@ -387,7 +449,23 @@ func (gen *ApiGenerator) GenApiUpdateFile(ctx context.Context, file string) erro
tableModel := tableCamel + "Model"

f := jen.NewFile(gen.packageName)

comment := ` Update godoc
@Summary Update a ${table} by ID
@Description Update a ${table} by ID
@Tags ${table}
@Accept json
@Produce json
@Param id query int true "ID of the ${table} to update"
@Param student body ${tableModel} true "${table} information to update"
@Success 200 {object} ${tableModel}
@Failure 400 {object} gin.H
@Failure 404 {object} gin.H
@Failure 500 {object} gin.H
@Router /${table}/update [post]`
comment = strings.ReplaceAll(comment, "${tableModel}", tableModel)
comment = strings.ReplaceAll(comment, "${table}", tableLower)

f.Comment(comment)
f.Func().Params(jen.Id("api").Op("*").Id(tableApi)).Id("Update").Params(jen.Id("c").Op("*").Qual("github.com/gohade/hade/framework/gin", "Context")).Block(
jen.List(jen.Id("id"), jen.Id("err")).Op(":=").Qual("strconv", "Atoi").Call(jen.Id("c").Dot("Query").Call(jen.Lit("id"))),
jen.If(jen.Err().Op("!=").Nil()).Block(
Expand Down
2 changes: 1 addition & 1 deletion framework/provider/app/version.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package app

// HadeVersion hade的版本
const HadeVersion = "1.0.5"
const HadeVersion = "1.0.6"

0 comments on commit 4ff1dab

Please sign in to comment.