Skip to content

Commit

Permalink
refactor(openapi): MarkdownProblems 根据 titleLevel 确定是否忽略 detail
Browse files Browse the repository at this point in the history
  • Loading branch information
caixw committed Dec 2, 2024
1 parent d39e28b commit 3ceadd1
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 8 deletions.
1 change: 1 addition & 0 deletions locales/zh.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
languages:
- zh-Hans
- cmn-Hans
- zh-CN
messages:
- key: SSE keep alive cron
message:
Expand Down
26 changes: 23 additions & 3 deletions openapi/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,11 +96,31 @@ func getPathParams(path string) []string {

// MarkdownProblems 将 problems 的内容生成为 markdown
//
// titleLevlel 标题的级别,1-6;
func MarkdownProblems(s web.Server, titleLevlel int) web.LocaleStringer {
// titleLevel 标题的级别,0-6:
// 如果取值为 0,表示以列表的形式输出,并忽略 detail 字段的内容。
// 1-6 表示输出 detail 内容,并且将 type 和 title 作为标题;
func MarkdownProblems(s web.Server, titleLevel int, detail bool) web.LocaleStringer {
if detail {
return markdownProblemsWithDetail(s, titleLevel)
} else {
return markdownProblemsWithoutDetail(s)
}
}

func markdownProblemsWithoutDetail(s web.Server) web.LocaleStringer {
buf := &errwrap.Buffer{}
args := make([]any, 0, 30)
s.Problems().Visit(func(status int, lp *web.LocaleProblem) {
buf.Printf("- %s", lp.Type()).WString(": %s\n\n")
args = append(args, lp.Title)
})
return web.Phrase(buf.String(), args...)
}

func markdownProblemsWithDetail(s web.Server, titleLevel int) web.LocaleStringer {
buf := &errwrap.Buffer{}
ss := strings.Repeat("#", titleLevel)

ss := strings.Repeat("#", titleLevlel)
args := make([]any, 0, 30)
s.Problems().Visit(func(status int, lp *web.LocaleProblem) {
buf.Printf("%s %s ", ss, lp.Type()).
Expand Down
9 changes: 4 additions & 5 deletions openapi/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,15 +54,14 @@ func TestMarkdownProblems(t *testing.T) {
ss := newServer(a)
p := ss.Locale().NewPrinter(language.SimplifiedChinese)

txt := MarkdownProblems(ss, 2)
txt := MarkdownProblems(ss, 2, true)
lines := strings.Split(txt.LocaleString(p), "\n\n")
a.Equal(lines[0], "## 400 Bad Request").
Equal(lines[1], "表示客户端错误,比如,错误的请求语法、无效的请求消息帧或欺骗性的请求路由等,服务器无法或不会处理该请求。").
Equal(lines[2], "## 401 Unauthorized")

txt = MarkdownProblems(ss, 3)
txt = MarkdownProblems(ss, 3, false)
lines = strings.Split(txt.LocaleString(p), "\n\n")
a.Equal(lines[0], "### 400 Bad Request").
Equal(lines[1], "表示客户端错误,比如,错误的请求语法、无效的请求消息帧或欺骗性的请求路由等,服务器无法或不会处理该请求。").
Equal(lines[2], "### 401 Unauthorized")
a.Equal(lines[0], "- 400: Bad Request").
Equal(lines[1], "- 401: Unauthorized")
}

0 comments on commit 3ceadd1

Please sign in to comment.