-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathsys_routes.go
1144 lines (1102 loc) · 30.3 KB
/
sys_routes.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package kuu
import (
"bytes"
"errors"
"fmt"
"net/http"
"os"
"path"
"reflect"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/ghodss/yaml"
"github.com/gin-gonic/gin/binding"
"gopkg.in/guregu/null.v3"
)
var valueCacheMap sync.Map
// OrgLoginableRoute
var OrgLoginableRoute = RouteInfo{
Name: "查询可登录组织",
Method: "GET",
Path: "/org/loginable",
IntlMessages: map[string]string{
"org_query_failed": "Query organization failed",
},
HandlerFunc: func(c *Context) *STDReply {
c.IgnoreAuth()
data, err := GetLoginableOrgs(c, c.SignInfo.UID)
if err != nil {
return c.STDErr(err, "org_query_failed")
}
return c.STD(data)
},
}
// OrgSwitchRoute
var OrgSwitchRoute = RouteInfo{
Name: "切换当前登录组织",
Method: "POST",
Path: "/org/switch",
IntlMessages: map[string]string{
"org_switch_failed": "Switching organization failed",
},
HandlerFunc: func(c *Context) *STDReply {
var body struct {
ActOrgID uint
}
if err := c.ShouldBindJSON(&body); err != nil {
return c.STDErr(err, "org_switch_failed")
}
err := c.IgnoreAuth().DB().
Model(&User{ID: c.SignInfo.UID}).
Update(User{ActOrgID: body.ActOrgID}).Error
if err != nil {
return c.STDErr(err, "org_switch_failed")
}
return c.STDOK()
},
}
// UserRoleAssigns
var UserRoleAssigns = RouteInfo{
Name: "查询用户已分配角色",
Method: "GET",
Path: "/user/role_assigns/:uid",
IntlMessages: map[string]string{
"role_assigns_failed": "User roles query failed",
},
HandlerFunc: func(c *Context) *STDReply {
raw := c.Param("uid")
if raw == "" {
return c.STDErr(errors.New("UID is required"), "role_assigns_failed")
}
uid := ParseID(raw)
user, err := GetUserWithRoles(uid)
if err != nil {
return c.STDErr(err, "role_assigns_failed")
}
return c.STD(user.RoleAssigns)
},
}
// RoleUserAssigns
var RoleUserAssignsList = RouteInfo{
Name: "查询角色关联用户",
Method: "GET",
Path: "/role/user_assigns_list",
IntlMessages: map[string]string{
"role_users_assigns_failed": "Role assigns users query failed",
},
HandlerFunc: func(c *Context) *STDReply {
var roles []Role
DB().Model(&Role{}).Find(&roles)
return c.STDOK()
},
}
// RoleUserAssigns
var RoleUserAssigns = RouteInfo{
Name: "查询角色关联用户",
Method: "GET",
Path: "/role/user_assigns/:roleid",
IntlMessages: map[string]string{
"role_users_assigns_failed": "Role assigns users query failed",
},
HandlerFunc: func(c *Context) *STDReply {
raw := c.Param("roleid")
if raw == "" {
return c.STDErr(errors.New("roleid is required"), "role_users_assigns_failed")
}
id := ParseID(raw)
var userids []uint
DB().Model(&RoleAssign{}).Where("role_id = ?", id).Pluck("user_id", &userids)
var users []User
DB().Model(&User{}).Where("id in (?)", userids).Find(&users)
var result []map[string]any
for _, user := range users {
item := map[string]any{
"ID": user.ID,
"Name": user.Name,
"Username": user.Username,
"Mobile": user.Mobile,
"Disable": user.Disable,
"CreatedAt": user.CreatedAt,
}
if os.Getenv("HIDDEN_MOBILE") == "true" {
item["Mobile"] = hideMobile(user.Mobile)
}
result = append(result, item)
}
return c.STD(result)
},
}
type MenuList []Menu
func (ml MenuList) Len() int {
return len(ml)
}
func (ml MenuList) Less(i, j int) bool {
return ml[i].Sort.Int64 < ml[j].Sort.Int64
}
func (ml MenuList) Swap(i, j int) {
tmp := ml[i]
ml[i] = ml[j]
ml[j] = tmp
}
// UserMenusRoute
var UserMenusRoute = RouteInfo{
Name: "查询用户菜单",
Method: "GET",
Path: "/user/menus",
IntlMessages: map[string]string{
"user_menus_failed": "User menus query failed",
},
HandlerFunc: func(c *Context) *STDReply {
var menus MenuList
// 查询授权菜单
if err := c.DB().Find(&menus).Error; err != nil {
return c.STDErr(err, "user_menus_failed")
}
// 补全父级菜单
var total MenuList
if err := c.IgnoreAuth().DB().Find(&total).Error; err != nil {
return c.STDErr(err, "user_menus_failed")
}
// 有sys_menu权限的直接返回所有菜单
if c.PrisDesc.HasPermission("sys_menu") {
sort.Sort(total)
return c.STD(total)
}
var (
codeMap = make(map[string]Menu)
existsMap = make(map[uint]bool)
finded = make(map[uint]bool)
)
for _, item := range total {
codeMap[item.Code] = item
}
for _, item := range menus {
existsMap[item.ID] = true
}
var fall func(result MenuList) MenuList
fall = func(result MenuList) MenuList {
recall := false
for _, item := range result {
if !finded[item.ID] {
pitem := codeMap[item.ParentCode.String]
if item.ParentCode.String != "" && pitem.ID != 0 && !existsMap[pitem.ID] {
result = append(result, pitem)
recall = true
existsMap[pitem.ID] = true
}
finded[item.ID] = true
}
}
if recall {
return fall(result)
}
return result
}
menus = fall(menus)
if strings.ToLower(c.DefaultQuery("default", "true")) == "false" {
var filtered MenuList
for _, item := range menus {
if item.Code != "default" {
filtered = append(filtered, item)
}
}
menus = filtered
}
sort.Sort(menus)
return c.STD(menus)
},
}
func getFileExtraData(c *Context) (*File, error) {
class := c.PostForm("Class")
ownerID := (uint)(0)
if v := c.PostForm("OwnerID"); v != "" {
vv, err := strconv.ParseUint(v, 10, 64)
if err != nil {
return nil, err
}
ownerID = (uint)(vv)
}
ownerType := c.PostForm("OwnerType")
return &File{Class: class, OwnerID: ownerID, OwnerType: ownerType}, nil
}
// UploadRoute
var UploadRoute = RouteInfo{
Name: "默认文件上传接口",
Method: "POST",
Path: "/upload",
IntlMessages: map[string]string{
"upload_failed": "Upload file failed",
},
HandlerFunc: func(c *Context) *STDReply {
var (
save2db = true
)
if v, ok := c.GetPostForm("save2db"); ok {
if b, err := strconv.ParseBool(v); err == nil {
save2db = b
}
}
extra, err := getFileExtraData(c)
if err != nil {
return c.STDErr(err, "upload_failed")
}
fh, err := c.FormFile("file")
if err != nil {
return c.STDErr(err, "upload_failed")
}
file, err := SaveUploadedFile(fh, save2db, extra)
if err != nil {
return c.STDErr(err, "upload_failed")
}
return c.STD(file)
},
}
// AuthRoute
var AuthRoute = RouteInfo{
Name: "操作权限鉴权接口",
Method: "GET",
Path: "/auth",
IntlMessages: map[string]string{
"auth_failed": "Authentication failed",
},
HandlerFunc: func(c *Context) *STDReply {
ps := c.Query("p")
split := strings.Split(ps, ",")
if len(split) == 0 {
return c.STDErr(errors.New("param 'p' is required"), "auth_failed")
}
ret := make(map[string]bool)
for _, s := range split {
_, has := c.PrisDesc.PermissionMap[s]
ret[s] = has
}
return c.STD(ret)
},
}
var ChangePassword = RouteInfo{
Name: "修改密码",
Method: "POST",
Path: "/changepasswd",
IntlMessages: map[string]string{
"parse_body_failed": "解析请求参数失败",
"oldpasswd_error": "旧密码错误",
"newpasswd_error": "新密码错误",
},
HandlerFunc: func(c *Context) *STDReply {
var body = struct {
OldPasswd string `binding:"required"`
NewPasswd string `binding:"required"`
}{}
if err := c.ShouldBindBodyWith(&body, binding.JSON); err != nil {
return c.STDErr(err, "parse_body_failed")
}
var user User
DB().Model(&User{}).Where("id = ?", c.PrisDesc.UID).First(&user)
if user.ID == 0 {
return c.STDErr(errors.New("用户不存在"), "parse_body_failed")
}
body.OldPasswd = strings.ToLower(body.OldPasswd)
if err := CompareHashAndPassword(user.Password, body.OldPasswd); err != nil {
return c.STDErr(err, "oldpasswd_error")
}
passwd, err := GenerateFromPassword(strings.ToLower(body.NewPasswd))
if err != nil {
return c.STDErr(err, "newpasswd_error")
}
DB().Model(&User{}).
Where("id = ?", c.PrisDesc.UID).
Updates(map[string]any{
"Password": passwd,
"LastChangePasswordTime": time.Now(),
})
return c.STDOK()
},
}
// MetaRoute
var MetaRoute = RouteInfo{
Name: "查询元数据列表",
Method: "GET",
Path: "/meta",
HandlerFunc: func(c *Context) *STDReply {
json := c.Query("json")
name := c.Query("name")
mod := c.Query("mod")
var list []*Metadata
if name != "" {
for _, name := range strings.Split(name, ",") {
if v, ok := metadataMap[name]; ok && v != nil {
list = append(list, v)
}
}
} else if mod != "" {
for _, item := range strings.Split(mod, ",") {
for _, meta := range metadataList {
if meta.ModCode == item {
list = append(list, meta)
}
}
}
} else {
list = metadataList
}
if json != "" {
return c.STD(list)
} else {
var (
hashKey = fmt.Sprintf("meta_%s_%s", name, mod)
result string
)
if v, ok := valueCacheMap.Load(hashKey); ok {
result = v.(string)
} else {
var buffer bytes.Buffer
for _, m := range list {
if len(m.Fields) > 0 {
if m.DisplayName != "" {
buffer.WriteString(fmt.Sprintf("%s(%s) {\n", m.Name, m.DisplayName))
} else {
buffer.WriteString(fmt.Sprintf("%s {\n", m.Name))
}
for index, field := range m.Fields {
if field.Enum != "" {
buffer.WriteString(fmt.Sprintf("\t%s %s ENUM(%s)", field.Code, field.Name, field.Enum))
} else {
buffer.WriteString(fmt.Sprintf("\t%s %s %s", field.Code, field.Name, field.Type))
}
if index != len(m.Fields)-1 {
buffer.WriteString("\n")
}
}
buffer.WriteString(fmt.Sprintf("\n}\n\n"))
}
}
result = buffer.String()
valueCacheMap.Store(hashKey, result)
}
c.String(http.StatusOK, result)
return nil
}
},
}
// EnumRoute
var EnumRoute = RouteInfo{
Name: "查询枚举列表",
Path: "/enum",
Method: "GET",
HandlerFunc: func(c *Context) *STDReply {
json := c.Query("json")
name := c.Query("name")
em := EnumMap()
var list []*EnumDesc
if name != "" {
for _, name := range strings.Split(name, ",") {
if v, ok := em[name]; ok && v != nil {
list = append(list, v)
}
}
} else {
list = EnumList()
}
if json != "" {
return c.STD(list)
} else {
var buffer bytes.Buffer
for _, desc := range list {
if desc.ClassName != "" {
buffer.WriteString(fmt.Sprintf("%s(%s) {\n", desc.ClassCode, desc.ClassName))
} else {
buffer.WriteString(fmt.Sprintf("%s {\n", desc.ClassCode))
}
index := 0
for value, label := range desc.Values {
if len(label) < 20 {
for i := 0; i < 20-len(label); i++ {
label += " "
}
}
buffer.WriteString(fmt.Sprintf("\t%s\t%v(%s)", label, value, reflect.ValueOf(value).Type().Kind().String()))
if index != len(desc.Values)-1 {
buffer.WriteString("\n")
}
index++
}
buffer.WriteString(fmt.Sprintf("\n}\n\n"))
}
c.String(http.StatusOK, buffer.String())
return nil
}
},
}
// DataDictRoute
var DataDictRoute = RouteInfo{
Name: "查询数据字典",
Method: "GET",
Path: "/datadict",
HandlerFunc: func(c *Context) *STDReply {
modCode := c.Query("modCode")
var buff strings.Builder
buff.WriteString(fmt.Sprintf("# %s数据字典\n\n", C().GetString("name")))
var modname string
bookmap := map[bool]string{true: "是", false: "否"}
m := DefaultCache.HGetAll(BuildKey("datadict"))
var keys []string
for k, _ := range m {
keys = append(keys, k)
}
sort.Strings(keys)
for _, key := range keys {
item := m[key]
var meta Metadata
err := JSONParse(item, &meta)
if err != nil {
return c.STDErr(err)
}
if meta.ModCode == "" {
continue
}
if modCode != "" && meta.ModCode != modCode {
continue
}
if modname != meta.ModCode {
modname = meta.ModCode
buff.WriteString(fmt.Sprintf("## %s\n\n", meta.ModCode))
}
buff.WriteString(fmt.Sprintf("### %s_%s %s\n\n", meta.ModCode, meta.NativeName, meta.DisplayName))
buff.WriteString("|字段名|字段类型|是否可空|是否主键|注释|\n")
buff.WriteString("| :--- | :--- | :--- | :--- | :--- |\n")
for _, field := range meta.Fields {
IsBland := bookmap[field.IsBland]
IsPrimaryKey := bookmap[field.IsPrimaryKey]
line := fmt.Sprintf("| %s | %s | %s | %s | %s |\n", field.NativeName, field.DBType, IsBland, IsPrimaryKey, field.Name)
buff.WriteString(line)
}
buff.WriteString("\n\n")
}
c.String(http.StatusOK, buff.String())
return nil
},
}
// CaptchaRoute
var CaptchaRoute = RouteInfo{
Name: "查询验证码",
Path: "/captcha",
Method: "GET",
HandlerFunc: func(c *Context) *STDReply {
var (
user = c.Query("user")
valid bool
)
if user != "" {
times := GetCacheInt(getFailedTimesKey(user))
valid = failedTimesValid(times)
}
if valid == false {
return c.STD(null.BoolFrom(valid))
}
// 生成验证码
id, base64Str := GenerateCaptcha()
c.SetCookie(CaptchaIDKey, id, ExpiresSeconds, "/", "", false, true)
return c.STD(D{
"id": id,
"base64Str": base64Str,
})
},
}
// ModelDocsRoute
var ModelDocsRoute = RouteInfo{
Name: "查询默认接口文档",
Method: "GET",
Path: "/model/docs",
IntlMessages: map[string]string{
"model_docs_failed": "Model document query failed",
},
HandlerFunc: func(c *Context) *STDReply {
var (
hashKeyYAML = "model_docs_yaml"
hashKeyJSON = "model_docs_json"
)
json := c.Query("json") != ""
// 取缓存
if json {
if v, ok := valueCacheMap.Load(hashKeyJSON); ok {
c.String(http.StatusOK, v.(string))
return nil
}
} else {
if v, ok := valueCacheMap.Load(hashKeyYAML); ok {
c.String(http.StatusOK, v.(string))
return nil
}
}
// 重新生成
var validMeta []*Metadata
for _, m := range metadataList {
if m == nil || m.RestDesc == nil || !m.RestDesc.IsValid() || len(m.Fields) == 0 {
continue
}
validMeta = append(validMeta, m)
}
name := GetAppName()
doc := Doc{
Openapi: "3.0.1",
Info: DocInfo{
Title: fmt.Sprintf("%s 模型默认接口文档", name),
Description: "调用说明:\n" +
"1. 本文档仅包含数据模型默认开放的增删改查RESTful接口\n" +
"1. 接口请求/响应的Content-Type默认为application/json,UTF-8编码\n" +
"1. 如未额外说明,接口响应格式默认为以下JSON格式:\n" +
"\t- `code` - **业务状态码**,0表成功,非0表失败(错误码默认为-1,令牌失效为555),该值一定存在,请按照该值判断业务操作是否成功,`integer`\n" +
"\t- `msg` - **提示信息**,表正常或异常情况下的提示信息,有值才存在,`string`\n" +
"\t- `data` - **数据部分**,正常时返回请求数据,异常时返回错误详情,有值才存在,`类型视具体接口而定`\n" +
"1. 日期格式为`2019-06-04T02:42:01.472Z`,js代码:`new Date().toISOString()`\n" +
"1. 用户密码等信息统一为MD5加密后的32位小写字符串,npm推荐使用blueimp-md5" +
"",
Version: "1.0.0",
Contact: DocInfoContact{
Email: "[email protected]",
},
},
Servers: []DocServer{
{Url: fmt.Sprintf("%s%s", c.Origin(), C().GetString("prefix")), Description: "默认服务器"},
},
Tags: func() (tags []DocTag) {
tags = []DocTag{{Name: "辅助接口"}}
for _, m := range validMeta {
tags = append(tags, DocTag{
Name: m.Name,
Description: m.DisplayName,
})
}
return
}(),
Paths: func() (paths map[string]DocPathItems) {
paths = map[string]DocPathItems{
"/meta": {
"get": {
Tags: []string{"辅助接口"},
Summary: "查询模型列表",
OperationID: "meta",
Responses: map[int]DocPathResponse{
200: {
Description: "查询模型列表成功",
Content: map[string]DocPathContentItem{
"text/plain": {
Schema: DocPathSchema{Type: "string"},
},
},
},
},
},
},
"/enum": {
"get": {
Tags: []string{"辅助接口"},
Summary: "查询枚举列表",
OperationID: "enum",
Responses: map[int]DocPathResponse{
200: {
Description: "查询枚举列表成功",
Content: map[string]DocPathContentItem{
"text/plain": {
Schema: DocPathSchema{Type: "string"},
},
},
},
},
},
},
"/upload": {
"post": {
Tags: []string{"辅助接口"},
Summary: "上传文件",
OperationID: "upload",
RequestBody: DocPathRequestBody{
Content: map[string]DocPathContentItem{
"multipart/form-data": {
Schema: DocPathSchema{
Type: "object",
Properties: map[string]DocPathSchema{
"file": {
Type: "string",
Format: "binary",
Description: "文件",
},
},
},
},
},
},
Responses: map[int]DocPathResponse{
200: {
Description: "上传成功",
Content: map[string]DocPathContentItem{
"application/json": {
Schema: DocPathSchema{Type: "string"},
},
},
},
},
Security: []DocPathItemSecurity{
map[string][]string{
"api_key": {},
},
},
},
},
"/whitelist": {
"get": {
Tags: []string{"辅助接口"},
Summary: "接口白名单",
Description: "接口白名单是指`不需要任何令牌`,可直接访问的接口,请前往在线链接查看最新列表",
OperationID: "whitelist",
Responses: map[int]DocPathResponse{
200: {
Description: "查询接口白名单成功",
Content: map[string]DocPathContentItem{
"text/plain": {
Schema: DocPathSchema{Type: "string"},
},
},
},
},
},
},
}
for _, m := range validMeta {
key := strings.ToLower(path.Join(GetModPrefix(m.ModCode), fmt.Sprintf("/%s", m.Name)))
items := make(DocPathItems)
displayName := m.DisplayName
if displayName == "" {
displayName = m.Name
}
// 新增接口
if m.RestDesc.Create {
items["post"] = DocPathItem{
Tags: []string{m.Name},
Summary: fmt.Sprintf("新增%s", displayName),
Description: "注意:\n1. 如需批量新增,请传递对象数组\n1. 当你请求体为对象格式时,返回数据也为对象格式\n1. 当你请求体为对象数组时,返回数据也为对象数组",
OperationID: fmt.Sprintf("create%s", m.Name),
RequestBody: DocPathRequestBody{
Required: true,
Description: fmt.Sprintf("%s对象", displayName),
Content: map[string]DocPathContentItem{
"application/json": {
Schema: DocPathSchema{
Ref: fmt.Sprintf("#/components/schemas/%s", m.Name),
},
},
},
},
Responses: map[int]DocPathResponse{
200: {
Description: fmt.Sprintf("新增%s成功", displayName),
Content: map[string]DocPathContentItem{
"application/json": {
Schema: DocPathSchema{
Ref: fmt.Sprintf("#/components/schemas/%s", m.Name),
},
},
},
},
},
Security: []DocPathItemSecurity{
map[string][]string{
"api_key": {},
},
},
}
}
// 删除接口
if m.RestDesc.Delete {
items["delete"] = DocPathItem{
Tags: []string{m.Name},
Summary: fmt.Sprintf("删除%s", displayName),
Description: "注意:\n如需批量删除,请指定multi=true",
OperationID: fmt.Sprintf("delete%s", m.Name),
Parameters: []DocPathParameter{
{
Name: "cond",
In: "query",
Required: true,
Description: "删除条件,JSON格式的字符串",
Schema: DocPathSchema{
Type: "string",
},
},
{
Name: "multi",
In: "query",
Description: "是否批量删除",
Schema: DocPathSchema{
Type: "boolean",
},
},
},
Responses: map[int]DocPathResponse{
200: {
Description: fmt.Sprintf("删除%s成功", displayName),
Content: map[string]DocPathContentItem{
"application/json": {
Schema: DocPathSchema{
Ref: fmt.Sprintf("#/components/schemas/%s", m.Name),
},
},
},
},
},
Security: []DocPathItemSecurity{
map[string][]string{
"api_key": {},
},
},
}
}
// 修改接口
if m.RestDesc.Update {
items["put"] = DocPathItem{
Tags: []string{m.Name},
Summary: fmt.Sprintf("修改%s", displayName),
Description: "注意:\n如需批量修改,请指定multi=true",
OperationID: fmt.Sprintf("update%s", m.Name),
RequestBody: DocPathRequestBody{
Required: true,
Description: fmt.Sprintf("%s对象", displayName),
Content: map[string]DocPathContentItem{
"application/json": {
Schema: DocPathSchema{
Type: "object",
Properties: map[string]DocPathSchema{
"cond": {
Ref: fmt.Sprintf("#/components/schemas/%s", m.Name),
Required: true,
},
"doc": {
Ref: fmt.Sprintf("#/components/schemas/%s", m.Name),
Required: true,
},
"multi": {
Type: "boolean",
},
},
},
},
},
},
Responses: map[int]DocPathResponse{
200: {
Description: fmt.Sprintf("修改%s成功", displayName),
Content: map[string]DocPathContentItem{
"application/json": {
Schema: DocPathSchema{
Ref: fmt.Sprintf("#/components/schemas/%s", m.Name),
},
},
},
},
},
Security: []DocPathItemSecurity{
map[string][]string{
"api_key": {},
},
},
}
}
// 查询接口
if m.RestDesc.Query {
items["get"] = DocPathItem{
Tags: []string{m.Name},
Summary: fmt.Sprintf("查询%s", displayName),
OperationID: fmt.Sprintf("query%s", m.Name),
Parameters: []DocPathParameter{
{
Name: "range",
In: "query",
Description: "查询数据范围,分页(PAGE)或全量(ALL)",
Schema: DocPathSchema{
Type: "string",
Enum: []interface{}{
"PAGE",
"ALL",
},
Default: "PAGE",
},
},
{
Name: "cond",
In: "query",
Description: fmt.Sprintf("查询条件,%s对象的JSON字符串", displayName),
Schema: DocPathSchema{
Type: "string",
},
},
{
Name: "sort",
In: "query",
Description: "排序字段,多字段排序以英文逗号分隔,逆序以负号开头",
Schema: DocPathSchema{
Type: "string",
},
},
{
Name: "project",
In: "query",
Description: "查询字段,注意字段依然返回,只是不查询",
Schema: DocPathSchema{
Type: "string",
},
},
{
Name: "page",
In: "query",
Description: "当前页码(仅PAGE模式有效)",
Schema: DocPathSchema{
Type: "integer",
Default: 1,
},
},
{
Name: "size",
In: "query",
Description: "每页条数(仅PAGE模式有效)",
Schema: DocPathSchema{
Type: "integer",
Default: 30,
},
},
},
Responses: map[int]DocPathResponse{
200: {
Description: fmt.Sprintf("查询%s成功", displayName),
Content: map[string]DocPathContentItem{
"application/json": {
Schema: DocPathSchema{
Type: "object",
Properties: map[string]DocPathSchema{
"list": {
Type: "array",
Items: &DocPathSchema{
Ref: fmt.Sprintf("#/components/schemas/%s", m.Name),
},
},
"totalrecords": {
Type: "integer",
Description: "当前查询条件下的总记录数",
},
"totalpages": {
Type: "integer",
Description: "当前查询条件下的总页数(仅PAGE模式存在)",
},
},
},
},
},
},
},
Security: []DocPathItemSecurity{
map[string][]string{
"api_key": {},
},
},
}
}
if len(items) > 0 {
paths[key] = items
}
}
return
}(),
Components: DocComponent{
Schemas: func() (schemas map[string]DocComponentSchema) {
schemas = make(map[string]DocComponentSchema)
em := EnumMap()
for _, m := range validMeta {
props := make(map[string]DocSchemaProperty)
for _, f := range m.Fields {
prop := DocSchemaProperty{}
if f.Name != "" {
prop.Title = f.Name
}
if f.IsRef {
if f.IsArray {
prop.Type = "array"
prop.Items = &DocSchemaProperty{
Ref: fmt.Sprintf("#/components/schemas/%s", f.Type),
}
} else {
prop.Ref = fmt.Sprintf("#/components/schemas/%s", f.Type)
}
} else {
prop.Type = f.Type
}
if f.Enum != "" && em[f.Enum] != nil {
for value, _ := range em[f.Enum].Values {
prop.Enum = append(prop.Enum, value)
}
}
props[f.Code] = prop
}
schemas[m.Name] = DocComponentSchema{
Type: "object",
Properties: props,
}
}
return
}(),
SecuritySchemes: map[string]DocSecurityScheme{
"api_key": {
Type: "apiKey",
Name: "api_key",
In: "header",
},
},
},
}
yml := doc.Marshal()
if json {
data, err := yaml.YAMLToJSON([]byte(yml))
if err != nil {
return c.STDErr(err, "model_docs_failed")
}
json := string(data)
valueCacheMap.Store(hashKeyJSON, json)
c.String(http.StatusOK, json)
} else {
valueCacheMap.Store(hashKeyYAML, yml)
c.String(http.StatusOK, yml)
}