From a807899f95c1ca5f33cfac43ddac511d0603b701 Mon Sep 17 00:00:00 2001 From: Max Date: Wed, 1 Feb 2023 17:25:11 +0800 Subject: [PATCH] [*] migrate to gou v0.10.3 (50%) --- api/api.go | 59 +-- api/api_test.go | 6 +- app/README.md | 1 - app/app.go | 82 ----- app/app_test.go | 15 - brain/README.md | 8 - brain/behaviors/listen/listen.go | 1 - brain/behaviors/send/send.go | 1 - brain/behaviors/zouyu/README.md | 7 - brain/behaviors/zouyu/types.go | 3 - brain/behaviors/zouyu/zouyu.go | 14 - brain/brain.go | 18 - brain/brain_test.go | 11 - brain/cli/README.md | 1 - brain/cli/cli.go | 1 - brain/cloud/README.md | 3 - brain/types.go | 9 - brain/web/README.md | 1 - cert/cert.go | 30 +- cert/cert_test.go | 7 +- chart/REAME.md | 1 - chart/api.go | 60 --- chart/chart.go | 103 ------ chart/chart_test.go | 47 --- chart/lang.go | 125 ------- chart/process.go | 79 ---- chart/process_test.go | 106 ------ chart/types.go | 14 - cmd/dump.go | 4 +- cmd/migrate.go | 6 +- cmd/restore.go | 6 +- cmd/root.go | 4 +- cmd/run.go | 7 +- cmd/service.go | 174 --------- cmd/socket.go | 7 +- cmd/start.go | 20 +- cmd/studio/run.go | 19 +- cmd/websocket.go | 125 +++---- config/config.go | 3 + crypto/crypto_test.go | 22 +- crypto/process.go | 14 +- engine/init_test.go | 3 +- engine/load.go | 193 +++++----- engine/process.go | 69 ++-- engine/process_test.go | 8 +- engine/user_test.go | 29 -- flow/flow.go | 53 +-- flow/flow_test.go | 8 +- go.mod | 11 +- go.sum | 16 - helper/array.process.go | 20 +- helper/array_test.go | 14 +- helper/captcha.go | 6 +- helper/captcha_test.go | 14 +- helper/case.go | 6 +- helper/case_test.go | 8 +- helper/control.process.go | 6 +- helper/control_test.go | 6 +- helper/env.process.go | 10 +- helper/env_test.go | 10 +- helper/hex.process.go | 4 +- helper/hex_test.go | 25 +- helper/if.go | 10 +- helper/if_test.go | 8 +- helper/jwt.go | 6 +- helper/jwt_test.go | 10 +- helper/map.process.go | 16 +- helper/map_test.go | 16 +- helper/password.go | 4 +- helper/password_test.go | 10 +- helper/process.go | 136 +++---- helper/range.go | 18 +- helper/string.process.go | 4 +- helper/string_test.go | 4 +- importer/importer.go | 45 ++- importer/importer_test.go | 1 - importer/init_test.go | 2 - importer/process.go | 40 +- importer/process_test.go | 18 +- init_test.go | 4 +- main.go | 3 - model/model.go | 51 +-- model/model_test.go | 8 +- network/ip.go | 63 ---- network/ip_test.go | 32 -- network/process.go | 19 - network/request.go | 168 --------- network/request.process.go | 127 ------- network/request_test.go | 66 ---- page/REAME.md | 1 - page/api.go | 60 --- page/lang.go | 125 ------- page/page.go | 121 ------ page/page_test.go | 44 --- page/process.go | 79 ---- page/process_test.go | 76 ---- page/types.go | 14 - plugin/plugin.go | 30 +- plugin/plugin_test.go | 6 +- query/query.go | 4 +- runtime/runtime.go | 25 +- schedule/schedule.go | 33 +- schedule/schedule_test.go | 5 +- script/script.go | 66 ++-- script/script_test.go | 18 +- service/guard.go | 2 - service/middleware.go | 2 +- service/service.go | 56 ++- service/watch.go | 77 ++-- setup/install.go | 21 +- share/api.go | 36 +- share/columns.go | 4 +- share/filters.go | 4 +- share/importable.go | 15 +- socket/socket.go | 39 +- socket/socket_test.go | 7 +- store/store.go | 44 +-- store/store_test.go | 1 - studio/router.go | 16 +- studio/studio.go | 4 +- studio/studio_test.go | 15 +- system/process_test.go | 2 +- table/api.go | 79 ---- table/json.go | 42 --- table/lang.go | 98 ----- table/process.go | 445 ---------------------- table/process_test.go | 547 ---------------------------- table/table.go | 486 ------------------------ table/table_test.go | 64 ---- table/types.go | 58 --- table/validate.go | 132 ------- task/task.go | 44 +-- task/task_test.go | 1 - user/captcha.go | 134 ------- user/captcha_test.go | 45 --- user/process.go | 80 ---- user/user.go | 85 ----- utils/datetime/now.go | 12 +- utils/datetime_test.go | 12 +- utils/process.go | 94 ++--- utils/str/str.go | 6 +- utils/str_test.go | 6 +- utils/tree/tree.go | 4 +- utils/tree_test.go | 4 +- websocket/websocket.go | 48 +-- websocket/websocket_test.go | 35 +- widget/widget.go | 174 ++++----- widget/widget_test.go | 8 +- widgets/action/action_test.go | 4 +- widgets/action/guard.go | 6 +- widgets/action/process.go | 8 +- widgets/action/types.go | 4 +- widgets/api.go | 28 +- widgets/app/app.go | 166 ++++----- widgets/app/app_test.go | 64 ++-- widgets/app/types.go | 4 +- widgets/chart/api.go | 26 +- widgets/chart/chart.go | 6 +- widgets/chart/chart_test.go | 3 +- widgets/chart/handler.go | 6 +- widgets/chart/process.go | 18 +- widgets/chart/process_test.go | 21 +- widgets/component/compute.go | 4 +- widgets/component/process.go | 19 +- widgets/component/props.go | 11 +- widgets/compute/compute.go | 16 +- widgets/dashboard/api.go | 26 +- widgets/dashboard/dashboard.go | 6 +- widgets/dashboard/dashboard_test.go | 3 +- widgets/dashboard/handler.go | 6 +- widgets/dashboard/process.go | 18 +- widgets/dashboard/process_test.go | 25 +- widgets/expression/expression.go | 10 +- widgets/expression/process.go | 10 +- widgets/form/action.go | 4 +- widgets/form/api.go | 68 ++-- widgets/form/bind.go | 4 +- widgets/form/fields.go | 4 +- widgets/form/form.go | 6 +- widgets/form/form_test.go | 5 +- widgets/form/handler.go | 14 +- widgets/form/layout.go | 4 +- widgets/form/process.go | 47 +-- widgets/form/process_test.go | 44 +-- widgets/hook/hook.go | 6 +- widgets/list/action.go | 4 +- widgets/list/api.go | 50 +-- widgets/list/bind.go | 4 +- widgets/list/fields.go | 4 +- widgets/list/handler.go | 14 +- widgets/list/layout.go | 4 +- widgets/list/list.go | 6 +- widgets/list/list_test.go | 5 +- widgets/list/process.go | 33 +- widgets/list/process_test.go | 15 +- widgets/login/login.go | 20 +- widgets/login/login_test.go | 9 +- widgets/login/process.go | 18 +- widgets/login/types.go | 4 +- widgets/models.go | 4 +- widgets/process.go | 16 +- widgets/process_test.go | 12 +- widgets/table/action.go | 4 +- widgets/table/api.go | 104 +++--- widgets/table/api_test.go | 3 +- widgets/table/bind.go | 4 +- widgets/table/excel.go | 4 +- widgets/table/fields.go | 4 +- widgets/table/fields_test.go | 4 +- widgets/table/handler.go | 14 +- widgets/table/layout.go | 4 +- widgets/table/mapping_test.go | 20 +- widgets/table/process.go | 90 ++--- widgets/table/process_test.go | 72 ++-- widgets/table/table.go | 6 +- widgets/table/table_test.go | 3 +- widgets/test/engine.go | 19 +- widgets/test/request.go | 9 +- widgets/test/server.go | 28 +- widgets/widgets_test.go | 3 +- xfs/process.go | 166 --------- xfs/process_test.go | 57 --- xfs/xfs.go | 263 ------------- xfs/xfs_test.go | 18 - 224 files changed, 1648 insertions(+), 6624 deletions(-) delete mode 100644 app/README.md delete mode 100644 app/app.go delete mode 100644 app/app_test.go delete mode 100644 brain/README.md delete mode 100644 brain/behaviors/listen/listen.go delete mode 100644 brain/behaviors/send/send.go delete mode 100644 brain/behaviors/zouyu/README.md delete mode 100644 brain/behaviors/zouyu/types.go delete mode 100644 brain/behaviors/zouyu/zouyu.go delete mode 100644 brain/brain.go delete mode 100644 brain/brain_test.go delete mode 100644 brain/cli/README.md delete mode 100644 brain/cli/cli.go delete mode 100644 brain/cloud/README.md delete mode 100644 brain/types.go delete mode 100644 brain/web/README.md delete mode 100644 chart/REAME.md delete mode 100644 chart/api.go delete mode 100644 chart/chart.go delete mode 100644 chart/chart_test.go delete mode 100644 chart/lang.go delete mode 100644 chart/process.go delete mode 100644 chart/process_test.go delete mode 100644 chart/types.go delete mode 100644 cmd/service.go delete mode 100644 engine/user_test.go delete mode 100644 network/ip.go delete mode 100644 network/ip_test.go delete mode 100644 network/process.go delete mode 100644 network/request.go delete mode 100644 network/request.process.go delete mode 100644 network/request_test.go delete mode 100644 page/REAME.md delete mode 100644 page/api.go delete mode 100644 page/lang.go delete mode 100644 page/page.go delete mode 100644 page/page_test.go delete mode 100644 page/process.go delete mode 100644 page/process_test.go delete mode 100644 page/types.go delete mode 100644 table/api.go delete mode 100644 table/json.go delete mode 100644 table/lang.go delete mode 100644 table/process.go delete mode 100644 table/process_test.go delete mode 100644 table/table.go delete mode 100644 table/table_test.go delete mode 100644 table/types.go delete mode 100644 table/validate.go delete mode 100644 user/captcha.go delete mode 100644 user/captcha_test.go delete mode 100644 user/process.go delete mode 100644 user/user.go delete mode 100644 xfs/process.go delete mode 100644 xfs/process_test.go delete mode 100644 xfs/xfs.go delete mode 100644 xfs/xfs_test.go diff --git a/api/api.go b/api/api.go index fb76b8592d..d0aafe0ebd 100644 --- a/api/api.go +++ b/api/api.go @@ -1,60 +1,17 @@ package api import ( - "fmt" - "path/filepath" - "strings" - - "github.com/yaoapp/gou" - "github.com/yaoapp/kun/log" + "github.com/yaoapp/gou/api" + "github.com/yaoapp/gou/application" "github.com/yaoapp/yao/config" "github.com/yaoapp/yao/share" ) -// Load 加载API +// Load apis func Load(cfg config.Config) error { - if share.BUILDIN { - return LoadBuildIn("apis", "") - } - return LoadFrom(filepath.Join(cfg.Root, "apis"), "") -} - -// LoadFrom 从特定目录加载 -func LoadFrom(dir string, prefix string) error { - if share.DirNotExists(dir) { - return fmt.Errorf("%s does not exists", dir) - } - - messages := []string{} - err := share.Walk(dir, ".http.json", func(root, filename string) { - name := prefix + share.SpecName(root, filename) - content := share.ReadFile(filename) - _, err := gou.LoadAPIReturn(string(content), name, "bearer-jwt") - if err != nil { - log.With(log.F{"root": root, "file": filename}).Error(err.Error()) - messages = append(messages, fmt.Sprintf("%s %s", name, err.Error())) - } - }) - - // Load WebSocket Server - err = share.Walk(dir, ".ws.json", func(root, filename string) { - name := prefix + share.SpecName(root, filename) - content := share.ReadFile(filename) - _, err := gou.LoadWebSocketServer(string(content), name) - if err != nil { - log.With(log.F{"root": root, "file": filename}).Error(err.Error()) - messages = append(messages, fmt.Sprintf("%s %s", name, err.Error())) - } - }) - - if len(messages) > 0 { - return fmt.Errorf("%s", strings.Join(messages, ";")) - } - - return err -} - -// LoadBuildIn 从制品中读取 -func LoadBuildIn(dir string, prefix string) error { - return nil + exts := []string{"*.http.yao", "*.http.json", "*.http.jsonc"} + return application.App.Walk("apis", func(root, file string, isdir bool) error { + _, err := api.Load(file, share.ID(root, file)) + return err + }, exts...) } diff --git a/api/api_test.go b/api/api_test.go index 8660f46130..a7e0e306c8 100644 --- a/api/api_test.go +++ b/api/api_test.go @@ -4,21 +4,19 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/api" "github.com/yaoapp/gou/websocket" "github.com/yaoapp/yao/config" ) func TestLoad(t *testing.T) { - gou.APIs = make(map[string]*gou.API) Load(config.Conf) - LoadFrom("not a path", "404.") check(t) } func check(t *testing.T) { keys := []string{} - for key := range gou.APIs { + for key := range api.APIs { keys = append(keys, key) } diff --git a/app/README.md b/app/README.md deleted file mode 100644 index 75fca7a16a..0000000000 --- a/app/README.md +++ /dev/null @@ -1 +0,0 @@ -# 应用信息 diff --git a/app/app.go b/app/app.go deleted file mode 100644 index 9fa96705f9..0000000000 --- a/app/app.go +++ /dev/null @@ -1,82 +0,0 @@ -package app - -import ( - jsoniter "github.com/json-iterator/go" - l "github.com/yaoapp/gou/lang" - "github.com/yaoapp/kun/exception" - "github.com/yaoapp/kun/maps" - "github.com/yaoapp/yao/config" - "github.com/yaoapp/yao/data" - "github.com/yaoapp/yao/share" - "github.com/yaoapp/yao/xfs" -) - -// Load Application -func Load(cfg config.Config) { - - // Set language pack - share.App.L = map[string]string{} - if l.Default != nil { - share.App.L = l.Default.Global - } - - // Load Info - LoadInfo(cfg.Root) - -} - -// L 语言包 -func L(word string) string { - if trans, has := share.App.L[word]; has { - return trans - } - return word -} - -// LoadInfo 应用信息 -func LoadInfo(root string) { - info := defaultInfo() - fs := xfs.New(root) - if fs.MustExists("/app.json") { - err := jsoniter.Unmarshal(fs.MustReadFile("/app.json"), &info) - if err != nil { - exception.New("解析应用失败 %s", 500, err).Throw() - } - } - if has, _ := fs.Exists("/yao/icons/icon.icns"); has { - info.Icons.Set("icns", xfs.Encode(fs.MustReadFile("/yao/icons/icon.icns"))) - } - - if has, _ := fs.Exists("/yao/icons/icon.ico"); has { - info.Icons.Set("ico", xfs.Encode(fs.MustReadFile("/yao/icons/icon.ico"))) - } - - if has, _ := fs.Exists("/yao/icons/icon.png"); has { - info.Icons.Set("png", xfs.Encode(fs.MustReadFile("/yao/icons/icon.png"))) - } - - info.L = share.App.L - share.App = info -} - -// LoadLangBuildIn 从制品中读取 -func LoadLangBuildIn(dir string) error { - return nil -} - -// defaultInfo 读取默认应用信息 -func defaultInfo() share.AppInfo { - info := share.AppInfo{ - Icons: maps.MakeSync(), - } - err := jsoniter.Unmarshal(data.MustAsset("yao/data/app.json"), &info) - if err != nil { - exception.New("解析默认应用失败 %s", 500, err).Throw() - } - - info.Icons.Set("icns", xfs.Encode(data.MustAsset("yao/data/icons/icon.icns"))) - info.Icons.Set("ico", xfs.Encode(data.MustAsset("yao/data/icons/icon.ico"))) - info.Icons.Set("png", xfs.Encode(data.MustAsset("yao/data/icons/icon.png"))) - - return info -} diff --git a/app/app_test.go b/app/app_test.go deleted file mode 100644 index cf78ad2588..0000000000 --- a/app/app_test.go +++ /dev/null @@ -1,15 +0,0 @@ -package app - -import ( - "os" - "testing" - - "github.com/yaoapp/yao/config" -) - -func TestLoad(t *testing.T) { - os.Setenv("YAO_LANG", "zh-cn") - Load(config.Conf) - // assert.Equal(t, "YAO", share.App.L["Yao"]) - // assert.Equal(t, "象传", share.App.L["Xiang"]) -} diff --git a/brain/README.md b/brain/README.md deleted file mode 100644 index cc4ac02041..0000000000 --- a/brain/README.md +++ /dev/null @@ -1,8 +0,0 @@ -# Brain - -the robot who helps you build various types of applications - -the robot has two modes : - -1. Generate an App DSL based on the rules -2. Connect AI cloud to generate app DSL based on input ( Not Supported Yet ) diff --git a/brain/behaviors/listen/listen.go b/brain/behaviors/listen/listen.go deleted file mode 100644 index 7eb623ac2e..0000000000 --- a/brain/behaviors/listen/listen.go +++ /dev/null @@ -1 +0,0 @@ -package listen diff --git a/brain/behaviors/send/send.go b/brain/behaviors/send/send.go deleted file mode 100644 index 44dc5badfe..0000000000 --- a/brain/behaviors/send/send.go +++ /dev/null @@ -1 +0,0 @@ -package send diff --git a/brain/behaviors/zouyu/README.md b/brain/behaviors/zouyu/README.md deleted file mode 100644 index 4eebd0f08a..0000000000 --- a/brain/behaviors/zouyu/README.md +++ /dev/null @@ -1,7 +0,0 @@ -# Zouyu - -Zouyu is a benevolent beast in ancient Chinese myths and legends. It is a very precious mythical beast in Lin's country. It is like a tiger, with colorful patterns on its body, and its tail is longer than its body. It looks like a tiger with white hair and black stripes, but it does not eat live animals. Travel thousands of miles a day. - -## Functions - -Connect a Database, generates a dashboard applications diff --git a/brain/behaviors/zouyu/types.go b/brain/behaviors/zouyu/types.go deleted file mode 100644 index cc6aeb762e..0000000000 --- a/brain/behaviors/zouyu/types.go +++ /dev/null @@ -1,3 +0,0 @@ -package zouyu - -type conn struct{} diff --git a/brain/behaviors/zouyu/zouyu.go b/brain/behaviors/zouyu/zouyu.go deleted file mode 100644 index 7d3bc864a5..0000000000 --- a/brain/behaviors/zouyu/zouyu.go +++ /dev/null @@ -1,14 +0,0 @@ -package zouyu - -// Run the data -func Run(dsn string) {} - -func (conn *conn) models() {} - -func (conn *conn) apis() {} - -func (conn *conn) flows() {} - -func (conn *conn) tables() {} - -func (conn *conn) env() {} diff --git a/brain/brain.go b/brain/brain.go deleted file mode 100644 index 02d20a8721..0000000000 --- a/brain/brain.go +++ /dev/null @@ -1,18 +0,0 @@ -package brain - -// NewBehaviors Returns the behaviors based on input words -func NewBehaviors(words string) (*Behaviors, error) { - resp, err := NPL(words) - if err != nil { - return nil, err - } - return resp.Behaviors, nil -} - -// Run the behaviors -func (behaviors *Behaviors) Run() {} - -// NPL the Natural language processing -func NPL(words string) (*Response, error) { - return &Response{Behaviors: &Behaviors{}}, nil -} diff --git a/brain/brain_test.go b/brain/brain_test.go deleted file mode 100644 index 480aea9e49..0000000000 --- a/brain/brain_test.go +++ /dev/null @@ -1,11 +0,0 @@ -package brain - -import ( - "fmt" - "testing" -) - -func TestNewBehaviors(t *testing.T) { - behaviors, err := NewBehaviors("hello") - fmt.Println(behaviors, err) -} diff --git a/brain/cli/README.md b/brain/cli/README.md deleted file mode 100644 index 93c42785f2..0000000000 --- a/brain/cli/README.md +++ /dev/null @@ -1 +0,0 @@ -# Command Line Interface diff --git a/brain/cli/cli.go b/brain/cli/cli.go deleted file mode 100644 index 7f1e458cd3..0000000000 --- a/brain/cli/cli.go +++ /dev/null @@ -1 +0,0 @@ -package cli diff --git a/brain/cloud/README.md b/brain/cloud/README.md deleted file mode 100644 index 91eec131f7..0000000000 --- a/brain/cloud/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# Cloud - -Connecting AI cloud to analyze behaviors diff --git a/brain/types.go b/brain/types.go deleted file mode 100644 index d74eee7903..0000000000 --- a/brain/types.go +++ /dev/null @@ -1,9 +0,0 @@ -package brain - -// Behaviors the Behaviors struct -type Behaviors struct{} - -// Response NPL Response -type Response struct { - Behaviors *Behaviors -} diff --git a/brain/web/README.md b/brain/web/README.md deleted file mode 100644 index 42fc93e6c9..0000000000 --- a/brain/web/README.md +++ /dev/null @@ -1 +0,0 @@ -# WEB Interface diff --git a/cert/cert.go b/cert/cert.go index 3ecffc3a69..2cf2c65178 100644 --- a/cert/cert.go +++ b/cert/cert.go @@ -1,35 +1,17 @@ package cert import ( - "fmt" - "path/filepath" - + "github.com/yaoapp/gou/application" "github.com/yaoapp/gou/ssl" - "github.com/yaoapp/kun/log" "github.com/yaoapp/yao/config" "github.com/yaoapp/yao/share" ) // Load 加载API func Load(cfg config.Config) error { - var root = filepath.Join(cfg.Root, "certs") - return LoadFrom(root, "") -} - -// LoadFrom 从特定目录加载 -func LoadFrom(dir string, prefix string) error { - - if share.DirNotExists(dir) { - return fmt.Errorf("%s does not exists", dir) - } - - err := share.Walk(dir, ".pem", func(root, filename string) { - name := prefix + share.SpecName(root, filename) - _, err := ssl.LoadCertificateFrom(filename, name) - if err != nil { - log.With(log.F{"root": root, "file": filename}).Error(err.Error()) - } - }) - - return err + exts := []string{"*.pem", "*.key", "*.pub"} + return application.App.Walk("certs", func(root, file string, isdir bool) error { + _, err := ssl.Load(file, share.ID(root, file)) + return err + }, exts...) } diff --git a/cert/cert_test.go b/cert/cert_test.go index 34cbdf2362..fd4d351867 100644 --- a/cert/cert_test.go +++ b/cert/cert_test.go @@ -4,21 +4,20 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" "github.com/yaoapp/gou/ssl" "github.com/yaoapp/yao/config" ) func TestLoad(t *testing.T) { Load(config.Conf) - LoadFrom("not a path", "404.") check(t) } func TestProcessSign(t *testing.T) { Load(config.Conf) args := []interface{}{"hello world", "private", "SHA256"} - signature, err := gou.NewProcess("ssl.Sign", args...).Exec() + signature, err := process.New("ssl.Sign", args...).Exec() if err != nil { t.Fatal(err) } @@ -29,7 +28,7 @@ func TestProcessVerify(t *testing.T) { Load(config.Conf) signature := "EDHf3C9TXEk7y8LzIk5czLefXZyGxcMDVMcbNuBBegDkTqnPsRQnhFtNOgCdox8lI3MzLatwjoljoMY4Qk+sHGd5mAHMpiREa1gRFSVYpA2xvXZ3+KsfOHAdICQrfUdy59QaJGo6iGPNGG8PQOXHPTVNn6LMfryat9+f4l21DPAZiT0RyCUgFZE3/Qv8Z/6J4AsIXMSKZD6BGPPHUxGe7UBrXZvcR5dX25EiNjuH2OO38YJnDiTRVw14UI5fk/mQrwRdezj5tSKFCyHt912BZExXtkHISiYFNTZ/2RhOup5Xx6o3GvrEOdshrnN80Lwu1Aaju+lnZp13hDz4P6hU7w==" args := []interface{}{"hello world", signature, "cert", "SHA256"} - res, err := gou.NewProcess("ssl.Verify", args...).Exec() + res, err := process.New("ssl.Verify", args...).Exec() if err != nil { t.Fatal(err) } diff --git a/chart/REAME.md b/chart/REAME.md deleted file mode 100644 index 3f12113c6d..0000000000 --- a/chart/REAME.md +++ /dev/null @@ -1 +0,0 @@ -# 数据图表 diff --git a/chart/api.go b/chart/api.go deleted file mode 100644 index b0c15debf7..0000000000 --- a/chart/api.go +++ /dev/null @@ -1,60 +0,0 @@ -package chart - -import ( - "github.com/yaoapp/yao/share" -) - -// SetupAPIs 设定API数据 -func (chart *Chart) SetupAPIs() { - - defaults := map[string]share.API{ - "data": apiDataDefault(), - "setting": apiSettingDefault(), - } - - // 开发者填写的规则 - for name := range chart.APIs { - if _, has := defaults[name]; !has { - delete(chart.APIs, name) - continue - } - - api := defaults[name] - api.Name = name - if chart.APIs[name].Process != "" { - api.Process = chart.APIs[name].Process - } - - if chart.APIs[name].Guard != "" { - api.Guard = chart.APIs[name].Guard - } - - if chart.APIs[name].Default != nil { - api.Default = chart.APIs[name].Default - } - - defaults[name] = api - } - - chart.APIs = defaults -} - -// apiSearchDefault data 接口默认值 -func apiDataDefault() share.API { - param := map[string]interface{}{} - return share.API{ - Name: "data", - Guard: "bearer-jwt", - Process: "xiang.chart.data", - Default: []interface{}{param}, - } -} - -// apiSettingDefault setting 接口默认值 -func apiSettingDefault() share.API { - return share.API{ - Name: "setting", - Guard: "bearer-jwt", - Process: "xiang.chart.setting", - } -} diff --git a/chart/chart.go b/chart/chart.go deleted file mode 100644 index e071415271..0000000000 --- a/chart/chart.go +++ /dev/null @@ -1,103 +0,0 @@ -package chart - -import ( - "fmt" - "path/filepath" - - jsoniter "github.com/json-iterator/go" - "github.com/yaoapp/gou" - "github.com/yaoapp/gou/lang" - "github.com/yaoapp/kun/exception" - "github.com/yaoapp/kun/log" - "github.com/yaoapp/yao/config" - "github.com/yaoapp/yao/share" -) - -// Charts 已载入图表 -var Charts = map[string]*Chart{} - -// Load 加载数据表格 -func Load(cfg config.Config) error { - if share.BUILDIN { - return LoadBuildIn("charts", "") - } - return LoadFrom(filepath.Join(cfg.Root, "charts"), "") -} - -// LoadBuildIn 从制品中读取 -func LoadBuildIn(dir string, prefix string) error { - return nil -} - -// LoadFrom 从特定目录加载 -func LoadFrom(dir string, prefix string) error { - - if share.DirNotExists(dir) { - return fmt.Errorf("%s does not exists", dir) - } - - err := share.Walk(dir, ".json", func(root, filename string) { - name := prefix + share.SpecName(root, filename) - content := share.ReadFile(filename) - _, err := LoadChart(content, name) - if err != nil { - log.With(log.F{"root": root, "file": filename}).Error(err.Error()) - } - }) - - if err != nil { - return err - } - - // Load Script - err = share.Walk(dir, ".js", func(root, filename string) { - name := prefix + share.SpecName(root, filename) - chart := Select(name) - if chart != nil { - script := share.ScriptName(filename) - content := share.ReadFile(filename) - chart.LoadScript(string(content), script) - } - }) - - return err -} - -// LoadChart 载入数据表格 -func LoadChart(source []byte, name string) (*Chart, error) { - chart := &Chart{ - Flow: &gou.Flow{Name: name}, - } - err := jsoniter.Unmarshal(source, chart) - if err != nil { - log.With(log.F{"name": name, "source": source}).Error(err.Error()) - return nil, err - } - chart.Prepare() - chart.SetupAPIs() - Charts[name] = chart - - // Apply a language pack - if lang.Default != nil { - lang.Default.Apply(Charts[name]) - } - - return chart, nil -} - -// Select 读取已加载图表 -func Select(name string) *Chart { - chart, has := Charts[name] - if !has { - exception.New( - fmt.Sprintf("Chart:%s; 尚未加载", name), - 400, - ).Throw() - } - return chart -} - -// GetData 运行 flow 返回数值 -func (chart Chart) GetData(params map[string]interface{}) interface{} { - return chart.Flow.Exec(params) -} diff --git a/chart/chart_test.go b/chart/chart_test.go deleted file mode 100644 index 956af6d687..0000000000 --- a/chart/chart_test.go +++ /dev/null @@ -1,47 +0,0 @@ -package chart - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/yaoapp/yao/config" - "github.com/yaoapp/yao/i18n" - "github.com/yaoapp/yao/model" - "github.com/yaoapp/yao/query" - "github.com/yaoapp/yao/share" -) - -func TestLoad(t *testing.T) { - - share.DBConnect(config.Conf.DB) - model.Load(config.Conf) - query.Load(config.Conf) - - Load(config.Conf) - LoadFrom("not a path", "404.") - check(t) -} - -func check(t *testing.T) { - keys := []string{} - for key := range Charts { - keys = append(keys, key) - } - assert.Equal(t, 3, len(keys)) - _, err := i18n.Trans("zh-hk", []string{"chart.lang"}, Charts["lang"]) - if err != nil { - t.Fatal(err) - } - - // lang := new.(*Chart) - // utils.Dump(lang.Output) - - // output := lang.Output.(map[string]interface{}) - // assert.Equal(t, "{{$in}}", output["參數"]) - - // filters := lang.Page.Layout["filters"].([]interface{}) - // begin := filters[0].(map[string]interface{}) - // assert.Equal(t, "開始時間", begin["name"]) - - // assert.Equal(t, "請選擇開始時間", lang.Filters["開始時間"].Input.Props["placeholder"]) -} diff --git a/chart/lang.go b/chart/lang.go deleted file mode 100644 index 667f740787..0000000000 --- a/chart/lang.go +++ /dev/null @@ -1,125 +0,0 @@ -package chart - -// Lang for applying a language pack -func (chart *Chart) Lang(trans func(widget string, inst string, value *string) bool) { - inst := chart.Flow.Name - widget := "chart" - - trans(widget, inst, &chart.Name) - trans(widget, inst, &chart.Label) - trans(widget, inst, &chart.Description) - trans(widget, inst, &chart.Page.Primary) - transMap(widget, inst, chart.Page.Layout, trans) - chart.Output = transAny(widget, inst, chart.Output, trans) - - // Filters - for name, filter := range chart.Filters { - new := name - trans(widget, inst, &new) - trans(widget, inst, &filter.Label) - delete(chart.Filters, name) - - // Props - transMap(widget, inst, filter.Input.Props, trans) - chart.Filters[new] = filter - } - -} - -func transAny(widget string, inst string, input interface{}, trans func(widget string, inst string, value *string) bool) interface{} { - switch input.(type) { - case []interface{}: - values := input.([]interface{}) - transArr(widget, inst, values, trans) - input = values - break - - case map[string]interface{}: - values := input.(map[string]interface{}) - for name, value := range values { - new := name - newValue := value - - switch value.(type) { - case string: - val := value.(string) - trans(widget, inst, &val) - newValue = val - break - - case []interface{}: - vals := value.([]interface{}) - transArr(widget, inst, vals, trans) - newValue = vals - break - - case map[string]interface{}: - vals := value.(map[string]interface{}) - transMap(widget, inst, vals, trans) - newValue = vals - break - } - - trans(widget, inst, &new) - delete(values, name) - values[new] = newValue - } - input = values - break - } - - return input -} - -func transMap(widget string, inst string, values map[string]interface{}, trans func(widget string, inst string, value *string) bool) { - for key, value := range values { - - switch value.(type) { - - case string: - v := value.(string) - trans(widget, inst, &v) - values[key] = v - break - - case []interface{}: - v := value.([]interface{}) - transArr(widget, inst, v, trans) - values[key] = v - break - - case map[string]interface{}: - v := value.(map[string]interface{}) - transMap(widget, inst, v, trans) - values[key] = v - break - } - - } -} - -func transArr(widget string, inst string, values []interface{}, trans func(widget string, inst string, value *string) bool) { - for key, value := range values { - switch value.(type) { - - case string: - v := value.(string) - trans(widget, inst, &v) - values[key] = v - break - - case []interface{}: - v := value.([]interface{}) - transArr(widget, inst, v, trans) - values[key] = v - break - - case map[string]interface{}: - v := value.(map[string]interface{}) - transMap(widget, inst, v, trans) - values[key] = v - break - } - - } -} diff --git a/chart/process.go b/chart/process.go deleted file mode 100644 index d6c73ebda0..0000000000 --- a/chart/process.go +++ /dev/null @@ -1,79 +0,0 @@ -package chart - -import ( - "strings" - - "github.com/yaoapp/gou" - "github.com/yaoapp/kun/maps" -) - -// 注册处理器 -func init() { - gou.RegisterProcessHandler("xiang.chart.data", ProcessData) - gou.RegisterProcessHandler("xiang.chart.setting", ProcessSetting) -} - -// ProcessData xiang.chart.data -// 查询数据分析图表中定义的数据 -func ProcessData(process *gou.Process) interface{} { - - process.ValidateArgNums(2) - name := process.ArgsString(0) - params := process.ArgsMap(1) - chart := Select(name) - api := chart.APIs["data"] - - if len(api.Default) > 0 { - if defaults, ok := api.Default[0].(map[string]interface{}); ok { - for key, value := range defaults { - if !params.Has(key) { - params.Set(key, value) - } - } - } - } - - // with Session - chart.Flow.WithGlobal(process.Global) - chart.Flow.WithSID(process.Sid) - - return chart.GetData(params) -} - -// ProcessSetting xiang.chart.setting -// 查询数据分析图表中定义的数据 -func ProcessSetting(process *gou.Process) interface{} { - - process.ValidateArgNums(2) - name := process.ArgsString(0) - field := process.ArgsString(1) - chart := Select(name) - - fields := strings.Split(field, ",") - setting := maps.Map{ - "name": chart.Name, - "label": chart.Label, - "version": chart.Version, - "description": chart.Description, - "filters": chart.Filters, - "page": chart.Page, - } - - if len(fields) == 1 && setting.Has(fields[0]) { - field := strings.TrimSpace(fields[0]) - return setting.Get(field) - } - - if len(fields) > 1 { - res := maps.Map{} - for _, field := range fields { - field = strings.TrimSpace(field) - if setting.Has(field) { - res.Set(field, setting.Get(field)) - } - } - return res - } - return setting - -} diff --git a/chart/process_test.go b/chart/process_test.go deleted file mode 100644 index c0d883ff31..0000000000 --- a/chart/process_test.go +++ /dev/null @@ -1,106 +0,0 @@ -package chart - -import ( - "net/url" - "testing" - "time" - - "github.com/gin-gonic/gin" - "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" - "github.com/yaoapp/gou/session" - "github.com/yaoapp/kun/any" - "github.com/yaoapp/yao/config" - _ "github.com/yaoapp/yao/helper" - "github.com/yaoapp/yao/model" - "github.com/yaoapp/yao/query" - "github.com/yaoapp/yao/runtime" - "github.com/yaoapp/yao/share" -) - -func init() { - runtime.Load(config.Conf) - share.DBConnect(config.Conf.DB) - model.Load(config.Conf) - query.Load(config.Conf) - Load(config.Conf) -} -func TestProcessSetting(t *testing.T) { - - args := []interface{}{ - "service.compare", - nil, - &gin.Context{}, - } - process := gou.NewProcess("xiang.chart.Setting", args...) - response := ProcessSetting(process) - assert.NotNil(t, response) - res := any.Of(response).Map() - assert.True(t, res.Has("name")) - assert.True(t, res.Has("label")) - assert.True(t, res.Has("description")) - assert.True(t, res.Has("page")) - assert.True(t, res.Has("version")) - - args = []interface{}{ - "service.compare", - "page,name", - &gin.Context{}, - } - process = gou.NewProcess("xiang.chart.Setting", args...) - response = ProcessSetting(process) - assert.NotNil(t, response) - - res = any.Of(response).Map() - assert.True(t, res.Has("name")) - assert.True(t, res.Has("page")) - assert.False(t, res.Has("label")) -} - -func TestProcessData(t *testing.T) { - - params := url.Values{ - "from": []string{"1981-01-01", "1990-01-01"}, - } - params.Set("to", "2049-12-31") - - args := []interface{}{ - "service.compare", - params, - &gin.Context{}, - } - process := gou.NewProcess("xiang.chart.Data", args...) - response := ProcessData(process) - // utils.Dump(response) - - assert.NotNil(t, response) - - res := any.Of(response).Map().Dot() - assert.Equal(t, "北京", res.Get("合并.0.城市")) -} - -func TestProcessDataGlobalSession(t *testing.T) { - - params := url.Values{ - "from": []string{"1981-01-01", "1990-01-01"}, - } - params.Set("to", "2049-12-31") - - args := []interface{}{ - "session", - params, - &gin.Context{}, - } - - sid := session.ID() - data := time.Now().String() - session.Global().ID(sid).Set("id", data) - process := gou. - NewProcess("xiang.chart.Data", args...). - WithSID(sid). - WithGlobal(map[string]interface{}{"foo": "bar"}) - - response := ProcessData(process) - res := any.Of(response).Map().Dot() - assert.Equal(t, data, res.Get("ID")) -} diff --git a/chart/types.go b/chart/types.go deleted file mode 100644 index b7b7e588dc..0000000000 --- a/chart/types.go +++ /dev/null @@ -1,14 +0,0 @@ -package chart - -import ( - "github.com/yaoapp/gou" - "github.com/yaoapp/yao/share" -) - -// Chart 图表格式 -type Chart struct { - *gou.Flow - APIs map[string]share.API `json:"apis,omitempty"` - Filters map[string]share.Filter `json:"filters,omitempty"` - Page share.Page `json:"page,omitempty"` -} diff --git a/cmd/dump.go b/cmd/dump.go index 5c90b900b0..5e3e6169f2 100644 --- a/cmd/dump.go +++ b/cmd/dump.go @@ -12,7 +12,7 @@ import ( "github.com/fatih/color" "github.com/spf13/cobra" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/model" "github.com/yaoapp/kun/exception" "github.com/yaoapp/yao/config" "github.com/yaoapp/yao/engine" @@ -71,7 +71,7 @@ var dumpCmd = &cobra.Command{ // Export models files := []string{} - for _, mod := range gou.Models { + for _, mod := range model.Models { fmt.Printf("\r%s", color.GreenString(L("Export the models: %s (%s)"), mod.Name, mod.MetaData.Table.Name)) jsonfiles, err := mod.Export(5000, func(curr, total int) { diff --git a/cmd/migrate.go b/cmd/migrate.go index 1115a6468c..9c12e24064 100644 --- a/cmd/migrate.go +++ b/cmd/migrate.go @@ -6,7 +6,7 @@ import ( "github.com/fatih/color" "github.com/spf13/cobra" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/model" "github.com/yaoapp/kun/exception" "github.com/yaoapp/yao/config" "github.com/yaoapp/yao/engine" @@ -43,7 +43,7 @@ var migrateCmd = &cobra.Command{ } if name != "" { - mod, has := gou.Models[name] + mod, has := model.Models[name] fmt.Printf(color.WhiteString(L("Update schema model: %s (%s) "), mod.Name, mod.MetaData.Table.Name) + "\t") if !has { @@ -70,7 +70,7 @@ var migrateCmd = &cobra.Command{ } // Do Stuff Here - for _, mod := range gou.Models { + for _, mod := range model.Models { fmt.Printf(color.WhiteString(L("Update schema model: %s (%s) "), mod.Name, mod.MetaData.Table.Name) + "\t") if resetModel { diff --git a/cmd/restore.go b/cmd/restore.go index 107f7e7b8c..01bf146f78 100644 --- a/cmd/restore.go +++ b/cmd/restore.go @@ -13,7 +13,7 @@ import ( "github.com/fatih/color" "github.com/spf13/cobra" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/model" "github.com/yaoapp/kun/exception" "github.com/yaoapp/yao/config" "github.com/yaoapp/yao/engine" @@ -113,7 +113,7 @@ func restoreModels(basePath string) { } // Migrate models - for _, mod := range gou.Models { + for _, mod := range model.Models { fmt.Printf("\r%s", strings.Repeat(" ", 80)) fmt.Printf(color.GreenString(L("\rUpdate schema model: %s (%s) "), mod.Name, mod.MetaData.Table.Name)) err := mod.Migrate(true) @@ -128,7 +128,7 @@ func restoreModels(basePath string) { for _, file := range files { namer := strings.Split(file.Name(), ".") name := strings.Join(namer[:len(namer)-2], ".") - if mod, has := gou.Models[name]; has { + if mod, has := model.Models[name]; has { fmt.Printf("\r%s", strings.Repeat(" ", 80)) fmt.Printf(color.GreenString(L("\rRestore model: %s (%s) "), mod.Name, mod.MetaData.Table.Name)) err := mod.Import(filepath.Join(basePath, file.Name())) diff --git a/cmd/root.go b/cmd/root.go index a0d248380b..188642527d 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -120,8 +120,8 @@ func init() { getCmd, dumpCmd, restoreCmd, - socketCmd, - websocketCmd, + // socketCmd, + // websocketCmd, studioCmd, upgradeCmd, ) diff --git a/cmd/run.go b/cmd/run.go index 7e9b88e4b1..922077d6ab 100644 --- a/cmd/run.go +++ b/cmd/run.go @@ -7,7 +7,8 @@ import ( "github.com/fatih/color" jsoniter "github.com/json-iterator/go" "github.com/spf13/cobra" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/plugin" + "github.com/yaoapp/gou/process" "github.com/yaoapp/kun/exception" "github.com/yaoapp/kun/utils" "github.com/yaoapp/yao/config" @@ -21,7 +22,7 @@ var runCmd = &cobra.Command{ Long: L("Execute process"), Run: func(cmd *cobra.Command, args []string) { defer share.SessionStop() - defer gou.KillPlugins() + defer plugin.KillAll() defer func() { err := exception.Catch(recover()) if err != nil { @@ -69,7 +70,7 @@ var runCmd = &cobra.Command{ } - process := gou.NewProcess(name, pargs...) + process := process.New(name, pargs...) res := process.Run() fmt.Println(color.WhiteString("--------------------------------------")) fmt.Println(color.WhiteString(L("%s Response"), name)) diff --git a/cmd/service.go b/cmd/service.go deleted file mode 100644 index e0eed14e2b..0000000000 --- a/cmd/service.go +++ /dev/null @@ -1,174 +0,0 @@ -package cmd - -import ( - "fmt" - "os" - "path/filepath" - "strings" - - "github.com/fatih/color" - "github.com/spf13/cobra" - "github.com/yaoapp/gou" - "github.com/yaoapp/kun/exception" - "github.com/yaoapp/yao/config" - "github.com/yaoapp/yao/share" -) - -// **** DEPRECATED **** -var serviceCmd = &cobra.Command{ - Use: "service", - Short: L("Service manager"), - Long: L("Service manager"), - Run: func(cmd *cobra.Command, args []string) { - loadService(config.Conf) - command := "ps" - if len(args) > 0 { - command = args[0] - } - - if len(args) > 1 { - args = args[1:] - } else { - args = []string{} - } - - switch command { - case "ps": - services() - break - case "install", "start", "stop", "remove", "status": - serviceManage(command, args) - break - default: - serviceHelp() - } - }, -} - -func serviceHelp() { - fmt.Println("Usage:") - fmt.Println(" ", color.GreenString(L("%s service [ps|start|stop|install|status] [all|name]"), share.BUILDNAME)) - fmt.Println("") -} - -func serviceManageAll(command string) { - for name := range gou.Services { - if name == "all" { - continue - } - serviceManage(command, []string{name}) - } -} - -func serviceManage(command string, args []string) { - if len(args) == 0 { - serviceHelp() - os.Exit(1) - } - - defer func() { - err := exception.Catch(recover()) - if err != nil { - fmt.Println(color.RedString(L("Fatal: %s"), err.Error())) - } - }() - - name := args[0] - if name == "all" { - serviceManageAll(command) - return - } - - srv := gou.SelectService(name) - var status = "" - var err error - switch command { - case "install": - status, err = srv.Install() - break - case "start": - status, err = srv.Start() - break - case "stop": - status, err = srv.Stop() - break - case "remove": - status, err = srv.Remove() - break - case "status": - status, err = srv.Status() - break - } - if err != nil { - fmt.Println(color.RedString(L("Fatal: %s"), err.Error())) - } - - fmt.Println(status) -} - -func services() { - for name, srv := range gou.Services { - status, err := srv.Status() - if err != nil { - status = err.Error() - } - fmt.Println( - color.GreenString("%s", name), - srv.Name, "....", - statusInfo(status), - ) - } - fmt.Println("") -} - -func statusInfo(message string) string { - if strings.Contains(message, "stopped") { - return statusStop() - } else if strings.Contains(message, "not installed") { - return statusNotInstalled() - } else if strings.Contains(message, "running") { - return statusRunning() - } - return statusUnknown() -} - -func statusUnknown() string { - return fmt.Sprintf("[ %s ]", color.WhiteString("UNKNOWN")) -} - -func statusRunning() string { - return fmt.Sprintf("[ %s ]", color.GreenString("RUNNING")) -} - -func statusNotInstalled() string { - return fmt.Sprintf("[ %s ]", color.YellowString("NOT INSTALLED")) -} - -func statusStop() string { - return fmt.Sprintf("[ %s ]", color.RedString("STOPED")) -} - -// Load 加载API -func loadService(cfg config.Config) { - var root = filepath.Join(cfg.Root, "services") - loadServiceFrom(root, "") -} - -func loadServiceFrom(dir string, prefix string) error { - - if share.DirNotExists(dir) { - return fmt.Errorf("%s does not exists", dir) - } - - err := share.Walk(dir, ".srv.json", func(root, filename string) { - name := prefix + share.SpecName(root, filename) - content := share.ReadFile(filename) - _, err := gou.LoadService(string(content), name) - if err != nil { - fmt.Println(color.RedString(L("Fatal: %s"), err.Error())) - os.Exit(1) - } - }) - - return err -} diff --git a/cmd/socket.go b/cmd/socket.go index fd5a19481d..6a9b140f3e 100644 --- a/cmd/socket.go +++ b/cmd/socket.go @@ -7,7 +7,8 @@ import ( "github.com/fatih/color" jsoniter "github.com/json-iterator/go" "github.com/spf13/cobra" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/plugin" + "github.com/yaoapp/gou/socket" "github.com/yaoapp/kun/exception" "github.com/yaoapp/yao/config" "github.com/yaoapp/yao/engine" @@ -20,7 +21,7 @@ var socketCmd = &cobra.Command{ Long: L("Open a socket connection"), Run: func(cmd *cobra.Command, args []string) { defer share.SessionStop() - defer gou.KillPlugins() + defer plugin.KillAll() defer func() { err := exception.Catch(recover()) if err != nil { @@ -67,7 +68,7 @@ var socketCmd = &cobra.Command{ } - socket, has := gou.Sockets[name] + socket, has := socket.Sockets[name] if !has { fmt.Println(color.RedString(L("%s not exists!"), name)) return diff --git a/cmd/start.go b/cmd/start.go index 3d8e03c577..216f7786f3 100644 --- a/cmd/start.go +++ b/cmd/start.go @@ -12,8 +12,9 @@ import ( "github.com/fatih/color" "github.com/spf13/cobra" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/api" "github.com/yaoapp/gou/connector" + "github.com/yaoapp/gou/schedule" "github.com/yaoapp/gou/store" "github.com/yaoapp/gou/task" "github.com/yaoapp/gou/websocket" @@ -152,14 +153,17 @@ var startCmd = &cobra.Command{ printStores(true) } + srv, err := service.Start() + // Start server go func() { - err := service.Start() + srv.Start() if err != nil { fmt.Println(color.RedString(L("Fatal: %s"), err.Error())) os.Exit(3) } }() + defer srv.Stop() fmt.Println(color.GreenString(L("✨LISTENING✨"))) @@ -256,12 +260,12 @@ func printStudio(silent bool, host string) { func printSchedules(silent bool) { - if len(gou.Schedules) == 0 { + if len(schedule.Schedules) == 0 { return } if silent { - for name, sch := range gou.Schedules { + for name, sch := range schedule.Schedules { process := fmt.Sprintf("Process: %s", sch.Process) if sch.TaskName != "" { process = fmt.Sprintf("Task: %s", sch.TaskName) @@ -272,9 +276,9 @@ func printSchedules(silent bool) { } fmt.Println(color.WhiteString("\n---------------------------------")) - fmt.Println(color.WhiteString(L("Schedules List (%d)"), len(gou.Schedules))) + fmt.Println(color.WhiteString(L("Schedules List (%d)"), len(schedule.Schedules))) fmt.Println(color.WhiteString("---------------------------------")) - for name, sch := range gou.Schedules { + for name, sch := range schedule.Schedules { process := fmt.Sprintf("Process: %s", sch.Process) if sch.TaskName != "" { process = fmt.Sprintf("Task: %s", sch.TaskName) @@ -309,7 +313,7 @@ func printTasks(silent bool) { func printApis(silent bool) { if silent { - for _, api := range gou.APIs { + for _, api := range api.APIs { if len(api.HTTP.Paths) <= 0 { continue } @@ -328,7 +332,7 @@ func printApis(silent bool) { fmt.Println(color.WhiteString(L("API List"))) fmt.Println(color.WhiteString("---------------------------------")) - for _, api := range gou.APIs { // API信息 + for _, api := range api.APIs { // API信息 if len(api.HTTP.Paths) <= 0 { continue } diff --git a/cmd/studio/run.go b/cmd/studio/run.go index 5794959c90..6ce8da531e 100644 --- a/cmd/studio/run.go +++ b/cmd/studio/run.go @@ -7,7 +7,8 @@ import ( "github.com/fatih/color" jsoniter "github.com/json-iterator/go" "github.com/spf13/cobra" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/plugin" + v8 "github.com/yaoapp/gou/runtime/v8" "github.com/yaoapp/kun/exception" "github.com/yaoapp/kun/utils" "github.com/yaoapp/yao/config" @@ -22,7 +23,7 @@ var RunCmd = &cobra.Command{ Long: L("Execute Yao Studio Script"), Run: func(cmd *cobra.Command, args []string) { defer share.SessionStop() - defer gou.KillPlugins() + defer plugin.KillAll() defer func() { err := exception.Catch(recover()) if err != nil { @@ -71,8 +72,18 @@ var RunCmd = &cobra.Command{ } } - req := gou.Yao.New(service, method) - res, err := req.RootCall(pargs...) + script, err := v8.SelectRoot(service) + if err != nil { + fmt.Println(color.RedString(L("Fatal: %s"), err.Error())) + } + + ctx, err := script.NewContext("", nil) + if err != nil { + fmt.Println(color.RedString(L("Fatal: %s"), err.Error())) + } + defer ctx.Close() + + res, err := ctx.Call(method, pargs...) if err != nil { fmt.Println(color.RedString("--------------------------------------")) fmt.Println(color.RedString(L("%s Error"), args[0])) diff --git a/cmd/websocket.go b/cmd/websocket.go index 69cc66d8c7..b796e298ef 100644 --- a/cmd/websocket.go +++ b/cmd/websocket.go @@ -1,71 +1,58 @@ package cmd -import ( - "fmt" - "strings" - - "github.com/fatih/color" - "github.com/spf13/cobra" - "github.com/yaoapp/gou" - "github.com/yaoapp/kun/exception" - "github.com/yaoapp/yao/config" - "github.com/yaoapp/yao/engine" - "github.com/yaoapp/yao/share" -) - -var websocketCmd = &cobra.Command{ - Use: "websocket", - Short: L("Open a websocket connection"), - Long: L("Open a websocket connection"), - Run: func(cmd *cobra.Command, args []string) { - defer share.SessionStop() - defer gou.KillPlugins() - defer func() { - err := exception.Catch(recover()) - if err != nil { - fmt.Println(color.RedString(L("Fatal: %s"), err.Error())) - } - }() - - Boot() - cfg := config.Conf - cfg.Session.IsCLI = true - engine.Load(cfg) - if len(args) < 1 { - fmt.Println(color.RedString(L("Not enough arguments"))) - fmt.Println(color.WhiteString(share.BUILDNAME + " help")) - return - } - - name := args[0] - websocket, has := gou.WebSockets[name] - if !has { - fmt.Println(color.RedString(L("%s not exists!"), name)) - return - } - - url := websocket.URL - protocols := websocket.Protocols - argsLen := len(args) - if argsLen > 1 { - url = args[1] - } - - if argsLen > 2 { - protocols = args[2:] - } - - fmt.Println(color.WhiteString("\n---------------------------------")) - fmt.Println(color.WhiteString(websocket.Name)) - fmt.Println(color.WhiteString("---------------------------------")) - fmt.Println(color.GreenString(" URL: %s", url)) - fmt.Println(color.GreenString("Protocols: %s", strings.Join(protocols, ","))) - fmt.Println(color.WhiteString("--------------------------------------")) - pargs := append([]string{url}, protocols...) - err := websocket.Open(pargs...) - if err != nil { - fmt.Println(color.RedString(L("%s"), err.Error())) - return - } - }, -} +// var websocketCmd = &cobra.Command{ +// Use: "websocket", +// Short: L("Open a websocket connection"), +// Long: L("Open a websocket connection"), +// Run: func(cmd *cobra.Command, args []string) { +// defer share.SessionStop() +// defer plugin.KillAll() +// defer func() { +// err := exception.Catch(recover()) +// if err != nil { +// fmt.Println(color.RedString(L("Fatal: %s"), err.Error())) +// } +// }() + +// Boot() +// cfg := config.Conf +// cfg.Session.IsCLI = true +// engine.Load(cfg) +// if len(args) < 1 { +// fmt.Println(color.RedString(L("Not enough arguments"))) +// fmt.Println(color.WhiteString(share.BUILDNAME + " help")) +// return +// } + +// name := args[0] +// websocket, has := websocket.WebSockets[name] +// if !has { +// fmt.Println(color.RedString(L("%s not exists!"), name)) +// return +// } + +// url := websocket.URL +// protocols := websocket.Protocols +// argsLen := len(args) +// if argsLen > 1 { +// url = args[1] +// } + +// if argsLen > 2 { +// protocols = args[2:] +// } + +// fmt.Println(color.WhiteString("\n---------------------------------")) +// fmt.Println(color.WhiteString(websocket.Name)) +// fmt.Println(color.WhiteString("---------------------------------")) +// fmt.Println(color.GreenString(" URL: %s", url)) +// fmt.Println(color.GreenString("Protocols: %s", strings.Join(protocols, ","))) +// fmt.Println(color.WhiteString("--------------------------------------")) +// pargs := append([]string{url}, protocols...) +// err := websocket.Open(pargs...) +// if err != nil { +// fmt.Println(color.RedString(L("%s"), err.Error())) +// return +// } +// }, +// } diff --git a/config/config.go b/config/config.go index 664368387b..e87e52abac 100644 --- a/config/config.go +++ b/config/config.go @@ -21,6 +21,9 @@ var Conf Config // LogOutput 日志输出 var LogOutput *os.File // 日志文件 +// DSLExtensions the dsl file Extensions +var DSLExtensions = []string{".yao", ".json", ".jsonc"} + func init() { filename, _ := filepath.Abs(filepath.Join(".", ".env")) if _, err := os.Stat(filename); errors.Is(err, os.ErrNotExist) { diff --git a/crypto/crypto_test.go b/crypto/crypto_test.go index 2a85bbd481..2efe614bbd 100644 --- a/crypto/crypto_test.go +++ b/crypto/crypto_test.go @@ -4,65 +4,65 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" ) func TestMD4(t *testing.T) { // Hash args := []interface{}{"MD4", "123456"} - res := gou.NewProcess("yao.crypto.hash", args...).Run() + res := process.New("yao.crypto.hash", args...).Run() assert.Equal(t, "585028aa0f794af812ee3be8804eb14a", res) // HMac args = append(args, "123456") - res = gou.NewProcess("yao.crypto.hmac", args...).Run() + res = process.New("yao.crypto.hmac", args...).Run() assert.Equal(t, "356f45727db95d65843b2794474d741c", res) } func TestMD5(t *testing.T) { // Hash args := []interface{}{"MD5", "123456"} - res := gou.NewProcess("yao.crypto.hash", args...).Run() + res := process.New("yao.crypto.hash", args...).Run() assert.Equal(t, "e10adc3949ba59abbe56e057f20f883e", res) // HMac args = append(args, "123456") - res = gou.NewProcess("yao.crypto.hmac", args...).Run() + res = process.New("yao.crypto.hmac", args...).Run() assert.Equal(t, "30ce71a73bdd908c3955a90e8f7429ef", res) } func TestSHA1(t *testing.T) { // Hash args := []interface{}{"SHA1", "123456"} - res := gou.NewProcess("yao.crypto.hash", args...).Run() + res := process.New("yao.crypto.hash", args...).Run() assert.Equal(t, "7c4a8d09ca3762af61e59520943dc26494f8941b", res) // HMac args = append(args, "123456") - res = gou.NewProcess("yao.crypto.hmac", args...).Run() + res = process.New("yao.crypto.hmac", args...).Run() assert.Equal(t, "74b55b6ab2b8e438ac810435e369e3047b3951d0", res) } func TestSHA256(t *testing.T) { // Hash args := []interface{}{"SHA256", "123456"} - res := gou.NewProcess("yao.crypto.hash", args...).Run() + res := process.New("yao.crypto.hash", args...).Run() assert.Equal(t, "8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92", res) // HMac args = append(args, "123456") - res = gou.NewProcess("yao.crypto.hmac", args...).Run() + res = process.New("yao.crypto.hmac", args...).Run() assert.Equal(t, "b8ad08a3a547e35829b821b75370301dd8c4b06bdd7771f9b541a75914068718", res) } func TestSHA1Base64(t *testing.T) { // Hash args := []interface{}{"SHA1", "123456"} - res := gou.NewProcess("yao.crypto.hash", args...).Run() + res := process.New("yao.crypto.hash", args...).Run() assert.Equal(t, "7c4a8d09ca3762af61e59520943dc26494f8941b", res) // HMac args = append(args, "123456", "base64") - res = gou.NewProcess("yao.crypto.hmac", args...).Run() + res = process.New("yao.crypto.hmac", args...).Run() assert.Equal(t, "dLVbarK45DisgQQ142njBHs5UdA=", res) } diff --git a/crypto/process.go b/crypto/process.go index dba48dd92b..c53eb7e835 100644 --- a/crypto/process.go +++ b/crypto/process.go @@ -1,22 +1,22 @@ package crypto import ( - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" "github.com/yaoapp/kun/exception" ) func init() { - gou.RegisterProcessHandler("yao.crypto.hash", ProcessHash) // deprecated → crypto.Hash - gou.RegisterProcessHandler("yao.crypto.hmac", ProcessHmac) // deprecated → crypto.Hash + process.Register("yao.crypto.hash", ProcessHash) // deprecated → crypto.Hash + process.Register("yao.crypto.hmac", ProcessHmac) // deprecated → crypto.Hash - gou.AliasProcess("yao.crypto.hash", "crypto.Hash") - gou.AliasProcess("yao.crypto.hmac", "crypto.Hmac") + process.Alias("yao.crypto.hash", "crypto.Hash") + process.Alias("yao.crypto.hmac", "crypto.Hmac") } // ProcessHash yao.crypto.hash Crypto Hash // Args[0] string: the hash function name. MD4/MD5/SHA1/SHA224/SHA256/SHA384/SHA512/MD5SHA1/RIPEMD160/SHA3_224/SHA3_256/SHA3_384/SHA3_512/SHA512_224/SHA512_256/BLAKE2s_256/BLAKE2b_256/BLAKE2b_384/BLAKE2b_512 // Args[1] string: value -func ProcessHash(process *gou.Process) interface{} { +func ProcessHash(process *process.Process) interface{} { process.ValidateArgNums(2) typ := process.ArgsString(0) value := process.ArgsString(1) @@ -38,7 +38,7 @@ func ProcessHash(process *gou.Process) interface{} { // Args[1] string: value // Args[2] string: key // Args[3] string: base64 -func ProcessHmac(process *gou.Process) interface{} { +func ProcessHmac(process *process.Process) interface{} { process.ValidateArgNums(3) typ := process.ArgsString(0) value := process.ArgsString(1) diff --git a/engine/init_test.go b/engine/init_test.go index fda9f4cef4..0f0e76f814 100644 --- a/engine/init_test.go +++ b/engine/init_test.go @@ -4,7 +4,6 @@ import ( "os" "testing" - "github.com/yaoapp/gou" "github.com/yaoapp/yao/config" ) @@ -19,7 +18,7 @@ func TestMain(m *testing.M) { exitVal := m.Run() // we can do clean up code here - gou.KillPlugins() + // gou.KillPlugins() os.Exit(exitVal) } diff --git a/engine/load.go b/engine/load.go index 6df2dd719f..de11c7f07f 100644 --- a/engine/load.go +++ b/engine/load.go @@ -7,12 +7,9 @@ import ( "strings" "github.com/fatih/color" - "github.com/yaoapp/gou" "github.com/yaoapp/kun/exception" "github.com/yaoapp/yao/api" - "github.com/yaoapp/yao/app" "github.com/yaoapp/yao/cert" - "github.com/yaoapp/yao/chart" "github.com/yaoapp/yao/config" "github.com/yaoapp/yao/connector" "github.com/yaoapp/yao/flow" @@ -20,40 +17,36 @@ import ( "github.com/yaoapp/yao/i18n" "github.com/yaoapp/yao/importer" "github.com/yaoapp/yao/model" - "github.com/yaoapp/yao/page" "github.com/yaoapp/yao/plugin" "github.com/yaoapp/yao/query" - "github.com/yaoapp/yao/runtime" "github.com/yaoapp/yao/schedule" "github.com/yaoapp/yao/script" "github.com/yaoapp/yao/share" "github.com/yaoapp/yao/socket" "github.com/yaoapp/yao/store" "github.com/yaoapp/yao/studio" - "github.com/yaoapp/yao/table" "github.com/yaoapp/yao/task" "github.com/yaoapp/yao/websocket" "github.com/yaoapp/yao/widget" - "github.com/yaoapp/yao/widgets" ) // Load 根据配置加载 API, FLow, Model, Plugin func Load(cfg config.Config) (err error) { defer func() { err = exception.Catch(recover()) }() - // Load Runtime - err = runtime.Load(cfg) - if err != nil { - printErr(cfg.Mode, "Runtime", err) - } + // // Load Runtime + // err = runtime.Load(cfg) + // if err != nil { + // printErr(cfg.Mode, "Runtime", err) + // } - // 加载应用信息 - // 第一步: 加载应用信息 - app.Load(cfg) + // // 加载应用信息 + // // 第一步: 加载应用信息 + // app.Load(cfg) // 加密密钥函数 - gou.LoadCrypt(fmt.Sprintf(`{"key":"%s"}`, cfg.DB.AESKey), "AES") - gou.LoadCrypt(`{}`, "PASSWORD") + // model.LoadCrypt(fmt.Sprintf(`{"key":"%s"}`, cfg.DB.AESKey), "AES") + // gou.LoadCrypt(`{}`, "PASSWORD") // Load Certs err = cert.Load(cfg) @@ -137,47 +130,47 @@ func Load(cfg config.Config) (err error) { printErr(cfg.Mode, "Plugin", err) } - // XGEN 1.0 - if share.App.XGen == "1.0" { - - // SET XGEN_BASE - // adminRoot := "yao" - // if share.App.Optional != nil { - // if root, has := share.App.Optional["adminRoot"]; has { - // adminRoot = fmt.Sprintf("%v", root) - // } - // } - // os.Setenv("XGEN_BASE", adminRoot) - - // Load build-in widgets - err = widgets.Load(cfg) - if err != nil { - printErr(cfg.Mode, "Widgets", err) - } - - delete(gou.APIs, "xiang.table") - delete(gou.APIs, "xiang.page") - delete(gou.APIs, "xiang.chart") - delete(gou.APIs, "xiang.xiang") - delete(gou.APIs, "xiang.user") - delete(gou.APIs, "xiang.storage") - - } else { // old version - err = table.Load(cfg) // 加载数据表格 table - if err != nil { - printErr(cfg.Mode, "Table", err) - } - - err = chart.Load(cfg) // 加载分析图表 chart - if err != nil { - printErr(cfg.Mode, "Chart", err) - } - - err = page.Load(cfg) // 加载页面 page 忽略错误 - if err != nil { - printErr(cfg.Mode, "Page", err) - } - } + // // XGEN 1.0 + // if share.App.XGen == "1.0" { + + // // SET XGEN_BASE + // // adminRoot := "yao" + // // if share.App.Optional != nil { + // // if root, has := share.App.Optional["adminRoot"]; has { + // // adminRoot = fmt.Sprintf("%v", root) + // // } + // // } + // // os.Setenv("XGEN_BASE", adminRoot) + + // // Load build-in widgets + // err = widgets.Load(cfg) + // if err != nil { + // printErr(cfg.Mode, "Widgets", err) + // } + + // delete(gou.APIs, "xiang.table") + // delete(gou.APIs, "xiang.page") + // delete(gou.APIs, "xiang.chart") + // delete(gou.APIs, "xiang.xiang") + // delete(gou.APIs, "xiang.user") + // delete(gou.APIs, "xiang.storage") + + // } else { // old version + // err = table.Load(cfg) // 加载数据表格 table + // if err != nil { + // printErr(cfg.Mode, "Table", err) + // } + + // err = chart.Load(cfg) // 加载分析图表 chart + // if err != nil { + // printErr(cfg.Mode, "Chart", err) + // } + + // err = page.Load(cfg) // 加载页面 page 忽略错误 + // if err != nil { + // printErr(cfg.Mode, "Page", err) + // } + // } importer.Load(cfg) // 加载数据导入 imports @@ -223,51 +216,51 @@ func printErr(mode, widget string, err error) { // Reload 根据配置重新加载 API, FLow, Model, Plugin func Reload(cfg config.Config) { - gou.APIs = map[string]*gou.API{} - gou.Models = map[string]*gou.Model{} - gou.Flows = map[string]*gou.Flow{} - gou.Plugins = map[string]*gou.Plugin{} + // gou.APIs = map[string]*gou.API{} + // gou.Models = map[string]*gou.Model{} + // gou.Flows = map[string]*gou.Flow{} + // gou.Plugins = map[string]*gou.Plugin{} Load(cfg) } // LoadEngine 加载引擎的 API, Flow, Model 配置 func LoadEngine(from ...string) { - var scripts []share.Script - if len(from) > 0 { - scripts = share.GetFilesFS(from[0], ".json") - } else { - scripts = share.GetFilesBin("yao", ".json") - } - - if scripts == nil { - exception.New("读取文件失败", 500, from).Throw() - } - - if len(scripts) == 0 { - exception.New("读取文件失败, 未找到任何可执行脚本", 500, from).Throw() - } - - // 加载 API, Flow, Models, Table, Chart, Screens - for _, script := range scripts { - switch script.Type { - case "models": - gou.LoadModel(string(script.Content), "xiang."+script.Name) - break - case "flows": - gou.LoadFlow(string(script.Content), "xiang."+script.Name) - break - case "apis": - gou.LoadAPI(string(script.Content), "xiang."+script.Name) - break - } - } - - // 加载数据应用 - for _, script := range scripts { - switch script.Type { - case "tables": - table.LoadTable(string(script.Content), "xiang."+script.Name) - break - } - } + // var scripts []share.Script + // if len(from) > 0 { + // scripts = share.GetFilesFS(from[0], ".json") + // } else { + // scripts = share.GetFilesBin("yao", ".json") + // } + + // if scripts == nil { + // exception.New("读取文件失败", 500, from).Throw() + // } + + // if len(scripts) == 0 { + // exception.New("读取文件失败, 未找到任何可执行脚本", 500, from).Throw() + // } + + // // 加载 API, Flow, Models, Table, Chart, Screens + // for _, script := range scripts { + // switch script.Type { + // case "models": + // gou.LoadModel(string(script.Content), "xiang."+script.Name) + // break + // case "flows": + // gou.LoadFlow(string(script.Content), "xiang."+script.Name) + // break + // case "apis": + // gou.LoadAPI(string(script.Content), "xiang."+script.Name) + // break + // } + // } + + // // 加载数据应用 + // for _, script := range scripts { + // switch script.Type { + // case "tables": + // table.LoadTable(string(script.Content), "xiang."+script.Name) + // break + // } + // } } diff --git a/engine/process.go b/engine/process.go index e82dd72984..98a9f2516e 100644 --- a/engine/process.go +++ b/engine/process.go @@ -1,30 +1,26 @@ package engine import ( - "path/filepath" - - "github.com/yaoapp/gou" - "github.com/yaoapp/yao/config" + "github.com/yaoapp/gou/process" "github.com/yaoapp/yao/share" - "github.com/yaoapp/yao/xfs" ) func init() { // 注册处理器 - gou.RegisterProcessHandler("xiang.main.Ping", processPing) // deprecated → utils.app.Ping @/utils/process.go - gou.AliasProcess("xiang.main.Ping", "xiang.sys.Ping") // deprecated + process.Register("xiang.main.Ping", processPing) // deprecated → utils.app.Ping @/utils/process.go + process.Alias("xiang.main.Ping", "xiang.sys.Ping") // deprecated - gou.RegisterProcessHandler("xiang.main.FileContent", processFileContent) // deprecated - gou.RegisterProcessHandler("xiang.main.AppFileContent", processAppFileContent) // deprecated + process.Register("xiang.main.FileContent", processFileContent) // deprecated + process.Register("xiang.main.AppFileContent", processAppFileContent) // deprecated - gou.RegisterProcessHandler("xiang.main.Inspect", processInspect) // deprecated → utils.app.Inspect @/utils/process.go - gou.AliasProcess("xiang.main.Inspect", "xiang.sys.Inspect") // deprecated + process.Register("xiang.main.Inspect", processInspect) // deprecated → utils.app.Inspect @/utils/process.go + process.Alias("xiang.main.Inspect", "xiang.sys.Inspect") // deprecated - gou.RegisterProcessHandler("xiang.main.Favicon", processFavicon) // deprecated + process.Register("xiang.main.Favicon", processFavicon) // deprecated } // processCreate 运行模型 MustCreate -func processPing(process *gou.Process) interface{} { +func processPing(process *process.Process) interface{} { res := map[string]interface{}{ "engine": share.BUILDNAME, "version": share.VERSION, @@ -33,37 +29,40 @@ func processPing(process *gou.Process) interface{} { } // processInspect 返回系统信息 -func processInspect(process *gou.Process) interface{} { +func processInspect(process *process.Process) interface{} { share.App.Icons.Set("favicon", "/api/xiang/favicon.ico") return share.App.Public() } // processFavicon 运行模型 MustCreate -func processFavicon(process *gou.Process) interface{} { - return xfs.DecodeString(share.App.Icons.Get("png").(string)) +func processFavicon(process *process.Process) interface{} { + // return xfs.DecodeString(share.App.Icons.Get("png").(string)) + return nil } // processFileContent 返回文件内容 -func processFileContent(process *gou.Process) interface{} { - process.ValidateArgNums(2) - filename := process.ArgsString(0) - encode := process.ArgsBool(1, true) - content := xfs.Stor.MustReadFile(filename) - if encode { - return xfs.Encode(content) - } - return string(content) +func processFileContent(process *process.Process) interface{} { + // process.ValidateArgNums(2) + // filename := process.ArgsString(0) + // encode := process.ArgsBool(1, true) + // content := xfs.Stor.MustReadFile(filename) + // if encode { + // return xfs.Encode(content) + // } + // return string(content) + return nil } // processAppFileContent 返回应用文件内容 -func processAppFileContent(process *gou.Process) interface{} { - process.ValidateArgNums(2) - fs := xfs.New(filepath.Join(config.Conf.Root, "data")) - filename := process.ArgsString(0) - encode := process.ArgsBool(1, true) - content := fs.MustReadFile(filename) - if encode { - return xfs.Encode(content) - } - return string(content) +func processAppFileContent(process *process.Process) interface{} { + // process.ValidateArgNums(2) + // fs := xfs.New(filepath.Join(config.Conf.Root, "data")) + // filename := process.ArgsString(0) + // encode := process.ArgsBool(1, true) + // content := fs.MustReadFile(filename) + // if encode { + // return xfs.Encode(content) + // } + // return string(content) + return nil } diff --git a/engine/process_test.go b/engine/process_test.go index 3aff66d7e1..3fe1b3b240 100644 --- a/engine/process_test.go +++ b/engine/process_test.go @@ -4,25 +4,25 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" "github.com/yaoapp/yao/share" ) func TestProcessPing(t *testing.T) { - process := gou.NewProcess("xiang.main.ping") + process := process.New("xiang.main.ping") res, ok := processPing(process).(map[string]interface{}) assert.True(t, ok) assert.Equal(t, res["version"], share.VERSION) } func TestProcessAliasPing(t *testing.T) { - res, ok := gou.NewProcess("xiang.sys.Ping").Run().(map[string]interface{}) + res, ok := process.New("xiang.sys.Ping").Run().(map[string]interface{}) assert.True(t, ok) assert.Equal(t, res["version"], share.VERSION) } func TestProcessInspect(t *testing.T) { - res, ok := gou.NewProcess("xiang.sys.Inspect").Run().(share.AppInfo) + res, ok := process.New("xiang.sys.Inspect").Run().(share.AppInfo) assert.True(t, ok) assert.NotNil(t, res.Version) } diff --git a/engine/user_test.go b/engine/user_test.go deleted file mode 100644 index 0344805728..0000000000 --- a/engine/user_test.go +++ /dev/null @@ -1,29 +0,0 @@ -package engine - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/yaoapp/yao/user" -) - -func TestUserAuth(t *testing.T) { - - res := user.Auth("email", "xiang@iqka.com", "A123456p+") - assert.True(t, res.Has("user")) - assert.True(t, res.Has("token")) - assert.True(t, res.Has("expires_at")) - assert.Panics(t, func() { - user.Auth("email", "xiang@iqka.com", "A123456p+22") - }) - - res = user.Auth("mobile", "13900001111", "U123456p+") - assert.True(t, res.Has("user")) - assert.True(t, res.Has("token")) - assert.True(t, res.Has("expires_at")) - - assert.Panics(t, func() { - user.Auth("email", "1390000111", "A123456p+22") - }) - -} diff --git a/flow/flow.go b/flow/flow.go index c0b21700a4..b938d87562 100644 --- a/flow/flow.go +++ b/flow/flow.go @@ -1,58 +1,17 @@ package flow import ( - "fmt" - "path/filepath" - - "github.com/yaoapp/gou" - "github.com/yaoapp/kun/log" + "github.com/yaoapp/gou/application" + "github.com/yaoapp/gou/flow" "github.com/yaoapp/yao/config" "github.com/yaoapp/yao/share" ) // Load 加载业务逻辑编排 func Load(cfg config.Config) error { - if share.BUILDIN { - return LoadBuildIn("flows", "") - } - return LoadFrom(filepath.Join(cfg.Root, "flows"), "") -} - -// LoadFrom 从特定目录加载 -func LoadFrom(dir string, prefix string) error { - - if share.DirNotExists(dir) { - return fmt.Errorf("%s does not exists", dir) - } - - err := share.Walk(dir, ".json", func(root, filename string) { - name := prefix + share.SpecName(root, filename) - content := share.ReadFile(filename) - _, err := gou.LoadFlowReturn(string(content), name) - if err != nil { - log.With(log.F{"root": root, "file": filename}).Error(err.Error()) - } - }) - - if err != nil { + exts := []string{"*.flow.yao", "*.flow.json", "*.flow.jsonc"} + return application.App.Walk("apis", func(root, file string, isdir bool) error { + _, err := flow.Load(file, share.ID(root, file)) return err - } - - // Load Script - err = share.Walk(dir, ".js", func(root, filename string) { - name := prefix + share.SpecName(root, filename) - flow := gou.SelectFlow(name) - if flow != nil { - script := share.ScriptName(filename) - content := share.ReadFile(filename) - flow.LoadScript(string(content), script) - } - }) - - return err -} - -// LoadBuildIn 从制品中读取 -func LoadBuildIn(dir string, prefix string) error { - return nil + }, exts...) } diff --git a/flow/flow_test.go b/flow/flow_test.go index 96619c5aa5..f9edb93acc 100644 --- a/flow/flow_test.go +++ b/flow/flow_test.go @@ -4,22 +4,18 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/flow" "github.com/yaoapp/yao/config" - "github.com/yaoapp/yao/runtime" ) func TestLoad(t *testing.T) { - runtime.Load(config.Conf) - gou.Flows = make(map[string]*gou.Flow) Load(config.Conf) - LoadFrom("not a path", "404.") check(t) } func check(t *testing.T) { keys := []string{} - for key := range gou.Flows { + for key := range flow.Flows { keys = append(keys, key) } assert.Equal(t, 26, len(keys)) diff --git a/go.mod b/go.mod index 95fc400c64..03c7e569c6 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,6 @@ module github.com/yaoapp/yao go 1.19 require ( - github.com/aliyun/alibaba-cloud-sdk-go v1.61.1286 github.com/blang/semver v3.5.1+incompatible github.com/caarlos0/env/v6 v6.9.1 github.com/elazarl/go-bindata-assetfs v1.0.1 @@ -15,11 +14,10 @@ require ( github.com/json-iterator/go v1.1.12 github.com/mojocn/base64Captcha v1.3.5 github.com/rhysd/go-github-selfupdate v1.2.3 - github.com/spf13/afero v1.6.0 github.com/spf13/cobra v1.2.1 github.com/stretchr/testify v1.7.1 github.com/xuri/excelize/v2 v2.5.0 - github.com/yaoapp/gou v0.0.0-20211120135538-e5387704eb03 + github.com/yaoapp/gou v0.10.3 github.com/yaoapp/kun v0.9.0 github.com/yaoapp/xun v0.9.0 golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d @@ -59,7 +57,6 @@ require ( github.com/hashicorp/golang-lru v0.5.4 // indirect github.com/hashicorp/yamux v0.0.0-20211028200310-0bc27b27de87 // indirect github.com/inconshreveable/mousetrap v1.0.0 // indirect - github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af // indirect github.com/jmoiron/sqlx v1.3.4 // indirect github.com/klauspost/compress v1.13.6 // indirect github.com/leodido/go-urn v1.2.0 // indirect @@ -81,7 +78,6 @@ require ( github.com/robfig/cron/v3 v3.0.1 // indirect github.com/sirupsen/logrus v1.8.1 // indirect github.com/spf13/pflag v1.0.5 // indirect - github.com/takama/daemon v1.0.0 // indirect github.com/tidwall/btree v1.1.0 // indirect github.com/tidwall/buntdb v1.2.9 // indirect github.com/tidwall/gjson v1.12.1 // indirect @@ -109,17 +105,16 @@ require ( google.golang.org/grpc v1.46.2 // indirect google.golang.org/protobuf v1.28.0 // indirect gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 // indirect - gopkg.in/ini.v1 v1.62.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 - rogchap.com/v8go v0.7.0 // indirect + rogchap.com/v8go v0.8.0 // indirect ) // go env -w GOPRIVATE=github.com/yaoapp/* replace github.com/yaoapp/kun => ../kun // kun local -replace github.com/yaoapp/xun => ../xun // gou local +replace github.com/yaoapp/xun => ../xun // xun local replace github.com/yaoapp/gou => ../gou // gou local diff --git a/go.sum b/go.sum index 3fc5b8e6ce..9aa4e84d5f 100644 --- a/go.sum +++ b/go.sum @@ -41,8 +41,6 @@ github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03 github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/TylerBrock/colorjson v0.0.0-20200706003622-8a50f05110d2 h1:ZBbLwSJqkHBuFDA6DUhhse0IGJ7T5bemHyNILUjvOq4= github.com/TylerBrock/colorjson v0.0.0-20200706003622-8a50f05110d2/go.mod h1:VSw57q4QFiWDbRnjdX8Cb3Ow0SFncRw+bA/ofY6Q83w= -github.com/aliyun/alibaba-cloud-sdk-go v1.61.1286 h1:+Ah33S/QRnOFp4dM6VV2gYDbFu3Cj4HrRy1VpOhBzm8= -github.com/aliyun/alibaba-cloud-sdk-go v1.61.1286/go.mod h1:9CMdKNL3ynIGPpfTcdwTvIm8SGuAZYYC4jFVSSvE1YQ= github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= @@ -122,7 +120,6 @@ github.com/go-sql-driver/mysql v1.6.0 h1:BCTh4TKNUYmOmMUcQ3IipzF5prigylS7XXjEkfC github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= -github.com/goji/httpauth v0.0.0-20160601135302-2da839ab0f4d/go.mod h1:nnjvkQ9ptGaCkuDUx6wNykzzlUixGxvkme+H/lnzb+A= github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY= github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I= github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 h1:DACJavvAHhabrF08vX0COfcOBJRhZ8lUbR+ZWIs0Y5g= @@ -199,7 +196,6 @@ github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= -github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= @@ -241,20 +237,16 @@ github.com/inconshreveable/go-update v0.0.0-20160112193335-8152e7eb6ccf/go.mod h github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/jhump/protoreflect v1.6.0 h1:h5jfMVslIg6l29nsMs0D8Wj17RDVdNYti0vDN/PZZoE= -github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af h1:pmfjZENx5imkbgOkpRUYLnmbU7UEFbjtDA2hxJ1ichM= -github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= github.com/jmoiron/sqlx v1.3.4 h1:wv+0IJZfL5z0uZoUjlpKgHkgaFSYD+r9CfrXjEXsO7w= github.com/jmoiron/sqlx v1.3.4/go.mod h1:2BljVx/86SuTyjE+aPYlHCTNvZrnJXghYGpNiXLBMCQ= github.com/joho/godotenv v1.3.0 h1:Zjp+RcGpHhGlrMbJzXTrZZPrWj+1vfm90La1wgB6Bhc= github.com/joho/godotenv v1.3.0/go.mod h1:7hK45KPybAkOC6peb+G5yklZfMxEjkZhHbwpqxOKXbg= -github.com/json-iterator/go v1.1.5/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= -github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= @@ -335,7 +327,6 @@ github.com/richardlehane/mscfb v1.0.3 h1:rD8TBkYWkObWO0oLDFCbwMeZ4KoalxQy+QgniCj github.com/richardlehane/mscfb v1.0.3/go.mod h1:YzVpcZg9czvAuhk9T+a3avCpcFPMUWm7gK3DypaEsUk= github.com/richardlehane/msoleps v1.0.1 h1:RfrALnSNXzmXLbGct/P2b4xkFz4e8Gmj/0Vj9M9xC1o= github.com/richardlehane/msoleps v1.0.1/go.mod h1:BWev5JBpU9Ko2WAgmZEuiz4/u3ZYTKbjLycmwiWUfWg= -github.com/robfig/cron v1.2.0/go.mod h1:JGuDeoQd7Z6yL4zQhZ3OPEVHB7fL6Ka6skscFHfmt2k= github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs= github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro= github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= @@ -346,11 +337,8 @@ github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE= github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= -github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= -github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIKYqbNC9s= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= -github.com/spf13/afero v1.6.0 h1:xoax2sJ2DT8S8xA2paPFjDCScCNeWsg75VG0DLRreiY= github.com/spf13/afero v1.6.0/go.mod h1:Ai8FlHk4v/PARR026UzYexafAt9roJ7LcLMAmO6Z93I= github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= github.com/spf13/cobra v1.2.1 h1:+KmjbUw1hriSNMF55oPrkZcb27aECyrj8V2ytv7kWDw= @@ -369,8 +357,6 @@ github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= -github.com/takama/daemon v1.0.0 h1:XS3VLnFKmqw2Z7fQ/dHRarrVjdir9G3z7BEP8osjizQ= -github.com/takama/daemon v1.0.0/go.mod h1:gKlhcjbqtBODg5v9H1nj5dU1a2j2GemtuWSNLD5rxOE= github.com/tcnksm/go-gitconfig v0.1.2 h1:iiDhRitByXAEyjgBqsKi9QU4o2TNtv9kPP3RgPgXBPw= github.com/tcnksm/go-gitconfig v0.1.2/go.mod h1:/8EhP4H7oJZdIPyT+/UIsG87kTzrzM4UsLGSItWYCpE= github.com/tidwall/assert v0.1.0 h1:aWcKyRBUAdLoVebxo95N7+YZVTFF/ASTr7BN4sLP6XI= @@ -582,7 +568,6 @@ golang.org/x/sys v0.0.0-20200501052902-10377860bb8e/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200511232937-7e40ca221e25/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200722175500-76b94024e4b6/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200803210538-64077c9b5642/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200905004654-be1d3432aa8f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -797,7 +782,6 @@ gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogR gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= -gopkg.in/ini.v1 v1.62.0 h1:duBzk771uxoUuOlyRLkHsygud9+5lrlGjdFBb4mSKDU= gopkg.in/ini.v1 v1.62.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= diff --git a/helper/array.process.go b/helper/array.process.go index 16073cf52b..8f21110145 100644 --- a/helper/array.process.go +++ b/helper/array.process.go @@ -1,12 +1,12 @@ package helper import ( - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" "github.com/yaoapp/kun/maps" ) // ProcessArrayPluck xiang.helper.ArrayPluck 将多个数据记录集合,合并为一个数据记录集合 -func ProcessArrayPluck(process *gou.Process) interface{} { +func ProcessArrayPluck(process *process.Process) interface{} { process.ValidateArgNums(2) columns := process.ArgsStrings(0) pluck := process.ArgsMap(1) @@ -14,7 +14,7 @@ func ProcessArrayPluck(process *gou.Process) interface{} { } // ProcessArraySplit xiang.helper.ArraySplit 将多条数记录集合,分解为一个 columns:[]string 和 values: [][]interface{} -func ProcessArraySplit(process *gou.Process) interface{} { +func ProcessArraySplit(process *process.Process) interface{} { process.ValidateArgNums(1) records := process.ArgsRecords(0) columns, values := ArraySplit(records) @@ -25,7 +25,7 @@ func ProcessArraySplit(process *gou.Process) interface{} { } // ProcessArrayColumn xiang.helper.ArrayColumn 返回多条数据记录,指定字段数值。 -func ProcessArrayColumn(process *gou.Process) interface{} { +func ProcessArrayColumn(process *process.Process) interface{} { process.ValidateArgNums(2) records := process.ArgsRecords(0) name := process.ArgsString(1) @@ -34,7 +34,7 @@ func ProcessArrayColumn(process *gou.Process) interface{} { } // ProcessArrayKeep xiang.helper.ArrayKeep 仅保留指定键名的数据 -func ProcessArrayKeep(process *gou.Process) interface{} { +func ProcessArrayKeep(process *process.Process) interface{} { process.ValidateArgNums(2) records := process.ArgsRecords(0) columns := process.ArgsStrings(1) @@ -42,7 +42,7 @@ func ProcessArrayKeep(process *gou.Process) interface{} { } // ProcessArrayTree xiang.helper.ArrayTree 转换为属性结构 -func ProcessArrayTree(process *gou.Process) interface{} { +func ProcessArrayTree(process *process.Process) interface{} { process.ValidateArgNums(2) records := process.ArgsRecords(0) setting := process.ArgsMap(1) @@ -50,7 +50,7 @@ func ProcessArrayTree(process *gou.Process) interface{} { } // ProcessArrayUnique xiang.helper.ArrayUnique 数组排重 -func ProcessArrayUnique(process *gou.Process) interface{} { +func ProcessArrayUnique(process *process.Process) interface{} { process.ValidateArgNums(1) if arr, ok := process.Args[0].([]interface{}); ok { return ArrayUnique(arr) @@ -59,7 +59,7 @@ func ProcessArrayUnique(process *gou.Process) interface{} { } // ProcessArrayMapSet xiang.helper.ArrayMapSet 数组映射设定数值 -func ProcessArrayMapSet(process *gou.Process) interface{} { +func ProcessArrayMapSet(process *process.Process) interface{} { process.ValidateArgNums(3) arr, ok := process.Args[0].([]map[string]interface{}) if ok { @@ -71,7 +71,7 @@ func ProcessArrayMapSet(process *gou.Process) interface{} { } // ProcessArrayIndexes xiang.helper.ArrayIndexes 返回数组索引。 -func ProcessArrayIndexes(process *gou.Process) interface{} { +func ProcessArrayIndexes(process *process.Process) interface{} { process.ValidateArgNums(1) records := process.ArgsArray(0) res := []int{} @@ -82,7 +82,7 @@ func ProcessArrayIndexes(process *gou.Process) interface{} { } // ProcessArrayGet xiang.helper.ArrayGet 返回指定索引数据 -func ProcessArrayGet(process *gou.Process) interface{} { +func ProcessArrayGet(process *process.Process) interface{} { process.ValidateArgNums(2) records := process.ArgsArray(0) index := process.ArgsInt(1) diff --git a/helper/array_test.go b/helper/array_test.go index 099c950619..1d63b6244d 100644 --- a/helper/array_test.go +++ b/helper/array_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" "github.com/yaoapp/kun/maps" ) @@ -116,7 +116,7 @@ func TestProcessArrayPluck(t *testing.T) { "计费": map[string]interface{}{"key": "city", "value": "计费种类", "items": []map[string]interface{}{{"city": "北京", "计费种类": 6}, {"city": "西安", "计费种类": 3}}}, }, } - process := gou.NewProcess("xiang.helper.ArrayPluck", args...) + process := process.New("xiang.helper.ArrayPluck", args...) response := ProcessArrayPluck(process) assert.NotNil(t, response) items, ok := response.([]map[string]interface{}) @@ -137,7 +137,7 @@ func TestProcessArraySplit(t *testing.T) { {"name": "世纪互联蓝云", "short_name": "上海蓝云"}, }, } - process := gou.NewProcess("xiang.helper.ArraySplit", args...) + process := process.New("xiang.helper.ArraySplit", args...) response := process.Run() assert.NotNil(t, response) res, ok := response.(map[string]interface{}) @@ -159,7 +159,7 @@ func TestProcessArrayUnique(t *testing.T) { args := []interface{}{ []interface{}{1, 2, 3, 3}, } - process := gou.NewProcess("xiang.helper.ArrayUnique", args...) + process := process.New("xiang.helper.ArrayUnique", args...) response := process.Run() assert.NotNil(t, response) res, ok := response.([]interface{}) @@ -171,7 +171,7 @@ func TestProcessArrayIndexes(t *testing.T) { args := []interface{}{ []interface{}{1, 2, 3, 3}, } - response := gou.NewProcess("xiang.helper.ArrayIndexes", args...).Run() + response := process.New("xiang.helper.ArrayIndexes", args...).Run() assert.NotNil(t, response) res, ok := response.([]int) assert.True(t, ok) @@ -180,10 +180,10 @@ func TestProcessArrayIndexes(t *testing.T) { func TestProcessArrayGet(t *testing.T) { - response := gou.NewProcess("xiang.helper.ArrayGet", []interface{}{1, 2, 3, 3}, 2).Run() + response := process.New("xiang.helper.ArrayGet", []interface{}{1, 2, 3, 3}, 2).Run() assert.Equal(t, 3, response) - response = gou.NewProcess("xiang.helper.ArrayGet", []interface{}{1, 2, 3, 3}, 4).Run() + response = process.New("xiang.helper.ArrayGet", []interface{}{1, 2, 3, 3}, 4).Run() assert.Nil(t, response) } diff --git a/helper/captcha.go b/helper/captcha.go index 830b4faecb..a5c354a5c5 100644 --- a/helper/captcha.go +++ b/helper/captcha.go @@ -5,7 +5,7 @@ import ( "image/color" "github.com/mojocn/base64Captcha" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" "github.com/yaoapp/kun/any" "github.com/yaoapp/kun/exception" "github.com/yaoapp/kun/log" @@ -139,7 +139,7 @@ func captchaParseHexColorFast(s string) (c color.RGBA, err error) { } // ProcessCaptchaValidate xiang.helper.CaptchaValidate 校验图形/音频验证码 -func ProcessCaptchaValidate(process *gou.Process) interface{} { +func ProcessCaptchaValidate(process *process.Process) interface{} { process.ValidateArgNums(2) id := process.ArgsString(0) code := process.ArgsString(1) @@ -155,7 +155,7 @@ func ProcessCaptchaValidate(process *gou.Process) interface{} { } // ProcessCaptcha xiang.helper.Captcha 校验图形/音频验证码 -func ProcessCaptcha(process *gou.Process) interface{} { +func ProcessCaptcha(process *process.Process) interface{} { process.ValidateArgNums(1) option := CaptchaOption{ Width: any.Of(process.ArgsURLValue(0, "width", "240")).CInt(), diff --git a/helper/captcha_test.go b/helper/captcha_test.go index 6fb4cd8c63..3da526e73a 100644 --- a/helper/captcha_test.go +++ b/helper/captcha_test.go @@ -5,7 +5,7 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" "github.com/yaoapp/kun/maps" ) @@ -51,19 +51,19 @@ func TestProcessCaptcha(t *testing.T) { args := url.Values{} args.Add("type", "math") args.Add("lang", "zh") - process := gou.NewProcess("xiang.helper.Captcha", args) - res := process.Run().(maps.Map) + p := process.New("xiang.helper.Captcha", args) + res := p.Run().(maps.Map) assert.IsType(t, "string", res.Get("id")) assert.IsType(t, "string", res.Get("content")) value := captchaStore.Get(res.Get("id").(string), false) - process = gou.NewProcess("xiang.helper.CaptchaValidate", res.Get("id"), value) - assert.True(t, process.Run().(bool)) + p = process.New("xiang.helper.CaptchaValidate", res.Get("id"), value) + assert.True(t, p.Run().(bool)) assert.Panics(t, func() { - gou.NewProcess("xiang.helper.CaptchaValidate", res.Get("id"), "xxx").Run() + process.New("xiang.helper.CaptchaValidate", res.Get("id"), "xxx").Run() }) assert.Panics(t, func() { - gou.NewProcess("xiang.helper.CaptchaValidate", res.Get("id"), "").Run() + process.New("xiang.helper.CaptchaValidate", res.Get("id"), "").Run() }) } diff --git a/helper/case.go b/helper/case.go index d14a57e6fa..024a43121e 100644 --- a/helper/case.go +++ b/helper/case.go @@ -2,7 +2,7 @@ package helper import ( jsoniter "github.com/json-iterator/go" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" "github.com/yaoapp/kun/exception" ) @@ -18,7 +18,7 @@ type CaseParam struct { func Case(params ...CaseParam) interface{} { for _, param := range params { if When(param.When) { - return gou.NewProcess(param.Process, param.Args...).Run() + return process.New(param.Process, param.Args...).Run() } } return nil @@ -39,7 +39,7 @@ func CaseParamOf(v interface{}) CaseParam { } // ProcessCase xiang.helper.Case Case条件判断 -func ProcessCase(process *gou.Process) interface{} { +func ProcessCase(process *process.Process) interface{} { process.ValidateArgNums(1) params := []CaseParam{} for _, v := range process.Args { diff --git a/helper/case_test.go b/helper/case_test.go index bf17c2aa32..b8fde7fea1 100644 --- a/helper/case_test.go +++ b/helper/case_test.go @@ -4,12 +4,12 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" ) func TestCase(t *testing.T) { - gou.RegisterProcessHandler("xiang.unit.return", func(process *gou.Process) interface{} { + process.Register("xiang.unit.return", func(process *process.Process) interface{} { return process.Args }) @@ -38,7 +38,7 @@ func TestCase(t *testing.T) { func TestProcessCase(t *testing.T) { - gou.RegisterProcessHandler("xiang.unit.return", func(process *gou.Process) interface{} { + process.Register("xiang.unit.return", func(process *process.Process) interface{} { return process.Args }) @@ -56,7 +56,7 @@ func TestProcessCase(t *testing.T) { "args": []interface{}{"foo"}, }, } - process := gou.NewProcess("xiang.helper.Case", args...) + process := process.New("xiang.helper.Case", args...) res := process.Run().([]interface{}) assert.Equal(t, "world", res[0]) } diff --git a/helper/control.process.go b/helper/control.process.go index f118381578..2a9a5ac42e 100644 --- a/helper/control.process.go +++ b/helper/control.process.go @@ -1,17 +1,17 @@ package helper import ( - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" "github.com/yaoapp/kun/exception" ) // ProcessReturn xiang.helper.Return 返回数值 -func ProcessReturn(process *gou.Process) interface{} { +func ProcessReturn(process *process.Process) interface{} { return process.Args } // ProcessThrow xiang.helper.Throw 抛出异常 -func ProcessThrow(process *gou.Process) interface{} { +func ProcessThrow(process *process.Process) interface{} { process.ValidateArgNums(2) message := process.ArgsString(0) code := process.ArgsInt(1) diff --git a/helper/control_test.go b/helper/control_test.go index 78881ff1dd..b40aafe83c 100644 --- a/helper/control_test.go +++ b/helper/control_test.go @@ -4,19 +4,19 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" "github.com/yaoapp/kun/exception" ) func TestProcessThrow(t *testing.T) { e := exception.New("Someting error", 500) assert.PanicsWithValue(t, *e, func() { - gou.NewProcess("xiang.helper.Throw", "Someting error", 500).Run() + process.New("xiang.helper.Throw", "Someting error", 500).Run() }) } func TestProcessReturn(t *testing.T) { - v := gou.NewProcess("xiang.helper.Return", "hello", "world").Run().([]interface{}) + v := process.New("xiang.helper.Return", "hello", "world").Run().([]interface{}) assert.Equal(t, "hello", v[0]) assert.Equal(t, "world", v[1]) } diff --git a/helper/env.process.go b/helper/env.process.go index e72ea6b9a6..3fae0853f3 100644 --- a/helper/env.process.go +++ b/helper/env.process.go @@ -5,18 +5,18 @@ import ( "fmt" "os" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" ) // ProcessEnvGet xiang.helper.EnvGet 读取ENV -func ProcessEnvGet(process *gou.Process) interface{} { +func ProcessEnvGet(process *process.Process) interface{} { process.ValidateArgNums(1) name := process.ArgsString(0) return os.Getenv(name) } // ProcessEnvSet xiang.helper.EnvSet 设置ENV -func ProcessEnvSet(process *gou.Process) interface{} { +func ProcessEnvSet(process *process.Process) interface{} { process.ValidateArgNums(2) name := process.ArgsString(0) value := process.ArgsString(1) @@ -24,7 +24,7 @@ func ProcessEnvSet(process *gou.Process) interface{} { } // ProcessEnvMultiGet xiang.helper.MultiGet 读取ENV -func ProcessEnvMultiGet(process *gou.Process) interface{} { +func ProcessEnvMultiGet(process *process.Process) interface{} { process.ValidateArgNums(1) res := map[string]string{} for i := range process.Args { @@ -35,7 +35,7 @@ func ProcessEnvMultiGet(process *gou.Process) interface{} { } // ProcessEnvMultiSet xiang.helper.MultiSet 设置ENV -func ProcessEnvMultiSet(process *gou.Process) interface{} { +func ProcessEnvMultiSet(process *process.Process) interface{} { process.ValidateArgNums(1) envs := process.ArgsMap(0) message := "" diff --git a/helper/env_test.go b/helper/env_test.go index 91f51acd48..fa3548756a 100644 --- a/helper/env_test.go +++ b/helper/env_test.go @@ -4,21 +4,21 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" "github.com/yaoapp/kun/maps" ) func TestProcessEnv(t *testing.T) { - err := gou.NewProcess("xiang.helper.EnvSet", "XIANG_UNIT_TEST", "FOO").Run() + err := process.New("xiang.helper.EnvSet", "XIANG_UNIT_TEST", "FOO").Run() assert.Nil(t, err) - test := gou.NewProcess("xiang.helper.EnvGet", "XIANG_UNIT_TEST").Run().(string) + test := process.New("xiang.helper.EnvGet", "XIANG_UNIT_TEST").Run().(string) assert.Equal(t, "FOO", test) } func TestProcessEnvMulti(t *testing.T) { - err := gou.NewProcess("xiang.helper.EnvMultiSet", maps.Map{"XIANG_UNIT_TEST": "FOO", "XIANG_UNIT_TEST2": "BAR"}).Run() + err := process.New("xiang.helper.EnvMultiSet", maps.Map{"XIANG_UNIT_TEST": "FOO", "XIANG_UNIT_TEST2": "BAR"}).Run() assert.Nil(t, err) - test := gou.NewProcess("xiang.helper.EnvMultiGet", "XIANG_UNIT_TEST", "XIANG_UNIT_TEST2").Run().(map[string]string) + test := process.New("xiang.helper.EnvMultiGet", "XIANG_UNIT_TEST", "XIANG_UNIT_TEST2").Run().(map[string]string) assert.Equal(t, "FOO", test["XIANG_UNIT_TEST"]) assert.Equal(t, "BAR", test["XIANG_UNIT_TEST2"]) } diff --git a/helper/hex.process.go b/helper/hex.process.go index d43be53a65..08684f3ecf 100644 --- a/helper/hex.process.go +++ b/helper/hex.process.go @@ -3,12 +3,12 @@ package helper import ( "encoding/hex" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" "github.com/yaoapp/kun/log" ) // ProcessHexToString xiang.helper.HexToString -func ProcessHexToString(process *gou.Process) interface{} { +func ProcessHexToString(process *process.Process) interface{} { process.ValidateArgNums(1) switch process.Args[0].(type) { diff --git a/helper/hex_test.go b/helper/hex_test.go index dd1fee71c6..1838c36525 100644 --- a/helper/hex_test.go +++ b/helper/hex_test.go @@ -6,46 +6,43 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" - "github.com/yaoapp/yao/config" - "github.com/yaoapp/yao/flow" - "github.com/yaoapp/yao/runtime" + "github.com/yaoapp/gou/process" "github.com/yaoapp/yao/share" ) func TestProcessHexToString(t *testing.T) { - res, err := gou.NewProcess("xiang.helper.HexToString", []byte{0x0, 0x1}).Exec() + res, err := process.New("xiang.helper.HexToString", []byte{0x0, 0x1}).Exec() assert.Nil(t, err) assert.Equal(t, "0001", res) - res, err = gou.NewProcess("xiang.helper.HexToString", string([]byte{0x0, 0x1})).Exec() + res, err = process.New("xiang.helper.HexToString", string([]byte{0x0, 0x1})).Exec() assert.Nil(t, err) assert.Equal(t, "0001", res) - res, err = gou.NewProcess("xiang.helper.HexToString", 1024).Exec() + res, err = process.New("xiang.helper.HexToString", 1024).Exec() assert.Nil(t, err) assert.Nil(t, res) } func TestProcessHexToStringInFlow(t *testing.T) { - testflow := path.Join(os.Getenv("YAO_DEV"), "tests", "flows", "helper") - flow.LoadFrom(testflow, "helper.") + // testflow := path.Join(os.Getenv("YAO_DEV"), "tests", "flows", "helper") + // flow.Load(testflow, "helper.") - res, err := gou.NewProcess("flows.helper.HexToString").Exec() + res, err := process.New("flows.helper.HexToString").Exec() assert.Nil(t, err) assert.Equal(t, "6162", res) // ab } func TestProcessHexToStringInScript(t *testing.T) { - runtime.Load(config.Conf) + testscirpt := path.Join(os.Getenv("YAO_DEV"), "tests", "scripts") share.LoadFrom(testscirpt) - res, err := gou.NewProcess("scripts.helper.HexToStringString").Exec() + res, err := process.New("scripts.helper.HexToStringString").Exec() assert.Nil(t, err) assert.Equal(t, "6162", res) // ab - res, err = gou.NewProcess("scripts.helper.HexToStringBytes", []byte{0x0, 0x1}).Exec() + res, err = process.New("scripts.helper.HexToStringBytes", []byte{0x0, 0x1}).Exec() assert.Nil(t, err) assert.Equal(t, "0001", res) // []byte{0x0, 0x1} } @@ -54,7 +51,7 @@ func TestProcessBufferInScript(t *testing.T) { testscirpt := path.Join(os.Getenv("YAO_DEV"), "tests", "scripts") share.LoadFrom(testscirpt) - res, err := gou.NewProcess("scripts.helper.Buffer").Exec() + res, err := process.New("scripts.helper.Buffer").Exec() assert.Nil(t, err) str, ok := res.(string) diff --git a/helper/if.go b/helper/if.go index c41a755892..fd4c1097e6 100644 --- a/helper/if.go +++ b/helper/if.go @@ -1,19 +1,21 @@ package helper -import "github.com/yaoapp/gou" +import ( + "github.com/yaoapp/gou/process" +) // IF 条件判断 func IF(param CaseParam, paramElse ...CaseParam) interface{} { if When(param.When) { - return gou.NewProcess(param.Process, param.Args...).Run() + return process.New(param.Process, param.Args...).Run() } else if len(paramElse) > 0 && When(paramElse[0].When) { - return gou.NewProcess(paramElse[0].Process, paramElse[0].Args...).Run() + return process.New(paramElse[0].Process, paramElse[0].Args...).Run() } return nil } // ProcessIF xiang.helper.IF IF条件判断 -func ProcessIF(process *gou.Process) interface{} { +func ProcessIF(process *process.Process) interface{} { process.ValidateArgNums(1) params := []CaseParam{} for _, v := range process.Args { diff --git a/helper/if_test.go b/helper/if_test.go index 2e4be48946..544d4219b7 100644 --- a/helper/if_test.go +++ b/helper/if_test.go @@ -4,12 +4,12 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" ) func TestIF(t *testing.T) { - gou.RegisterProcessHandler("xiang.unit.return", func(process *gou.Process) interface{} { + process.Register("xiang.unit.return", func(process *process.Process) interface{} { return process.Args }) @@ -38,7 +38,7 @@ func TestIF(t *testing.T) { func TestProcessIF(t *testing.T) { - gou.RegisterProcessHandler("xiang.unit.return", func(process *gou.Process) interface{} { + process.Register("xiang.unit.return", func(process *process.Process) interface{} { return process.Args }) @@ -56,7 +56,7 @@ func TestProcessIF(t *testing.T) { "args": []interface{}{"foo"}, }, } - process := gou.NewProcess("xiang.helper.IF", args...) + process := process.New("xiang.helper.IF", args...) res := process.Run().([]interface{}) assert.Equal(t, "world", res[0]) } diff --git a/helper/jwt.go b/helper/jwt.go index fb04926f06..6583cfb5be 100644 --- a/helper/jwt.go +++ b/helper/jwt.go @@ -5,7 +5,7 @@ import ( "time" "github.com/golang-jwt/jwt" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" "github.com/yaoapp/gou/session" "github.com/yaoapp/kun/any" "github.com/yaoapp/kun/exception" @@ -119,7 +119,7 @@ func JwtMake(id int, data map[string]interface{}, option map[string]interface{}, } // ProcessJwtMake xiang.helper.JwtMake 生成JWT -func ProcessJwtMake(process *gou.Process) interface{} { +func ProcessJwtMake(process *process.Process) interface{} { process.ValidateArgNums(2) id := process.ArgsInt(0) data := process.ArgsMap(1) @@ -131,7 +131,7 @@ func ProcessJwtMake(process *gou.Process) interface{} { } // ProcessJwtValidate xiang.helper.JwtValidate 校验JWT -func ProcessJwtValidate(process *gou.Process) interface{} { +func ProcessJwtValidate(process *process.Process) interface{} { process.ValidateArgNums(1) tokenString := process.ArgsString(0) return JwtValidate(tokenString) diff --git a/helper/jwt_test.go b/helper/jwt_test.go index 60d977a065..b1fdb1174b 100644 --- a/helper/jwt_test.go +++ b/helper/jwt_test.go @@ -5,7 +5,7 @@ import ( "time" "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" ) func TestJwt(t *testing.T) { @@ -26,13 +26,13 @@ func TestProcessJwt(t *testing.T) { data := map[string]interface{}{"hello": "world", "id": 1} option := map[string]interface{}{"subject": "Unit Test", "audience": "Test", "issuer": "UnitTest", "timeout": 1, "sid": ""} args := []interface{}{1, data, option} - process := gou.NewProcess("xiang.helper.JwtMake", args...) - token := process.Run().(JwtToken) + p := process.New("xiang.helper.JwtMake", args...) + token := p.Run().(JwtToken) tokenString := token.Token - res := gou.NewProcess("xiang.helper.JwtValidate", tokenString).Run().(*JwtClaims) + res := process.New("xiang.helper.JwtValidate", tokenString).Run().(*JwtClaims) assert.Equal(t, float64(1), res.Data["id"]) assert.Equal(t, "world", res.Data["hello"]) assert.Equal(t, "UnitTest", res.Issuer) time.Sleep(2 * time.Second) - assert.Panics(t, func() { gou.NewProcess("xiang.helper.JwtValidate", tokenString).Run() }) + assert.Panics(t, func() { process.New("xiang.helper.JwtValidate", tokenString).Run() }) } diff --git a/helper/map.process.go b/helper/map.process.go index a3a7be04f8..fdabc757b9 100644 --- a/helper/map.process.go +++ b/helper/map.process.go @@ -3,25 +3,25 @@ package helper import ( "fmt" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" ) // ProcessMapValues xiang.helper.MapValues 返回映射表的数值 -func ProcessMapValues(process *gou.Process) interface{} { +func ProcessMapValues(process *process.Process) interface{} { process.ValidateArgNums(1) record := process.ArgsMap(0) return MapValues(record) } // ProcessMapKeys xiang.helper.MapKeys 返回映射表的键 -func ProcessMapKeys(process *gou.Process) interface{} { +func ProcessMapKeys(process *process.Process) interface{} { process.ValidateArgNums(1) record := process.ArgsMap(0) return MapKeys(record) } // ProcessMapGet xiang.helper.MapGet 返回映射表给定键的值 -func ProcessMapGet(process *gou.Process) interface{} { +func ProcessMapGet(process *process.Process) interface{} { process.ValidateArgNums(2) record := process.ArgsMap(0) key := process.ArgsString(1) @@ -29,7 +29,7 @@ func ProcessMapGet(process *gou.Process) interface{} { } // ProcessMapSet xiang.helper.MapSet 设定键值,返回映射表给定键的值 -func ProcessMapSet(process *gou.Process) interface{} { +func ProcessMapSet(process *process.Process) interface{} { process.ValidateArgNums(3) record := process.ArgsMap(0) key := process.ArgsString(1) @@ -38,7 +38,7 @@ func ProcessMapSet(process *gou.Process) interface{} { } // ProcessMapDel xiang.helper.MapDel 删除给定键, 返回映射表 -func ProcessMapDel(process *gou.Process) interface{} { +func ProcessMapDel(process *process.Process) interface{} { process.ValidateArgNums(2) record := process.ArgsMap(0) key := process.ArgsString(1) @@ -46,7 +46,7 @@ func ProcessMapDel(process *gou.Process) interface{} { } // ProcessMapMultiDel xiang.helper.MapMultiDel 删除一组给定键, 返回映射表 -func ProcessMapMultiDel(process *gou.Process) interface{} { +func ProcessMapMultiDel(process *process.Process) interface{} { process.ValidateArgNums(2) record := process.ArgsMap(0) keys := []string{} @@ -57,7 +57,7 @@ func ProcessMapMultiDel(process *gou.Process) interface{} { } // ProcessMapToArray xiang.helper.MapToArray 映射转换为 KeyValue 数组 -func ProcessMapToArray(process *gou.Process) interface{} { +func ProcessMapToArray(process *process.Process) interface{} { process.ValidateArgNums(1) m := process.ArgsMap(0) res := []map[string]interface{}{} diff --git a/helper/map_test.go b/helper/map_test.go index c7c6d52eab..46d8fff354 100644 --- a/helper/map_test.go +++ b/helper/map_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" ) func TestProcessMapDel(t *testing.T) { @@ -12,7 +12,7 @@ func TestProcessMapDel(t *testing.T) { map[string]interface{}{"foo": "Value1", "bar": "Value2"}, "bar", } - new := gou.NewProcess("xiang.helper.MapDel", args...).Run().(map[string]interface{}) + new := process.New("xiang.helper.MapDel", args...).Run().(map[string]interface{}) _, has := new["bar"] assert.False(t, has) assert.Equal(t, "Value1", new["foo"]) @@ -24,11 +24,11 @@ func TestProcessGetSet(t *testing.T) { "bar", "Value2", } - new := gou.NewProcess("xiang.helper.MapSet", args...).Run().(map[string]interface{}) + new := process.New("xiang.helper.MapSet", args...).Run().(map[string]interface{}) assert.Equal(t, "Value1", new["foo"]) assert.Equal(t, "Value2", new["bar"]) - bar := gou.NewProcess("xiang.helper.MapGet", new, "bar").Run().(string) + bar := process.New("xiang.helper.MapGet", new, "bar").Run().(string) assert.Equal(t, "Value2", bar) } @@ -36,7 +36,7 @@ func TestProcessMapKeys(t *testing.T) { args := []interface{}{ map[string]interface{}{"foo": "Value1", "bar": "Value2"}, } - keys := gou.NewProcess("xiang.helper.MapKeys", args...).Run().([]string) + keys := process.New("xiang.helper.MapKeys", args...).Run().([]string) assert.Contains(t, keys, "foo") assert.Contains(t, keys, "bar") } @@ -45,7 +45,7 @@ func TestProcessMapValues(t *testing.T) { args := []interface{}{ map[string]interface{}{"foo": "Value1", "bar": "Value2"}, } - values := gou.NewProcess("xiang.helper.MapValues", args...).Run().([]interface{}) + values := process.New("xiang.helper.MapValues", args...).Run().([]interface{}) assert.Contains(t, values, "Value1") assert.Contains(t, values, "Value2") } @@ -56,14 +56,14 @@ func TestProcessMapMultiDel(t *testing.T) { "foo", "bar", } - new := gou.NewProcess("xiang.helper.MapMultiDel", args...).Run().(map[string]interface{}) + new := process.New("xiang.helper.MapMultiDel", args...).Run().(map[string]interface{}) assert.Nil(t, new["foo"]) assert.Nil(t, new["bar"]) } func TestProcessMapToArray(t *testing.T) { - arr := gou.NewProcess("xiang.helper.MapToArray", map[string]interface{}{ + arr := process.New("xiang.helper.MapToArray", map[string]interface{}{ "foo": "Value1", "bar": "Value2", }).Run().([]map[string]interface{}) diff --git a/helper/password.go b/helper/password.go index 1887959e97..1d5b56c537 100644 --- a/helper/password.go +++ b/helper/password.go @@ -1,7 +1,7 @@ package helper import ( - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" "github.com/yaoapp/kun/exception" "golang.org/x/crypto/bcrypt" ) @@ -17,7 +17,7 @@ func PasswordValidate(password string, passwordHash string) bool { } // ProcessPasswordValidate xiang.helper.PasswordValidate 校验密码 -func ProcessPasswordValidate(process *gou.Process) interface{} { +func ProcessPasswordValidate(process *process.Process) interface{} { process.ValidateArgNums(2) return PasswordValidate(process.ArgsString(0), process.ArgsString(1)) } diff --git a/helper/password_test.go b/helper/password_test.go index e03883a73c..b1e46e2624 100644 --- a/helper/password_test.go +++ b/helper/password_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" ) func TestPassword(t *testing.T) { @@ -18,13 +18,13 @@ func TestProcessPassword(t *testing.T) { pwd := "U123456p+" hash := "$2a$04$TS/rWBs66jADjQl8fa.w..ivkNAjH8d4sI1OPGvEB9Leed6EpzIF2" args := []interface{}{pwd, hash} - process := gou.NewProcess("xiang.helper.PasswordValidate", args...) - res := process.Run() + p := process.New("xiang.helper.PasswordValidate", args...) + res := p.Run() assert.True(t, res.(bool)) args = []interface{}{pwd, "123456"} - process = gou.NewProcess("xiang.helper.PasswordValidate", args...) + p = process.New("xiang.helper.PasswordValidate", args...) assert.Panics(t, func() { - process.Run() + p.Run() }) } diff --git a/helper/process.go b/helper/process.go index e5a2a99902..ed14310fa2 100644 --- a/helper/process.go +++ b/helper/process.go @@ -3,89 +3,89 @@ package helper import ( "time" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" "github.com/yaoapp/kun/utils" ) func init() { // 注册处理器 - gou.RegisterProcessHandler("xiang.helper.ArrayGet", ProcessArrayGet) // deprecated → utils.arr.Get @/utils/process.go - gou.RegisterProcessHandler("xiang.helper.ArrayIndexes", ProcessArrayIndexes) // deprecated → utils.arr.Indexes @/utils/process.go - gou.RegisterProcessHandler("xiang.helper.ArrayPluck", ProcessArrayPluck) // deprecated → utils.arr.Pluck @/utils/process.go - gou.RegisterProcessHandler("xiang.helper.ArraySplit", ProcessArraySplit) // deprecated → utils.arr.Split @/utils/process.go - gou.RegisterProcessHandler("xiang.helper.ArrayColumn", ProcessArrayColumn) // deprecated → utils.arr.Column @/utils/process.go - gou.RegisterProcessHandler("xiang.helper.ArrayKeep", ProcessArrayKeep) // deprecated → utils.arr.Keep @/utils/process.go - gou.RegisterProcessHandler("xiang.helper.ArrayTree", ProcessArrayTree) // deprecated → utils.arr.Tree @/utils/process.go - gou.RegisterProcessHandler("xiang.helper.ArrayUnique", ProcessArrayUnique) // deprecated → utils.arr.Unique @/utils/process.go - gou.RegisterProcessHandler("xiang.helper.ArrayMapSet", ProcessArrayMapSet) // deprecated → utils.arr.MapSet @/utils/process.go - - gou.RegisterProcessHandler("xiang.helper.MapKeys", ProcessMapKeys) // deprecated → utils.map.Keys @/utils/process.go - gou.RegisterProcessHandler("xiang.helper.MapValues", ProcessMapValues) // deprecated → utils.map.Values @/utils/process.go - gou.RegisterProcessHandler("xiang.helper.MapToArray", ProcessMapToArray) // deprecated → utils.map.Array @/utils/process.go - gou.RegisterProcessHandler("xiang.helper.MapGet", ProcessMapGet) // deprecated → utils.map.Get @/utils/process.go - gou.RegisterProcessHandler("xiang.helper.MapSet", ProcessMapSet) // deprecated → utils.map.Set @/utils/process.go - gou.RegisterProcessHandler("xiang.helper.MapDel", ProcessMapDel) // deprecated → utils.map.Del @/utils/process.go - gou.RegisterProcessHandler("xiang.helper.MapMultiDel", ProcessMapMultiDel) // deprecated → utils.map.DelMany @/utils/process.go - - gou.RegisterProcessHandler("xiang.helper.HexToString", ProcessHexToString) // deprecated - - gou.RegisterProcessHandler("xiang.helper.StrConcat", ProcessStrConcat) // deprecated → utils.str.Concat @/utils/process.go - - gou.RegisterProcessHandler("xiang.helper.Captcha", ProcessCaptcha) // deprecated → utils.captcha.Make @/utils/process.go - gou.RegisterProcessHandler("xiang.helper.CaptchaValidate", ProcessCaptchaValidate) // deprecated → utils.captcha.Verify @/utils/process.go - - gou.RegisterProcessHandler("xiang.helper.PasswordValidate", ProcessPasswordValidate) // deprecated → utils.pwd.Verify @/utils/process.go - - gou.RegisterProcessHandler("xiang.helper.JwtMake", ProcessJwtMake) // deprecated → utils.jwt.Make @/utils/process.go - gou.RegisterProcessHandler("xiang.helper.JwtValidate", ProcessJwtValidate) // deprecated → utils.jwt.Verify @/utils/process.go - - gou.RegisterProcessHandler("xiang.helper.For", ProcessFor) // deprecated → utils.flow.For @/utils/process.go - gou.AliasProcess("xiang.helper.For", "xiang.flow.For") // deprecated - gou.RegisterProcessHandler("xiang.helper.Each", ProcessEach) // deprecated → utils.flow.Each @/utils/process.go - gou.AliasProcess("xiang.helper.Each", "xiang.flow.Each") // deprecated - gou.RegisterProcessHandler("xiang.helper.Case", ProcessCase) // deprecated → utils.flow.Case @/utils/process.go - gou.AliasProcess("xiang.helper.Case", "xiang.flow.Case") // deprecated - gou.RegisterProcessHandler("xiang.helper.IF", ProcessIF) // deprecated → utils.flow.IF @/utils/process.go - gou.AliasProcess("xiang.helper.IF", "xiang.flow.IF") // deprecated - gou.RegisterProcessHandler("xiang.helper.Throw", ProcessThrow) // deprecated → utils.flow.Throw @/utils/process.go - gou.AliasProcess("xiang.helper.Throw", "xiang.flow.Throw") // deprecated - gou.RegisterProcessHandler("xiang.helper.Return", ProcessReturn) // deprecated → utils.flow.Return @/utils/process.go - gou.AliasProcess("xiang.helper.Return", "xiang.flow.Return") // deprecated - - gou.RegisterProcessHandler("xiang.helper.EnvSet", ProcessEnvSet) // deprecated → utils.env.Set @/utils/process.go - gou.AliasProcess("xiang.helper.EnvSet", "xiang.env.Set") // deprecated - gou.AliasProcess("xiang.helper.EnvSet", "yao.env.Set") // deprecated - - gou.RegisterProcessHandler("xiang.helper.EnvGet", ProcessEnvGet) // deprecated → utils.env.Get @/utils/process.go - gou.AliasProcess("xiang.helper.EnvGet", "xiang.env.Get") // deprecated - gou.AliasProcess("xiang.helper.EnvGet", "yao.env.Get") // deprecated - - gou.RegisterProcessHandler("xiang.helper.EnvMultiSet", ProcessEnvMultiSet) // deprecated → utils.env.SetMany @/utils/process.go - gou.AliasProcess("xiang.helper.EnvMultiSet", "xiang.env.MultiSet") // deprecated - gou.AliasProcess("xiang.helper.EnvMultiSet", "yao.env.MultiSet") // deprecated - - gou.RegisterProcessHandler("xiang.helper.EnvMultiGet", ProcessEnvMultiGet) // deprecated → utils.env.GetMany @/utils/process.go - gou.AliasProcess("xiang.helper.EnvMultiGet", "xiang.env.MultiGet") // deprecated - gou.AliasProcess("xiang.helper.EnvMultiGet", "yao.env.MultiGet") // deprecated - - gou.RegisterProcessHandler("xiang.helper.Print", ProcessPrint) // deprecated → utils.fmt.Println @/utils/process.go - gou.AliasProcess("xiang.helper.Print", "xiang.sys.Print") // deprecated - - gou.RegisterProcessHandler("xiang.flow.Sleep", ProcessSleep) // deprecated → utils.time.Sleep @/utils/process.go - gou.AliasProcess("xiang.flow.Sleep", "xiang.sys.Sleep") // deprecated - gou.AliasProcess("xiang.flow.Sleep", "yao.sys.Sleep") // deprecated + process.Register("xiang.helper.ArrayGet", ProcessArrayGet) // deprecated → utils.arr.Get @/utils/process.go + process.Register("xiang.helper.ArrayIndexes", ProcessArrayIndexes) // deprecated → utils.arr.Indexes @/utils/process.go + process.Register("xiang.helper.ArrayPluck", ProcessArrayPluck) // deprecated → utils.arr.Pluck @/utils/process.go + process.Register("xiang.helper.ArraySplit", ProcessArraySplit) // deprecated → utils.arr.Split @/utils/process.go + process.Register("xiang.helper.ArrayColumn", ProcessArrayColumn) // deprecated → utils.arr.Column @/utils/process.go + process.Register("xiang.helper.ArrayKeep", ProcessArrayKeep) // deprecated → utils.arr.Keep @/utils/process.go + process.Register("xiang.helper.ArrayTree", ProcessArrayTree) // deprecated → utils.arr.Tree @/utils/process.go + process.Register("xiang.helper.ArrayUnique", ProcessArrayUnique) // deprecated → utils.arr.Unique @/utils/process.go + process.Register("xiang.helper.ArrayMapSet", ProcessArrayMapSet) // deprecated → utils.arr.MapSet @/utils/process.go + + process.Register("xiang.helper.MapKeys", ProcessMapKeys) // deprecated → utils.map.Keys @/utils/process.go + process.Register("xiang.helper.MapValues", ProcessMapValues) // deprecated → utils.map.Values @/utils/process.go + process.Register("xiang.helper.MapToArray", ProcessMapToArray) // deprecated → utils.map.Array @/utils/process.go + process.Register("xiang.helper.MapGet", ProcessMapGet) // deprecated → utils.map.Get @/utils/process.go + process.Register("xiang.helper.MapSet", ProcessMapSet) // deprecated → utils.map.Set @/utils/process.go + process.Register("xiang.helper.MapDel", ProcessMapDel) // deprecated → utils.map.Del @/utils/process.go + process.Register("xiang.helper.MapMultiDel", ProcessMapMultiDel) // deprecated → utils.map.DelMany @/utils/process.go + + process.Register("xiang.helper.HexToString", ProcessHexToString) // deprecated + + process.Register("xiang.helper.StrConcat", ProcessStrConcat) // deprecated → utils.str.Concat @/utils/process.go + + process.Register("xiang.helper.Captcha", ProcessCaptcha) // deprecated → utils.captcha.Make @/utils/process.go + process.Register("xiang.helper.CaptchaValidate", ProcessCaptchaValidate) // deprecated → utils.captcha.Verify @/utils/process.go + + process.Register("xiang.helper.PasswordValidate", ProcessPasswordValidate) // deprecated → utils.pwd.Verify @/utils/process.go + + process.Register("xiang.helper.JwtMake", ProcessJwtMake) // deprecated → utils.jwt.Make @/utils/process.go + process.Register("xiang.helper.JwtValidate", ProcessJwtValidate) // deprecated → utils.jwt.Verify @/utils/process.go + + process.Register("xiang.helper.For", ProcessFor) // deprecated → utils.flow.For @/utils/process.go + process.Alias("xiang.helper.For", "xiang.flow.For") // deprecated + process.Register("xiang.helper.Each", ProcessEach) // deprecated → utils.flow.Each @/utils/process.go + process.Alias("xiang.helper.Each", "xiang.flow.Each") // deprecated + process.Register("xiang.helper.Case", ProcessCase) // deprecated → utils.flow.Case @/utils/process.go + process.Alias("xiang.helper.Case", "xiang.flow.Case") // deprecated + process.Register("xiang.helper.IF", ProcessIF) // deprecated → utils.flow.IF @/utils/process.go + process.Alias("xiang.helper.IF", "xiang.flow.IF") // deprecated + process.Register("xiang.helper.Throw", ProcessThrow) // deprecated → utils.flow.Throw @/utils/process.go + process.Alias("xiang.helper.Throw", "xiang.flow.Throw") // deprecated + process.Register("xiang.helper.Return", ProcessReturn) // deprecated → utils.flow.Return @/utils/process.go + process.Alias("xiang.helper.Return", "xiang.flow.Return") // deprecated + + process.Register("xiang.helper.EnvSet", ProcessEnvSet) // deprecated → utils.env.Set @/utils/process.go + process.Alias("xiang.helper.EnvSet", "xiang.env.Set") // deprecated + process.Alias("xiang.helper.EnvSet", "yao.env.Set") // deprecated + + process.Register("xiang.helper.EnvGet", ProcessEnvGet) // deprecated → utils.env.Get @/utils/process.go + process.Alias("xiang.helper.EnvGet", "xiang.env.Get") // deprecated + process.Alias("xiang.helper.EnvGet", "yao.env.Get") // deprecated + + process.Register("xiang.helper.EnvMultiSet", ProcessEnvMultiSet) // deprecated → utils.env.SetMany @/utils/process.go + process.Alias("xiang.helper.EnvMultiSet", "xiang.env.MultiSet") // deprecated + process.Alias("xiang.helper.EnvMultiSet", "yao.env.MultiSet") // deprecated + + process.Register("xiang.helper.EnvMultiGet", ProcessEnvMultiGet) // deprecated → utils.env.GetMany @/utils/process.go + process.Alias("xiang.helper.EnvMultiGet", "xiang.env.MultiGet") // deprecated + process.Alias("xiang.helper.EnvMultiGet", "yao.env.MultiGet") // deprecated + + process.Register("xiang.helper.Print", ProcessPrint) // deprecated → utils.fmt.Println @/utils/process.go + process.Alias("xiang.helper.Print", "xiang.sys.Print") // deprecated + + process.Register("xiang.flow.Sleep", ProcessSleep) // deprecated → utils.time.Sleep @/utils/process.go + process.Alias("xiang.flow.Sleep", "xiang.sys.Sleep") // deprecated + process.Alias("xiang.flow.Sleep", "yao.sys.Sleep") // deprecated } // ProcessPrint xiang.helper.Print 打印语句 -func ProcessPrint(process *gou.Process) interface{} { +func ProcessPrint(process *process.Process) interface{} { process.ValidateArgNums(1) utils.Dump(process.Args...) return nil } // ProcessSleep xiang.flow.Sleep 等待 -func ProcessSleep(process *gou.Process) interface{} { +func ProcessSleep(process *process.Process) interface{} { process.ValidateArgNums(1) ms := process.ArgsInt(0) time.Sleep(time.Duration((ms * int(time.Millisecond)))) diff --git a/helper/range.go b/helper/range.go index d9beda0660..cd9c63e021 100644 --- a/helper/range.go +++ b/helper/range.go @@ -5,8 +5,8 @@ import ( "regexp" jsoniter "github.com/json-iterator/go" - "github.com/yaoapp/gou" - "github.com/yaoapp/gou/query/share" + "github.com/yaoapp/gou/helper" + "github.com/yaoapp/gou/process" "github.com/yaoapp/kun/any" "github.com/yaoapp/kun/exception" ) @@ -69,14 +69,14 @@ func For(from int, to int, p Process) { "value": i, } args := bindArgs(p.Args, bindings) - gou.NewProcess(p.Process, args...).Run() + process.New(p.Process, args...).Run() } } func bindArgs(args []interface{}, bindings map[string]interface{}) []interface{} { new := []interface{}{} for i := range args { - new = append(new, share.Bind(args[i], bindings, reVar)) + new = append(new, helper.Bind(args[i], bindings, reVar)) } return new } @@ -89,7 +89,7 @@ func rangeString(v string, p Process) { "value": value, } args := bindArgs(p.Args, bindings) - gou.NewProcess(p.Process, args...).Run() + process.New(p.Process, args...).Run() } } @@ -101,7 +101,7 @@ func rangeMap(v map[string]interface{}, p Process) { "value": value, } args := bindArgs(p.Args, bindings) - gou.NewProcess(p.Process, args...).Run() + process.New(p.Process, args...).Run() } } @@ -112,7 +112,7 @@ func rangeArray(v []interface{}, p Process) { "value": value, } args := bindArgs(p.Args, bindings) - gou.NewProcess(p.Process, args...).Run() + process.New(p.Process, args...).Run() } } @@ -141,7 +141,7 @@ func ProcessOf(v map[string]interface{}) Process { } // ProcessEach xiang.helper.Each 循环过程控制 -func ProcessEach(process *gou.Process) interface{} { +func ProcessEach(process *process.Process) interface{} { process.ValidateArgNums(2) v := process.Args[0] p := ProcessOf(process.ArgsMap(1)) @@ -150,7 +150,7 @@ func ProcessEach(process *gou.Process) interface{} { } // ProcessFor xiang.helper.For 循环过程控制 -func ProcessFor(process *gou.Process) interface{} { +func ProcessFor(process *process.Process) interface{} { process.ValidateArgNums(3) from := process.ArgsInt(0) to := process.ArgsInt(1) diff --git a/helper/string.process.go b/helper/string.process.go index 2daaf37aef..bc1d760f74 100644 --- a/helper/string.process.go +++ b/helper/string.process.go @@ -3,11 +3,11 @@ package helper import ( "fmt" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" ) // ProcessStrConcat xiang.helper.StrConcat 连接字符串 -func ProcessStrConcat(process *gou.Process) interface{} { +func ProcessStrConcat(process *process.Process) interface{} { process.ValidateArgNums(2) res := "" for i := range process.Args { diff --git a/helper/string_test.go b/helper/string_test.go index 449af13051..4ae0d20b7e 100644 --- a/helper/string_test.go +++ b/helper/string_test.go @@ -4,10 +4,10 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" ) func TestProcessStrConcat(t *testing.T) { - res := gou.NewProcess("xiang.helper.StrConcat", "FOO", 20, "BAR").Run().(string) + res := process.New("xiang.helper.StrConcat", "FOO", 20, "BAR").Run().(string) assert.Equal(t, "FOO20BAR", res) } diff --git a/importer/importer.go b/importer/importer.go index bd77157bc9..bb76d111aa 100644 --- a/importer/importer.go +++ b/importer/importer.go @@ -8,8 +8,8 @@ import ( "strings" "github.com/google/uuid" - jsoniter "github.com/json-iterator/go" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/application" + "github.com/yaoapp/gou/process" "github.com/yaoapp/kun/any" "github.com/yaoapp/kun/exception" "github.com/yaoapp/kun/log" @@ -17,32 +17,30 @@ import ( "github.com/yaoapp/yao/importer/from" "github.com/yaoapp/yao/importer/xlsx" "github.com/yaoapp/yao/share" - "github.com/yaoapp/yao/xfs" ) // Importers 导入器 var Importers = map[string]*Importer{} // Load 加载导入器 -func Load(cfg config.Config) { - LoadFrom(filepath.Join(cfg.Root, "imports"), "") -} +func Load(cfg config.Config) error { + return application.App.Walk("apis", func(root, file string, isdir bool) error { + + id := share.ID(root, file) + data, err := application.App.Read(file) + if err != nil { + return err + } -// LoadFrom 从特定目录加载 -func LoadFrom(dir string, prefix string) { - if share.DirNotExists(dir) { - return - } - share.Walk(dir, ".json", func(root, filename string) { var importer Importer - name := prefix + share.SpecName(root, filename) - content := share.ReadFile(filename) - err := jsoniter.Unmarshal(content, &importer) + err = application.Parse(file, data, &importer) if err != nil { - exception.New("%s 导入配置错误. %s", 400, name, err.Error()).Ctx(filename).Throw() + return fmt.Errorf("%s 导入配置错误. %s", id, err.Error()) } - Importers[name] = &importer - }) + Importers[id] = &importer + + return err + }, config.DSLExtensions...) } // Select 选择已加载导入器 @@ -59,12 +57,13 @@ func Open(name string) from.Source { ext := strings.ToLower(strings.TrimPrefix(filepath.Ext(name), ".")) switch ext { case "xlsx": + // Refector ***** // fullpath := name - fullpath := filepath.Join(xfs.Stor.Root, name) + // fullpath := filepath.Join(xfs.Stor.Root, name) // if !strings.HasPrefix(fullpath, "/") { // fullpath = filepath.Join(xfs.Stor.Root, name) // } - return xlsx.Open(fullpath) + return xlsx.Open(name) } exception.New("暂不支持: %s 文件导入", 400, ext).Throw() return nil @@ -169,7 +168,7 @@ func (imp *Importer) DataClean(data [][]interface{}, bindings []*Binding) ([]str // DataValidate 数值校验 func DataValidate(row []interface{}, value interface{}, rule string) ([]interface{}, bool) { - process, err := gou.ProcessOf(rule, value, row) + process, err := process.Of(rule, value, row) if err != nil { log.With(log.F{"rule": rule, "row": row}).Error("DataValidate: %s", err.Error()) return row, true @@ -405,7 +404,7 @@ func (imp *Importer) Run(src from.Source, mapping *Mapping) interface{} { length := len(data) total = total + length columns, data := imp.DataClean(data, mapping.Columns) - process, err := gou.ProcessOf(imp.Process, columns, data, id, page) + process, err := process.Of(imp.Process, columns, data, id, page) if err != nil { failed = failed + length log.With(log.F{"line": line}).Error("导入失败: %s", err.Error()) @@ -444,7 +443,7 @@ func (imp *Importer) Run(src from.Source, mapping *Mapping) interface{} { } if imp.Output != "" { - res, err := gou.NewProcess(imp.Output, output).WithSID(imp.Sid).Exec() + res, err := process.New(imp.Output, output).WithSID(imp.Sid).Exec() if err != nil { log.With(log.F{"output": imp.Output}).Error(err.Error()) return output diff --git a/importer/importer_test.go b/importer/importer_test.go index 8452e7bd62..faac3084b2 100644 --- a/importer/importer_test.go +++ b/importer/importer_test.go @@ -11,7 +11,6 @@ import ( ) func TestLoad(t *testing.T) { - LoadFrom("not a path", "404.") assert.IsType(t, &Importer{}, Select("order")) } func TestFingerprintSimple(t *testing.T) { diff --git a/importer/init_test.go b/importer/init_test.go index 89b294196f..f2976cf39c 100644 --- a/importer/init_test.go +++ b/importer/init_test.go @@ -7,13 +7,11 @@ import ( "github.com/yaoapp/yao/config" "github.com/yaoapp/yao/model" "github.com/yaoapp/yao/query" - "github.com/yaoapp/yao/runtime" "github.com/yaoapp/yao/script" "github.com/yaoapp/yao/share" ) func TestMain(m *testing.M) { - runtime.Load(config.Conf) share.DBConnect(config.Conf.DB) model.Load(config.Conf) query.Load(config.Conf) diff --git a/importer/process.go b/importer/process.go index 33dfed0bae..86c24f4058 100644 --- a/importer/process.go +++ b/importer/process.go @@ -2,31 +2,31 @@ package importer import ( jsoniter "github.com/json-iterator/go" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" "github.com/yaoapp/kun/exception" ) func init() { // 注册处理器 - gou.RegisterProcessHandler("xiang.import.Run", ProcessRun) // deprecated → yao.import.Run - gou.RegisterProcessHandler("xiang.import.Data", ProcessData) // deprecated → yao.import.Data - gou.RegisterProcessHandler("xiang.import.Setting", ProcessSetting) // deprecated → yao.import.Setting - gou.RegisterProcessHandler("xiang.import.DataSetting", ProcessDataSetting) // deprecated → yao.import.DataSetting - gou.RegisterProcessHandler("xiang.import.Mapping", ProcessMapping) // deprecated → yao.import.Mapping - gou.RegisterProcessHandler("xiang.import.MappingSetting", ProcessMappingSetting) // deprecated → yao.import.MappingSetting - - gou.AliasProcess("xiang.import.Run", "yao.import.Run") - gou.AliasProcess("xiang.import.Data", "yao.import.Data") - gou.AliasProcess("xiang.import.Setting", "yao.import.Setting") - gou.AliasProcess("xiang.import.DataSetting", "yao.import.DataSetting") - gou.AliasProcess("xiang.import.Mapping", "yao.import.Mapping") - gou.AliasProcess("xiang.import.MappingSetting", "yao.import.MappingSetting") + process.Register("xiang.import.Run", ProcessRun) // deprecated → yao.import.Run + process.Register("xiang.import.Data", ProcessData) // deprecated → yao.import.Data + process.Register("xiang.import.Setting", ProcessSetting) // deprecated → yao.import.Setting + process.Register("xiang.import.DataSetting", ProcessDataSetting) // deprecated → yao.import.DataSetting + process.Register("xiang.import.Mapping", ProcessMapping) // deprecated → yao.import.Mapping + process.Register("xiang.import.MappingSetting", ProcessMappingSetting) // deprecated → yao.import.MappingSetting + + process.Alias("xiang.import.Run", "yao.import.Run") + process.Alias("xiang.import.Data", "yao.import.Data") + process.Alias("xiang.import.Setting", "yao.import.Setting") + process.Alias("xiang.import.DataSetting", "yao.import.DataSetting") + process.Alias("xiang.import.Mapping", "yao.import.Mapping") + process.Alias("xiang.import.MappingSetting", "yao.import.MappingSetting") } // ProcessRun xiang.import.Run // 导入数据 -func ProcessRun(process *gou.Process) interface{} { +func ProcessRun(process *process.Process) interface{} { process.ValidateArgNums(3) name := process.ArgsString(0) imp := Select(name).WithSid(process.Sid) @@ -39,7 +39,7 @@ func ProcessRun(process *gou.Process) interface{} { // ProcessSetting xiang.import.Setting // 导入配置选项 -func ProcessSetting(process *gou.Process) interface{} { +func ProcessSetting(process *process.Process) interface{} { process.ValidateArgNums(1) name := process.ArgsString(0) imp := Select(name).WithSid(process.Sid) @@ -53,7 +53,7 @@ func ProcessSetting(process *gou.Process) interface{} { // ProcessData xiang.import.Data // 数据预览 -func ProcessData(process *gou.Process) interface{} { +func ProcessData(process *process.Process) interface{} { process.ValidateArgNums(5) name := process.ArgsString(0) imp := Select(name).WithSid(process.Sid) @@ -71,7 +71,7 @@ func ProcessData(process *gou.Process) interface{} { // ProcessDataSetting xiang.import.DataSetting // 数据预览表格配置 -func ProcessDataSetting(process *gou.Process) interface{} { +func ProcessDataSetting(process *process.Process) interface{} { process.ValidateArgNums(1) name := process.ArgsString(0) imp := Select(name).WithSid(process.Sid) @@ -80,7 +80,7 @@ func ProcessDataSetting(process *gou.Process) interface{} { // ProcessMapping xiang.import.Mapping // 字段映射预览 -func ProcessMapping(process *gou.Process) interface{} { +func ProcessMapping(process *process.Process) interface{} { process.ValidateArgNums(2) name := process.ArgsString(0) imp := Select(name).WithSid(process.Sid) @@ -93,7 +93,7 @@ func ProcessMapping(process *gou.Process) interface{} { // ProcessMappingSetting xiang.import.MappingSetting // 字段映射表格配置 -func ProcessMappingSetting(process *gou.Process) interface{} { +func ProcessMappingSetting(process *process.Process) interface{} { process.ValidateArgNums(2) name := process.ArgsString(0) imp := Select(name).WithSid(process.Sid) diff --git a/importer/process_test.go b/importer/process_test.go index d385e034d3..318c08ef8e 100644 --- a/importer/process_test.go +++ b/importer/process_test.go @@ -5,13 +5,13 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" ) func TestProcessMapping(t *testing.T) { simple := filepath.Join("assets", "simple.xlsx") args := []interface{}{"order", simple} - response := gou.NewProcess("xiang.import.Mapping", args...).Run() + response := process.New("xiang.import.Mapping", args...).Run() _, ok := response.(*Mapping) assert.True(t, ok) } @@ -19,39 +19,39 @@ func TestProcessMapping(t *testing.T) { func TestProcessMappingSetting(t *testing.T) { simple := filepath.Join("assets", "simple.xlsx") args := []interface{}{"order", simple} - response := gou.NewProcess("xiang.import.MappingSetting", args...).Run() + response := process.New("xiang.import.MappingSetting", args...).Run() _, ok := response.(map[string]interface{}) assert.True(t, ok) } func TestProcessData(t *testing.T) { simple := filepath.Join("assets", "simple.xlsx") - mapping := gou.NewProcess("xiang.import.Mapping", "order", simple).Run() + mapping := process.New("xiang.import.Mapping", "order", simple).Run() args := []interface{}{"order", simple, 1, 2, mapping} - response := gou.NewProcess("xiang.import.Data", args...).Run() + response := process.New("xiang.import.Data", args...).Run() _, ok := response.(map[string]interface{}) assert.True(t, ok) } func TestProcessDataSetting(t *testing.T) { args := []interface{}{"order"} - response := gou.NewProcess("xiang.import.DataSetting", args...).Run() + response := process.New("xiang.import.DataSetting", args...).Run() _, ok := response.(map[string]interface{}) assert.True(t, ok) } func TestProcessSetting(t *testing.T) { args := []interface{}{"order"} - response := gou.NewProcess("xiang.import.Setting", args...).Run() + response := process.New("xiang.import.Setting", args...).Run() _, ok := response.(map[string]interface{}) assert.True(t, ok) } func TestProcessRun(t *testing.T) { simple := filepath.Join("assets", "simple.xlsx") - mapping := gou.NewProcess("xiang.import.Mapping", "order", simple).Run() + mapping := process.New("xiang.import.Mapping", "order", simple).Run() args := []interface{}{"order", simple, mapping} - response := gou.NewProcess("xiang.import.Run", args...).Run() + response := process.New("xiang.import.Run", args...).Run() _, ok := response.(map[string]int) assert.True(t, ok) } diff --git a/init_test.go b/init_test.go index 9a59584f00..b6460eb4f5 100644 --- a/init_test.go +++ b/init_test.go @@ -4,7 +4,7 @@ import ( "os" "testing" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/plugin" "github.com/yaoapp/yao/config" ) @@ -16,7 +16,7 @@ func TestMain(m *testing.M) { exitVal := m.Run() // we can do clean up code here - gou.KillPlugins() + plugin.KillAll() os.Exit(exitVal) } diff --git a/main.go b/main.go index b242196104..b59480eb0a 100644 --- a/main.go +++ b/main.go @@ -6,11 +6,8 @@ import ( _ "github.com/yaoapp/gou/encoding" _ "github.com/yaoapp/yao/crypto" _ "github.com/yaoapp/yao/helper" - _ "github.com/yaoapp/yao/network" _ "github.com/yaoapp/yao/system" - _ "github.com/yaoapp/yao/user" _ "github.com/yaoapp/yao/utils" - _ "github.com/yaoapp/yao/xfs" ) // 主程序 diff --git a/model/model.go b/model/model.go index 7088168006..4faaa683c2 100644 --- a/model/model.go +++ b/model/model.go @@ -1,54 +1,17 @@ package model import ( - "fmt" - "path/filepath" - "strings" - - "github.com/yaoapp/gou" - "github.com/yaoapp/kun/log" + "github.com/yaoapp/gou/application" + "github.com/yaoapp/gou/model" "github.com/yaoapp/yao/config" "github.com/yaoapp/yao/share" ) // Load 加载数据模型 func Load(cfg config.Config) error { - if share.BUILDIN { - return LoadBuildIn("models", "") - } - return LoadFrom(filepath.Join(cfg.Root, "models"), "") -} - -// LoadFrom 从特定目录加载 -func LoadFrom(dir string, prefix string) error { - - messages := []string{} - if share.DirNotExists(dir) { - return fmt.Errorf("%s does not exists", dir) - } - - err := share.Walk(dir, ".json", func(root, filename string) { - name := prefix + share.SpecName(root, filename) - content := share.ReadFile(filename) - _, err := gou.LoadModelReturn(string(content), name) - if err != nil { - log.With(log.F{"root": root, "file": filename}).Error(err.Error()) - messages = append(messages, err.Error()) - } - }) - - if err != nil { - messages = append(messages, err.Error()) - } - - if len(messages) > 0 { - return fmt.Errorf("[Model] %s", strings.Join(messages, ";")) - } - - return nil -} - -// LoadBuildIn 从制品中读取 -func LoadBuildIn(dir string, prefix string) error { - return nil + exts := []string{"*.mod.yao", "*.mod.json", "*.mod.jsonc"} + return application.App.Walk("apis", func(root, file string, isdir bool) error { + _, err := model.Load(file, share.ID(root, file)) + return err + }, exts...) } diff --git a/model/model_test.go b/model/model_test.go index be1a69070c..6ab87283d4 100644 --- a/model/model_test.go +++ b/model/model_test.go @@ -5,27 +5,25 @@ import ( "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/model" "github.com/yaoapp/yao/config" "github.com/yaoapp/yao/share" ) func TestLoad(t *testing.T) { share.DBConnect(config.Conf.DB) - gou.Models = make(map[string]*gou.Model) Load(config.Conf) - LoadFrom("not a path", "404.") check(t) } func check(t *testing.T) { keys := []string{} - for key := range gou.Models { + for key := range model.Models { keys = append(keys, key) } assert.Equal(t, 11, len(keys)) - demo := gou.Select("demo") + demo := model.Select("demo") assert.Equal(t, demo.MetaData.Name, "::Demo") assert.Equal(t, demo.Columns["action"].Label, "::Action") } diff --git a/network/ip.go b/network/ip.go deleted file mode 100644 index 80f1fc55be..0000000000 --- a/network/ip.go +++ /dev/null @@ -1,63 +0,0 @@ -package network - -import ( - "net" - - "github.com/yaoapp/gou" - "github.com/yaoapp/kun/exception" -) - -// IP 读取IP地址 -func IP() map[string]string { - res := map[string]string{} - ifaces, err := net.Interfaces() - if err != nil { - exception.New("读取网卡失败 %s", 500, err.Error()).Throw() - } - for _, i := range ifaces { - addrs, err := i.Addrs() - if err != nil { - exception.New("读取IP地址失败 %s", 500, err.Error()).Throw() - } - // handle err - for _, addr := range addrs { - var ip net.IP - switch v := addr.(type) { - case *net.IPNet: - ip = v.IP - case *net.IPAddr: - ip = v.IP - } - res[i.Name] = ip.String() - } - } - return res -} - -// ProcessIP xiang.network.IP IP地址 -func ProcessIP(process *gou.Process) interface{} { - return IP() -} - -// FreePort xiang.network.FreePort 获取可用端口 -func FreePort() int { - addr, err := net.ResolveTCPAddr("tcp", ":0") - if err != nil { - exception.New("获取可用端口失败 %s", 500, err.Error()).Throw() - return 0 - } - - l, err := net.ListenTCP("tcp", addr) - if err != nil { - exception.New("获取可用端口失败 %s", 500, err.Error()).Throw() - return 0 - } - - defer l.Close() - return l.Addr().(*net.TCPAddr).Port -} - -// ProcessFreePort xiang.network.FreePort 获取可用端口 -func ProcessFreePort(process *gou.Process) interface{} { - return FreePort() -} diff --git a/network/ip_test.go b/network/ip_test.go deleted file mode 100644 index 67c9e5096a..0000000000 --- a/network/ip_test.go +++ /dev/null @@ -1,32 +0,0 @@ -package network - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" -) - -func TestIP(t *testing.T) { - resp := IP() - assert.True(t, len(resp) > 0) -} - -func TestProcessIP(t *testing.T) { - res := gou.NewProcess("xiang.network.ip").Run() - resp, ok := res.(map[string]string) - assert.True(t, ok) - assert.True(t, len(resp) > 0) -} - -func TestFreePort(t *testing.T) { - port := FreePort() - assert.True(t, port > 0) -} - -func TestProcessFreePort(t *testing.T) { - res := gou.NewProcess("xiang.network.FreePort").Run() - port, ok := res.(int) - assert.True(t, ok) - assert.True(t, port > 0) -} diff --git a/network/process.go b/network/process.go deleted file mode 100644 index 376a5b8eee..0000000000 --- a/network/process.go +++ /dev/null @@ -1,19 +0,0 @@ -package network - -// ******************************************************* -// * DEPRECATED → http * -// ******************************************************* - -import "github.com/yaoapp/gou" - -func init() { - // 注册处理器 - gou.RegisterProcessHandler("xiang.network.ip", ProcessIP) - gou.RegisterProcessHandler("xiang.network.FreePort", ProcessFreePort) - gou.RegisterProcessHandler("xiang.network.Get", ProcessGet) - gou.RegisterProcessHandler("xiang.network.Post", ProcessPost) - gou.RegisterProcessHandler("xiang.network.PostJSON", ProcessPostJSON) - gou.RegisterProcessHandler("xiang.network.Put", ProcessPut) - gou.RegisterProcessHandler("xiang.network.PutJSON", ProcessPutJSON) - gou.RegisterProcessHandler("xiang.network.Send", ProcessSend) -} diff --git a/network/request.go b/network/request.go deleted file mode 100644 index de0f1c8014..0000000000 --- a/network/request.go +++ /dev/null @@ -1,168 +0,0 @@ -package network - -// ******************************************************* -// * DEPRECATED → http * -// ******************************************************* - -import ( - "bytes" - "crypto/tls" - "fmt" - "io/ioutil" - "net/http" - "strings" - - jsoniter "github.com/json-iterator/go" - "github.com/yaoapp/gou/dns" -) - -// Response 请求响应结果 -type Response struct { - Status int `json:"status"` - Body string `json:"body"` - Data interface{} `json:"data"` - Headers map[string]interface{} `json:"headers"` -} - -// RequestGet 发送GET请求 -func RequestGet(url string, params map[string]interface{}, headers map[string]string) Response { - return RequestSend("GET", url, params, nil, headers) -} - -// RequestPost 发送POST请求 -func RequestPost(url string, data interface{}, headers map[string]string) Response { - return RequestSend("POST", url, map[string]interface{}{}, data, headers) -} - -// RequestPostJSON 发送POST请求 -func RequestPostJSON(url string, data interface{}, headers map[string]string) Response { - if headers == nil { - headers = map[string]string{} - } - headers["content-type"] = "application/json;charset=utf8" - return RequestSend("POST", url, map[string]interface{}{}, data, headers) -} - -// RequestPut 发送PUT请求 -func RequestPut(url string, data interface{}, headers map[string]string) Response { - return RequestSend("PUT", url, map[string]interface{}{}, data, headers) -} - -// RequestPutJSON 发送PUT请求 -func RequestPutJSON(url string, data interface{}, headers map[string]string) Response { - if headers == nil { - headers = map[string]string{} - } - headers["content-type"] = "application/json;charset=utf8" - return RequestSend("PUT", url, map[string]interface{}{}, data, headers) -} - -// RequestSend 发送Request请求 -func RequestSend(method string, url string, params map[string]interface{}, data interface{}, headers map[string]string) Response { - - var body []byte - var err error - if data != nil { - if strings.HasPrefix(strings.ToLower(headers["content-type"]), "application/json") { - body, err = jsoniter.Marshal(data) - if err != nil { - return Response{ - Status: 500, - Body: err.Error(), - Data: map[string]interface{}{"code": 500, "message": err.Error()}, - Headers: map[string]interface{}{ - "Content-Type": "application/json;charset=utf8", - }, - } - } - } else { - body = []byte(fmt.Sprintf("%v", data)) - } - } - - req, err := http.NewRequest(method, url, bytes.NewBuffer(body)) - if err != nil { - return Response{ - Status: 500, - Body: err.Error(), - Data: map[string]interface{}{"code": 500, "message": err.Error()}, - Headers: map[string]interface{}{ - "Content-Type": "application/json;charset=utf8", - }, - } - } - - // Request Header - if headers != nil { - for name, header := range headers { - req.Header.Set(name, header) - } - } - - // Force using system DSN resolver - // var dialer = &net.Dialer{Resolver: &net.Resolver{PreferGo: false}} - var dialContext = dns.DialContext() - var tr = &http.Transport{DialContext: dialContext} - var client *http.Client = &http.Client{Transport: tr} - - // Https SkipVerify false - if strings.HasPrefix(url, "https://") { - tr = &http.Transport{ - TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, - DialContext: dialContext, - } - client = &http.Client{Transport: tr} - } - defer tr.CloseIdleConnections() - - resp, err := client.Do(req) - if err != nil { - return Response{ - Status: 0, - Body: err.Error(), - Data: map[string]interface{}{"code": 500, "message": err.Error()}, - Headers: map[string]interface{}{ - "Content-Type": "application/json;charset=utf8", - }, - } - } - defer resp.Body.Close() - - body, err = ioutil.ReadAll(resp.Body) // response body is []byte - if err != nil { - return Response{ - Status: 500, - Body: err.Error(), - Data: map[string]interface{}{"code": resp.StatusCode, "message": err.Error()}, - Headers: map[string]interface{}{ - "Content-Type": "application/json;charset=utf8", - }, - } - } - - // JSON 解析 - var res interface{} - if strings.HasPrefix(resp.Header.Get("Content-Type"), "application/json") { - err = jsoniter.Unmarshal(body, &res) - if err != nil { - return Response{ - Status: 500, - Body: err.Error(), - Data: map[string]interface{}{"code": resp.StatusCode, "message": err.Error()}, - Headers: map[string]interface{}{ - "Content-Type": "application/json;charset=utf8", - }, - } - } - } - respHeaders := map[string]interface{}{} - for name := range resp.Header { - respHeaders[name] = resp.Header.Get(name) - } - return Response{ - Status: resp.StatusCode, - Body: string(body), - Data: res, - Headers: respHeaders, - } -} diff --git a/network/request.process.go b/network/request.process.go deleted file mode 100644 index 0b28591f5f..0000000000 --- a/network/request.process.go +++ /dev/null @@ -1,127 +0,0 @@ -package network - -import ( - "fmt" - - "github.com/yaoapp/gou" -) - -// ******************************************************* -// * DEPRECATED → http * -// ******************************************************* - -// ProcessPost xiang.helper.Post HTTP Post -func ProcessPost(process *gou.Process) interface{} { - process.ValidateArgNums(1) - var data interface{} - var headers = map[string]string{} - url := process.ArgsString(0) - if process.NumOfArgs() > 1 { - data = process.Args[1] - } - if process.NumOfArgs() > 2 { - inputHeaders := process.ArgsMap(2) - for name, value := range inputHeaders { - headers[name] = fmt.Sprintf("%v", value) - } - } - return RequestPost(url, data, headers) -} - -// ProcessPostJSON xiang.helper.PostJSON HTTP Post -func ProcessPostJSON(process *gou.Process) interface{} { - process.ValidateArgNums(1) - var data interface{} - var headers = map[string]string{} - url := process.ArgsString(0) - if process.NumOfArgs() > 1 { - data = process.Args[1] - } - if process.NumOfArgs() > 2 { - inputHeaders := process.ArgsMap(2) - for name, value := range inputHeaders { - headers[name] = fmt.Sprintf("%v", value) - } - } - return RequestPostJSON(url, data, headers) -} - -// ProcessPut xiang.helper.Put HTTP PUT -func ProcessPut(process *gou.Process) interface{} { - process.ValidateArgNums(1) - var data interface{} - var headers = map[string]string{} - url := process.ArgsString(0) - if process.NumOfArgs() > 1 { - data = process.Args[1] - } - if process.NumOfArgs() > 2 { - inputHeaders := process.ArgsMap(2) - for name, value := range inputHeaders { - headers[name] = fmt.Sprintf("%v", value) - } - } - return RequestPut(url, data, headers) -} - -// ProcessPutJSON xiang.helper.PutJSON HTTP PUT -func ProcessPutJSON(process *gou.Process) interface{} { - process.ValidateArgNums(1) - var data interface{} - var headers = map[string]string{} - url := process.ArgsString(0) - if process.NumOfArgs() > 1 { - data = process.Args[1] - } - if process.NumOfArgs() > 2 { - inputHeaders := process.ArgsMap(2) - for name, value := range inputHeaders { - headers[name] = fmt.Sprintf("%v", value) - } - } - return RequestPutJSON(url, data, headers) -} - -// ProcessSend xiang.helper.Send HTTP Send -func ProcessSend(process *gou.Process) interface{} { - process.ValidateArgNums(2) - var data interface{} - var params = map[string]interface{}{} - var headers = map[string]string{} - method := process.ArgsString(0) - url := process.ArgsString(1) - if process.NumOfArgs() > 2 { - params = process.ArgsMap(2) - } - - if process.NumOfArgs() > 3 { - data = process.Args[3] - } - - if process.NumOfArgs() > 4 { - inputHeaders := process.ArgsMap(4) - for name, value := range inputHeaders { - headers[name] = fmt.Sprintf("%v", value) - } - } - return RequestSend(method, url, params, data, headers) -} - -// ProcessGet xiang.helper.Get HTTP Get -func ProcessGet(process *gou.Process) interface{} { - process.ValidateArgNums(1) - var params = map[string]interface{}{} - var headers = map[string]string{} - url := process.ArgsString(0) - if process.NumOfArgs() > 1 { - params = process.ArgsMap(1) - } - if process.NumOfArgs() > 2 { - inputHeaders := process.ArgsMap(2) - for name, value := range inputHeaders { - headers[name] = fmt.Sprintf("%v", value) - } - } - - return RequestGet(url, params, headers) -} diff --git a/network/request_test.go b/network/request_test.go deleted file mode 100644 index 9e0d3ab6c4..0000000000 --- a/network/request_test.go +++ /dev/null @@ -1,66 +0,0 @@ -package network - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" - "github.com/yaoapp/kun/any" -) - -func TestRequestGetHtml(t *testing.T) { - resp := RequestGet("https://api.github.com/zen", nil, nil) - assert.Equal(t, 200, resp.Status) - assert.Equal(t, nil, resp.Data) -} - -func TestRequestGetJSON(t *testing.T) { - resp := RequestGet("https://api.github.com/users/yaoapp", nil, nil) - assert.Equal(t, 200, resp.Status) - data := any.Of(resp.Data).MapStr().Dot() - assert.Equal(t, "https://github.com/YaoApp", data.Get("html_url")) -} - -func TestRequestPost(t *testing.T) { - resp := RequestPost("https://api.github.com/zen", map[string]interface{}{"foo": "bar"}, nil) - assert.Equal(t, 404, resp.Status) -} - -func TestRequestPostJSON(t *testing.T) { - resp := RequestPostJSON("https://api.github.com/zen", map[string]interface{}{"foo": "bar"}, nil) - assert.Equal(t, 404, resp.Status) -} - -func TestRequestProcessGet(t *testing.T) { - args := []interface{}{"https://api.github.com/zen"} - res := gou.NewProcess("xiang.network.Get", args...).Run() - resp, ok := res.(Response) - assert.True(t, ok) - assert.Equal(t, 200, resp.Status) - assert.Equal(t, nil, resp.Data) -} - -func TestRequestProcessPost(t *testing.T) { - args := []interface{}{"https://api.github.com/zen", map[string]interface{}{"foo": "bar"}, nil} - res := gou.NewProcess("xiang.network.Post", args...).Run() - resp, ok := res.(Response) - assert.True(t, ok) - assert.Equal(t, 404, resp.Status) -} - -func TestRequestProcessPostJSON(t *testing.T) { - args := []interface{}{"https://api.github.com/zen", map[string]interface{}{"foo": "bar"}, nil} - res := gou.NewProcess("xiang.network.PostJSON", args...).Run() - resp, ok := res.(Response) - assert.True(t, ok) - assert.Equal(t, 404, resp.Status) -} - -func TestRequestProcessSend(t *testing.T) { - args := []interface{}{"GET", "https://api.github.com/zen"} - res := gou.NewProcess("xiang.network.Send", args...).Run() - resp, ok := res.(Response) - assert.True(t, ok) - assert.Equal(t, 200, resp.Status) - assert.Equal(t, nil, resp.Data) -} diff --git a/page/REAME.md b/page/REAME.md deleted file mode 100644 index 82e08d541b..0000000000 --- a/page/REAME.md +++ /dev/null @@ -1 +0,0 @@ -# 数据页面 diff --git a/page/api.go b/page/api.go deleted file mode 100644 index 3f9c07dc93..0000000000 --- a/page/api.go +++ /dev/null @@ -1,60 +0,0 @@ -package page - -import ( - "github.com/yaoapp/yao/share" -) - -// SetupAPIs 设定API数据 -func (page *Page) SetupAPIs() { - - defaults := map[string]share.API{ - "data": apiDataDefault(), - "setting": apiSettingDefault(), - } - - // 开发者填写的规则 - for name := range page.APIs { - if _, has := defaults[name]; !has { - delete(page.APIs, name) - continue - } - - api := defaults[name] - api.Name = name - if page.APIs[name].Process != "" { - api.Process = page.APIs[name].Process - } - - if page.APIs[name].Guard != "" { - api.Guard = page.APIs[name].Guard - } - - if page.APIs[name].Default != nil { - api.Default = page.APIs[name].Default - } - - defaults[name] = api - } - - page.APIs = defaults -} - -// apiSearchDefault data 接口默认值 -func apiDataDefault() share.API { - param := map[string]interface{}{} - return share.API{ - Name: "data", - Guard: "bearer-jwt", - Process: "xiang.page.data", - Default: []interface{}{param}, - } -} - -// apiSettingDefault setting 接口默认值 -func apiSettingDefault() share.API { - return share.API{ - Name: "setting", - Guard: "bearer-jwt", - Process: "xiang.page.setting", - } -} diff --git a/page/lang.go b/page/lang.go deleted file mode 100644 index 9342eabeb5..0000000000 --- a/page/lang.go +++ /dev/null @@ -1,125 +0,0 @@ -package page - -// Lang for applying a language pack -func (page *Page) Lang(trans func(widget string, inst string, value *string) bool) { - inst := page.Flow.Name - widget := "page" - - trans(widget, inst, &page.Name) - trans(widget, inst, &page.Label) - trans(widget, inst, &page.Description) - trans(widget, inst, &page.Page.Primary) - transMap(widget, inst, page.Page.Layout, trans) - page.Output = transAny(widget, inst, page.Output, trans) - - // Filters - for name, filter := range page.Filters { - new := name - trans(widget, inst, &new) - trans(widget, inst, &filter.Label) - delete(page.Filters, name) - - // Props - transMap(widget, inst, filter.Input.Props, trans) - page.Filters[new] = filter - } - -} - -func transAny(widget string, inst string, input interface{}, trans func(widget string, inst string, value *string) bool) interface{} { - switch input.(type) { - case []interface{}: - values := input.([]interface{}) - transArr(widget, inst, values, trans) - input = values - break - - case map[string]interface{}: - values := input.(map[string]interface{}) - for name, value := range values { - new := name - newValue := value - - switch value.(type) { - case string: - val := value.(string) - trans(widget, inst, &val) - newValue = val - break - - case []interface{}: - vals := value.([]interface{}) - transArr(widget, inst, vals, trans) - newValue = vals - break - - case map[string]interface{}: - vals := value.(map[string]interface{}) - transMap(widget, inst, vals, trans) - newValue = vals - break - } - - trans(widget, inst, &new) - delete(values, name) - values[new] = newValue - } - input = values - break - } - - return input -} - -func transMap(widget string, inst string, values map[string]interface{}, trans func(widget string, inst string, value *string) bool) { - for key, value := range values { - - switch value.(type) { - - case string: - v := value.(string) - trans(widget, inst, &v) - values[key] = v - break - - case []interface{}: - v := value.([]interface{}) - transArr(widget, inst, v, trans) - values[key] = v - break - - case map[string]interface{}: - v := value.(map[string]interface{}) - transMap(widget, inst, v, trans) - values[key] = v - break - } - - } -} - -func transArr(widget string, inst string, values []interface{}, trans func(widget string, inst string, value *string) bool) { - for key, value := range values { - switch value.(type) { - - case string: - v := value.(string) - trans(widget, inst, &v) - values[key] = v - break - - case []interface{}: - v := value.([]interface{}) - transArr(widget, inst, v, trans) - values[key] = v - break - - case map[string]interface{}: - v := value.(map[string]interface{}) - transMap(widget, inst, v, trans) - values[key] = v - break - } - - } -} diff --git a/page/page.go b/page/page.go deleted file mode 100644 index 98bbfe1571..0000000000 --- a/page/page.go +++ /dev/null @@ -1,121 +0,0 @@ -package page - -import ( - "fmt" - "path" - - jsoniter "github.com/json-iterator/go" - "github.com/yaoapp/gou" - "github.com/yaoapp/gou/lang" - "github.com/yaoapp/kun/exception" - "github.com/yaoapp/kun/log" - "github.com/yaoapp/yao/config" - "github.com/yaoapp/yao/share" -) - -// Pages 已载入页面 -var Pages = map[string]*Page{} - -// Load 加载页面 -func Load(cfg config.Config) error { - - if share.BUILDIN { - return LoadBuildIn("pages", "") - } - - var errs error = nil - if err := LoadFrom(path.Join(cfg.Root, "/kanban"), ""); err != nil { - // log.Trace("load kanban error: %s ", err.Error()) - errs = err - } - if err := LoadFrom(path.Join(cfg.Root, "/screen"), ""); err != nil { - // log.Trace("load screen error: %s", err.Error()) - errs = err - } - if err := LoadFrom(path.Join(cfg.Root, "/pages"), ""); err != nil { - // log.Trace("load screen error: %s", err.Error()) - errs = err - } - - return errs -} - -// LoadBuildIn 从制品中读取 -func LoadBuildIn(dir string, prefix string) error { - return nil -} - -// LoadFrom 从特定目录加载 -func LoadFrom(dir string, prefix string) error { - - if share.DirNotExists(dir) { - return fmt.Errorf("%s does not exists", dir) - } - - err := share.Walk(dir, ".json", func(root, filename string) { - name := prefix + share.SpecName(root, filename) - content := share.ReadFile(filename) - _, err := LoadPage(content, name) - if err != nil { - log.With(log.F{"root": root, "file": filename}).Error(err.Error()) - } - }) - if err != nil { - return err - } - - // Load Script - err = share.Walk(dir, ".js", func(root, filename string) { - name := prefix + share.SpecName(root, filename) - page := Select(name) - if page != nil { - script := share.ScriptName(filename) - content := share.ReadFile(filename) - page.LoadScript(string(content), script) - } - }) - - return err - -} - -// LoadPage 载入页面 -func LoadPage(source []byte, name string) (*Page, error) { - page := &Page{ - Flow: gou.Flow{ - Name: name, - }, - } - err := jsoniter.Unmarshal(source, page) - if err != nil { - log.With(log.F{"name": name, "source": source}).Error(err.Error()) - return nil, err - } - page.Prepare() - page.SetupAPIs() - Pages[name] = page - - // Apply a language pack - if lang.Default != nil { - lang.Default.Apply(Pages[name]) - } - - return page, nil -} - -// Select 读取已加载页面 -func Select(name string) *Page { - page, has := Pages[name] - if !has { - exception.New( - fmt.Sprintf("Page:%s; 尚未加载", name), - 400, - ).Throw() - } - return page -} - -// GetData 运行 flow 返回数值 -func (page Page) GetData(params map[string]interface{}) interface{} { - return page.Flow.Exec(params) -} diff --git a/page/page_test.go b/page/page_test.go deleted file mode 100644 index 7446d8492e..0000000000 --- a/page/page_test.go +++ /dev/null @@ -1,44 +0,0 @@ -package page - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/yaoapp/yao/config" - "github.com/yaoapp/yao/i18n" - "github.com/yaoapp/yao/model" - "github.com/yaoapp/yao/query" - "github.com/yaoapp/yao/share" -) - -func TestLoad(t *testing.T) { - - share.DBConnect(config.Conf.DB) - model.Load(config.Conf) - query.Load(config.Conf) - - Load(config.Conf) - LoadFrom("not a path", "404.") - check(t) -} - -func check(t *testing.T) { - keys := []string{} - for key := range Pages { - keys = append(keys, key) - } - assert.Equal(t, 2, len(keys)) - _, err := i18n.Trans("zh-hk", []string{"chart.lang"}, Pages["lang"]) - if err != nil { - t.Fatal(err) - } - // lang := Pages["lang"] - // output := lang.Output.(map[string]interface{}) - // assert.Equal(t, "{{$in}}", output["參數"]) - - // filters := lang.Page.Layout["filters"].([]interface{}) - // begin := filters[0].(map[string]interface{}) - // assert.Equal(t, "開始時間", begin["name"]) - - // assert.Equal(t, "請選擇開始時間", lang.Filters["開始時間"].Input.Props["placeholder"]) -} diff --git a/page/process.go b/page/process.go deleted file mode 100644 index 21eb2e8e88..0000000000 --- a/page/process.go +++ /dev/null @@ -1,79 +0,0 @@ -package page - -import ( - "strings" - - "github.com/yaoapp/gou" - "github.com/yaoapp/kun/maps" -) - -// 注册处理器 -func init() { - gou.RegisterProcessHandler("xiang.page.data", ProcessData) - gou.RegisterProcessHandler("xiang.page.setting", ProcessSetting) -} - -// ProcessData xiang.page.data -// 查询数据分析页面中定义的数据 -func ProcessData(process *gou.Process) interface{} { - - process.ValidateArgNums(2) - name := process.ArgsString(0) - params := process.ArgsMap(1) - page := Select(name) - api := page.APIs["data"] - - if len(api.Default) > 0 { - if defaults, ok := api.Default[0].(map[string]interface{}); ok { - for key, value := range defaults { - if !params.Has(key) { - params.Set(key, value) - } - } - } - } - - // with Session - page.Flow.WithGlobal(process.Global) - page.Flow.WithSID(process.Sid) - - return page.GetData(params) -} - -// ProcessSetting xiang.page.setting -// 查询数据分析页面中定义的数据 -func ProcessSetting(process *gou.Process) interface{} { - - process.ValidateArgNums(2) - name := process.ArgsString(0) - field := process.ArgsString(1) - page := Select(name) - - fields := strings.Split(field, ",") - setting := maps.Map{ - "name": page.Name, - "label": page.Label, - "version": page.Version, - "description": page.Description, - "filters": page.Filters, - "page": page.Page, - } - - if len(fields) == 1 && setting.Has(fields[0]) { - field := strings.TrimSpace(fields[0]) - return setting.Get(field) - } - - if len(fields) > 1 { - res := maps.Map{} - for _, field := range fields { - field = strings.TrimSpace(field) - if setting.Has(field) { - res.Set(field, setting.Get(field)) - } - } - return res - } - return setting - -} diff --git a/page/process_test.go b/page/process_test.go deleted file mode 100644 index 0fb7664868..0000000000 --- a/page/process_test.go +++ /dev/null @@ -1,76 +0,0 @@ -package page - -import ( - "net/url" - "testing" - - "github.com/gin-gonic/gin" - "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" - "github.com/yaoapp/kun/any" - "github.com/yaoapp/yao/config" - _ "github.com/yaoapp/yao/helper" - "github.com/yaoapp/yao/model" - "github.com/yaoapp/yao/query" - "github.com/yaoapp/yao/runtime" - "github.com/yaoapp/yao/share" -) - -func init() { - runtime.Load(config.Conf) - share.DBConnect(config.Conf.DB) - model.Load(config.Conf) - query.Load(config.Conf) - Load(config.Conf) -} -func TestProcessSetting(t *testing.T) { - - args := []interface{}{ - "service.compare", - nil, - &gin.Context{}, - } - process := gou.NewProcess("xiang.page.Setting", args...) - response := ProcessSetting(process) - assert.NotNil(t, response) - res := any.Of(response).Map() - assert.True(t, res.Has("name")) - assert.True(t, res.Has("label")) - assert.True(t, res.Has("description")) - assert.True(t, res.Has("page")) - assert.True(t, res.Has("version")) - - args = []interface{}{ - "service.compare", - "page,name", - &gin.Context{}, - } - process = gou.NewProcess("xiang.page.Setting", args...) - response = ProcessSetting(process) - assert.NotNil(t, response) - - res = any.Of(response).Map() - assert.True(t, res.Has("name")) - assert.True(t, res.Has("page")) - assert.False(t, res.Has("label")) -} - -func TestProcessData(t *testing.T) { - - params := url.Values{ - "from": []string{"1981-01-01", "1990-01-01"}, - } - params.Set("to", "2049-12-31") - - args := []interface{}{ - "service.compare", - params, - &gin.Context{}, - } - process := gou.NewProcess("xiang.page.Data", args...) - response := ProcessData(process) - assert.NotNil(t, response) - - res := any.Of(response).Map().Dot() - assert.Equal(t, "北京", res.Get("合并.0.城市")) -} diff --git a/page/types.go b/page/types.go deleted file mode 100644 index 327c9f3903..0000000000 --- a/page/types.go +++ /dev/null @@ -1,14 +0,0 @@ -package page - -import ( - "github.com/yaoapp/gou" - "github.com/yaoapp/yao/share" -) - -// Page 页面格式 -type Page struct { - gou.Flow - APIs map[string]share.API `json:"apis,omitempty"` - Filters map[string]share.Filter `json:"filters,omitempty"` - Page share.Page `json:"page,omitempty"` -} diff --git a/plugin/plugin.go b/plugin/plugin.go index fa254b35b0..628a9fea8f 100644 --- a/plugin/plugin.go +++ b/plugin/plugin.go @@ -1,33 +1,17 @@ package plugin import ( - "fmt" - "path/filepath" - - "github.com/yaoapp/gou" - "github.com/yaoapp/kun/log" + "github.com/yaoapp/gou/application" + "github.com/yaoapp/gou/plugin" "github.com/yaoapp/yao/config" "github.com/yaoapp/yao/share" ) // Load 加载业务插件 func Load(cfg config.Config) error { - return LoadFrom(filepath.Join(cfg.Root, "plugins")) -} - -// LoadFrom 从特定目录加载 -func LoadFrom(dir string) error { - - if share.DirNotExists(dir) { - return fmt.Errorf("%s does not exists", dir) - } - - err := share.Walk(dir, ".so", func(root, filename string) { - name := share.SpecName(root, filename) - _, err := gou.LoadPluginReturn(filename, name) - if err != nil { - log.With(log.F{"root": root, "file": filename}).Error(err.Error()) - } - }) - return err + exts := []string{"*.so"} + return application.App.Walk("apis", func(root, file string, isdir bool) error { + _, err := plugin.Load(file, share.ID(root, file)) + return err + }, exts...) } diff --git a/plugin/plugin_test.go b/plugin/plugin_test.go index 69964a916d..a02d8123ea 100644 --- a/plugin/plugin_test.go +++ b/plugin/plugin_test.go @@ -5,20 +5,18 @@ import ( "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/plugin" "github.com/yaoapp/yao/config" ) func TestLoad(t *testing.T) { - gou.Plugins = make(map[string]*gou.Plugin) Load(config.Conf) - LoadFrom("404") check(t) } func check(t *testing.T) { keys := []string{} - for key := range gou.Plugins { + for key := range plugin.Plugins { keys = append(keys, key) } assert.Equal(t, 1, len(keys)) diff --git a/query/query.go b/query/query.go index 9039532ccb..3a27df5f00 100644 --- a/query/query.go +++ b/query/query.go @@ -1,7 +1,7 @@ package query import ( - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/model" "github.com/yaoapp/gou/query" dsl "github.com/yaoapp/gou/query/gou" "github.com/yaoapp/kun/log" @@ -19,7 +19,7 @@ func DefaultQuery() { query.Register("default", &dsl.Query{ Query: capsule.Query(), GetTableName: func(s string) string { - if mod, has := gou.Models[s]; has { + if mod, has := model.Models[s]; has { return mod.MetaData.Table.Name } log.Error("%s model does not load", s) diff --git a/runtime/runtime.go b/runtime/runtime.go index 1038f8d174..6ef3a9fa2d 100644 --- a/runtime/runtime.go +++ b/runtime/runtime.go @@ -1,18 +1,11 @@ package runtime -import ( - "github.com/yaoapp/gou" - "github.com/yaoapp/gou/runtime" - "github.com/yaoapp/yao/config" - "github.com/yaoapp/yao/fs" -) - -// Load runtime -func Load(cfg config.Config) error { - dataRoot, err := fs.Root(cfg) - if err != nil { - return err - } - gou.LoadRuntime(runtime.Option{FileRoot: dataRoot}) - return nil -} +// // Load runtime +// func Load(cfg config.Config) error { +// dataRoot, err := fs.Root(cfg) +// if err != nil { +// return err +// } +// gou.LoadRuntime(runtime.Option{FileRoot: dataRoot}) +// return nil +// } diff --git a/schedule/schedule.go b/schedule/schedule.go index 70fe869e55..91a55861eb 100644 --- a/schedule/schedule.go +++ b/schedule/schedule.go @@ -1,36 +1,17 @@ package schedule import ( - "fmt" - "path/filepath" - - "github.com/yaoapp/gou" - "github.com/yaoapp/kun/log" + "github.com/yaoapp/gou/application" + "github.com/yaoapp/gou/schedule" "github.com/yaoapp/yao/config" "github.com/yaoapp/yao/share" ) // Load load schedule func Load(cfg config.Config) error { - var root = filepath.Join(cfg.Root, "schedules") - return LoadFrom(root, "") -} - -// LoadFrom load from dir -func LoadFrom(dir string, prefix string) error { - - if share.DirNotExists(dir) { - return fmt.Errorf("%s does not exists", dir) - } - - err := share.Walk(dir, ".json", func(root, filename string) { - name := prefix + share.SpecName(root, filename) - content := share.ReadFile(filename) - _, err := gou.LoadSchedule(string(content), name) - if err != nil { - log.With(log.F{"root": root, "file": filename}).Error(err.Error()) - } - }) - - return err + exts := []string{"*.sch.yao", "*.sch.json", "*.sch.jsonc"} + return application.App.Walk("schedules", func(root, file string, isdir bool) error { + _, err := schedule.Load(file, share.ID(root, file)) + return err + }, exts...) } diff --git a/schedule/schedule_test.go b/schedule/schedule_test.go index d0f27e3eb8..bd29dcfde5 100644 --- a/schedule/schedule_test.go +++ b/schedule/schedule_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/schedule" "github.com/yaoapp/yao/config" "github.com/yaoapp/yao/task" ) @@ -12,10 +12,9 @@ import ( func TestLoad(t *testing.T) { task.Load(config.Conf) Load(config.Conf) - LoadFrom("not a path", "404.") check(t) } func check(t *testing.T) { - assert.Equal(t, 2, len(gou.Schedules)) + assert.Equal(t, 2, len(schedule.Schedules)) } diff --git a/script/script.go b/script/script.go index f2547bd8c8..686d7f4f72 100644 --- a/script/script.go +++ b/script/script.go @@ -1,49 +1,43 @@ package script import ( - "fmt" - "path/filepath" - - "github.com/yaoapp/gou" - "github.com/yaoapp/kun/log" + "github.com/yaoapp/gou/application" + v8 "github.com/yaoapp/gou/runtime/v8" "github.com/yaoapp/yao/config" "github.com/yaoapp/yao/share" ) // Load 加载共享库 func Load(cfg config.Config) error { - if share.BUILDIN { - return LoadBuildIn("scripts") - } - - err := LoadFrom(filepath.Join(cfg.Root, "scripts"), "") - if err != nil { + exts := []string{"*.js"} + return application.App.Walk("scripts", func(root, file string, isdir bool) error { + _, err := v8.Load(file, share.ID(root, file)) return err - } - - return LoadFrom(filepath.Join(cfg.Root, "services"), "__yao_service.") -} + }, exts...) -// LoadBuildIn 从制品中读取 -func LoadBuildIn(dir string) error { - return nil + // return LoadFrom(filepath.Join(cfg.Root, "services"), "__yao_service.") } -// LoadFrom 从特定目录加载共享库 -func LoadFrom(dir string, prefix string) error { - - if share.DirNotExists(dir) { - log.Error("%s does not exists", dir) - return nil - } - - // 加载共享脚本 - err := share.Walk(dir, ".js", func(root, filename string) { - name := share.SpecName(root, filename) - err := gou.Yao.Load(filename, fmt.Sprintf("%s%s", prefix, name)) - if err != nil { - log.Error("加载脚本失败 %s", err.Error()) - } - }) - return err -} +// // LoadBuildIn 从制品中读取 +// func LoadBuildIn(dir string) error { +// return nil +// } + +// // LoadFrom 从特定目录加载共享库 +// func LoadFrom(dir string, prefix string) error { + +// if share.DirNotExists(dir) { +// log.Error("%s does not exists", dir) +// return nil +// } + +// // 加载共享脚本 +// err := share.Walk(dir, ".js", func(root, filename string) { +// name := share.SpecName(root, filename) +// err := gou.Yao.Load(filename, fmt.Sprintf("%s%s", prefix, name)) +// if err != nil { +// log.Error("加载脚本失败 %s", err.Error()) +// } +// }) +// return err +// } diff --git a/script/script_test.go b/script/script_test.go index c16dfb3573..fc46ba76cb 100644 --- a/script/script_test.go +++ b/script/script_test.go @@ -1,23 +1,11 @@ package script import ( - "os" - "path" "testing" - - "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" - "github.com/yaoapp/yao/config" - "github.com/yaoapp/yao/runtime" ) -func init() { - runtime.Load(config.Conf) - rootLib := path.Join(os.Getenv("YAO_DEV"), "/tests/scripts") - LoadFrom(rootLib, "") -} func TestScript(t *testing.T) { - res, err := gou.Yao.New("time", "hello").Call("world") - assert.Nil(t, err) - assert.Equal(t, "name:world", res) + // res, err := gou.Yao.New("time", "hello").Call("world") + // assert.Nil(t, err) + // assert.Equal(t, "name:world", res) } diff --git a/service/guard.go b/service/guard.go index aa1ce27f17..e7d3e8c3ec 100644 --- a/service/guard.go +++ b/service/guard.go @@ -5,7 +5,6 @@ import ( "github.com/gin-gonic/gin" "github.com/yaoapp/yao/helper" - table_v0 "github.com/yaoapp/yao/table" "github.com/yaoapp/yao/widgets/chart" "github.com/yaoapp/yao/widgets/dashboard" @@ -18,7 +17,6 @@ import ( var Guards = map[string]gin.HandlerFunc{ "bearer-jwt": guardBearerJWT, // Bearer JWT "cross-origin": guardCrossOrigin, // Cross-Origin Resource Sharing - "table-guard": table_v0.Guard, // Table Guard ( v0.9 table) "widget-table": table.Guard, // Widget Table Guard "widget-list": list.Guard, // Widget List Guard "widget-form": form.Guard, // Widget Form Guard diff --git a/service/middleware.go b/service/middleware.go index 6e3338f31f..297fb0a59a 100644 --- a/service/middleware.go +++ b/service/middleware.go @@ -8,7 +8,7 @@ import ( ) // Middlewares 服务中间件 -var Middlewares = []gin.HandlerFunc{ +var Middlewares = []func(c *gin.Context){ BinStatic, } diff --git a/service/service.go b/service/service.go index b5f24f005c..bd6cf0e0fd 100644 --- a/service/service.go +++ b/service/service.go @@ -3,7 +3,9 @@ package service import ( "context" - "github.com/yaoapp/gou" + "github.com/gin-gonic/gin" + "github.com/yaoapp/gou/api" + "github.com/yaoapp/gou/server/http" "github.com/yaoapp/kun/log" "github.com/yaoapp/yao/config" "github.com/yaoapp/yao/share" @@ -14,44 +16,38 @@ var shutdown = make(chan bool, 1) var shutdownComplete = make(chan bool, 1) // Start 启动服务 -func Start() error { +func Start() (*http.Server, error) { err := prepare() if err != nil { - return err + return nil, err } - gou.SetHTTPGuards(Guards) - gou.ServeHTTP( - gou.Server{ - Host: config.Conf.Host, - Port: config.Conf.Port, - Root: "/api", - Allows: config.Conf.AllowFrom, - }, - shutdown, func(s gou.Server) { - shutdownComplete <- true - }, - Middlewares...) + router := gin.New() + api.SetRoutes(router, "/api", config.Conf.AllowFrom...) + srv := http.New(router, http.Option{ + Host: config.Conf.Host, + Port: config.Conf.Port, + Root: "/api", + Allows: config.Conf.AllowFrom, + }).With(Middlewares...) - return nil + return srv, nil } // StartWithouttSession 启动服务 -func StartWithouttSession() { - - gou.SetHTTPGuards(Guards) - gou.ServeHTTP( - gou.Server{ - Host: config.Conf.Host, - Port: config.Conf.Port, - Root: "/api", - Allows: config.Conf.AllowFrom, - }, - shutdown, func(s gou.Server) { - shutdownComplete <- true - }, - Middlewares...) +func StartWithouttSession() (*http.Server, error) { + + router := gin.New() + api.SetRoutes(router, "/api", config.Conf.AllowFrom...) + srv := http.New(router, http.Option{ + Host: config.Conf.Host, + Port: config.Conf.Port, + Root: "/api", + Allows: config.Conf.AllowFrom, + }).With(Middlewares...) + + return srv, nil } // StopWithouttSession 关闭服务 diff --git a/service/watch.go b/service/watch.go index 6dd81a53ef..1a8a97a8a2 100644 --- a/service/watch.go +++ b/service/watch.go @@ -14,7 +14,6 @@ import ( "github.com/fatih/color" "github.com/fsnotify/fsnotify" - "github.com/yaoapp/gou" "github.com/yaoapp/kun/log" "github.com/yaoapp/yao/config" "github.com/yaoapp/yao/engine" @@ -207,44 +206,44 @@ func watchStart(cfg config.Config) error { } func watchModel(root string, file string, event string, cfg config.Config) { - name := share.SpecName(root, file) - switch event { - case "CREATE": - content, err := ioutil.ReadFile(file) - if err != nil { - fmt.Println(color.RedString("[Watch] Model: %s %s", name, err.Error())) - return - } - _, err = gou.LoadModelReturn(string(content), name) - if err != nil { - fmt.Println(color.RedString("[Watch] Model: %s %s", name, err.Error())) - return - } - - // mod.Migrate(true) - fmt.Println(color.GreenString("[Watch] Model: %s Created (Please run yao migrate manually)", name)) - break - - case "WRITE": - content, err := ioutil.ReadFile(file) - if err != nil { - fmt.Println(color.RedString("[Watch] Model: %s %s", name, err.Error())) - return - } - _, err = gou.LoadModelReturn(string(content), name) - if err != nil { - fmt.Println(color.RedString("[Watch] Model: %s %s", name, err.Error())) - return - } - // mod.Migrate(false) - fmt.Println(color.GreenString("[Watch] Model: %s Reloaded (Please run yao migrate manually)", name)) - break - - case "REMOVE", "RENAME": - delete(gou.Models, name) - fmt.Println(color.GreenString("[Watch] Model: %s Removed", name)) - break - } + // name := share.SpecName(root, file) + // switch event { + // case "CREATE": + // content, err := ioutil.ReadFile(file) + // if err != nil { + // fmt.Println(color.RedString("[Watch] Model: %s %s", name, err.Error())) + // return + // } + // _, err = gou.LoadModelReturn(string(content), name) + // if err != nil { + // fmt.Println(color.RedString("[Watch] Model: %s %s", name, err.Error())) + // return + // } + + // // mod.Migrate(true) + // fmt.Println(color.GreenString("[Watch] Model: %s Created (Please run yao migrate manually)", name)) + // break + + // case "WRITE": + // content, err := ioutil.ReadFile(file) + // if err != nil { + // fmt.Println(color.RedString("[Watch] Model: %s %s", name, err.Error())) + // return + // } + // _, err = gou.LoadModelReturn(string(content), name) + // if err != nil { + // fmt.Println(color.RedString("[Watch] Model: %s %s", name, err.Error())) + // return + // } + // // mod.Migrate(false) + // fmt.Println(color.GreenString("[Watch] Model: %s Reloaded (Please run yao migrate manually)", name)) + // break + + // case "REMOVE", "RENAME": + // delete(gou.Models, name) + // fmt.Println(color.GreenString("[Watch] Model: %s Removed", name)) + // break + // } } func watchReload(root string, file string, event string, cfg config.Config) { diff --git a/setup/install.go b/setup/install.go index 7f1522e0f9..b969e5ef66 100644 --- a/setup/install.go +++ b/setup/install.go @@ -6,7 +6,8 @@ import ( "path/filepath" "strings" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/model" + "github.com/yaoapp/gou/process" "github.com/yaoapp/kun/log" "github.com/yaoapp/yao/data" "github.com/yaoapp/yao/engine" @@ -276,7 +277,7 @@ func makeMigrate(root string) error { } // Do Stuff Here - for _, mod := range gou.Models { + for _, mod := range model.Models { has, err := mod.HasTable() if err != nil { return err @@ -316,17 +317,17 @@ func makeSetup(root string) error { return fmt.Errorf("setup studio script %s error", app.Setting.Setup) } - service := strings.Join(names[1:len(names)-1], ".") - method := names[len(names)-1] - req := gou.Yao.New(service, method) - _, err := req.RootCall(cfg) - if err != nil { - return err - } + // service := strings.Join(names[1:len(names)-1], ".") + // method := names[len(names)-1] + // req := gou.Yao.New(service, method) + // _, err := req.RootCall(cfg) + // if err != nil { + // return err + // } return nil } - p, err := gou.ProcessOf(app.Setting.Setup, cfg) + p, err := process.Of(app.Setting.Setup, cfg) if err != nil { return err } diff --git a/share/api.go b/share/api.go index 3034e3d4be..f76978bc08 100644 --- a/share/api.go +++ b/share/api.go @@ -1,13 +1,11 @@ package share import ( - "fmt" "strings" - "github.com/gin-gonic/gin" - "github.com/yaoapp/gou" - "github.com/yaoapp/gou/query/share" + "github.com/yaoapp/gou/helper" "github.com/yaoapp/gou/session" + "github.com/yaoapp/gou/types" "github.com/yaoapp/kun/any" "github.com/yaoapp/kun/exception" "github.com/yaoapp/kun/log" @@ -15,26 +13,6 @@ import ( "github.com/yaoapp/kun/utils" ) -// IsAllow 鉴权处理程序 (废弃) -func (api API) IsAllow(v interface{}) bool { - c, ok := v.(*gin.Context) - if !ok { - return false - } - - guards := strings.Split(api.Guard, ",") - for _, guard := range guards { - guard = strings.TrimSpace(guard) - handler, has := gou.HTTPGuards[guard] - if has { - handler(c) - fmt.Println(api.Guard, c.IsAborted()) - return c.IsAborted() - } - } - return false -} - // ValidateLoop 循环引用校验 func (api API) ValidateLoop(name string) API { if strings.ToLower(api.Process) == strings.ToLower(name) { @@ -88,7 +66,7 @@ func (api API) DefaultString(i int, defaults ...string) string { } // MergeDefaultQueryParam 合并默认查询参数 -func (api API) MergeDefaultQueryParam(param gou.QueryParam, i int, sid string) gou.QueryParam { +func (api API) MergeDefaultQueryParam(param types.QueryParam, i int, sid string) types.QueryParam { if len(api.Default) > i && api.Default[i] != nil { defaults := GetQueryParam(api.Default[i], sid) @@ -104,7 +82,7 @@ func (api API) MergeDefaultQueryParam(param gou.QueryParam, i int, sid string) g if defaults.Wheres != nil { if param.Wheres == nil { - param.Wheres = []gou.QueryWhere{} + param.Wheres = []types.QueryWhere{} } param.Wheres = append(param.Wheres, defaults.Wheres...) } @@ -117,7 +95,7 @@ func (api API) MergeDefaultQueryParam(param gou.QueryParam, i int, sid string) g } // GetQueryParam 解析参数 -func GetQueryParam(v interface{}, sid string) gou.QueryParam { +func GetQueryParam(v interface{}, sid string) types.QueryParam { log.With(log.F{"sid": sid}).Trace("GetQueryParam Entry") data := map[string]interface{}{} if sid != "" { @@ -129,8 +107,8 @@ func GetQueryParam(v interface{}, sid string) gou.QueryParam { log.Error("读取会话信息出错 %s", err.Error()) } } - v = share.Bind(v, maps.Of(data).Dot()) - param, ok := gou.AnyToQueryParam(v) + v = helper.Bind(v, maps.Of(data).Dot()) + param, ok := types.AnyToQueryParam(v) if !ok { exception.New("参数默认值数据结构错误", 400).Ctx(v).Throw() } diff --git a/share/columns.go b/share/columns.go index aff7e54b9f..d7cda9e9fd 100644 --- a/share/columns.go +++ b/share/columns.go @@ -3,7 +3,7 @@ package share import ( "fmt" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/model" ) var elms = map[string]Column{ @@ -54,7 +54,7 @@ var elms = map[string]Column{ // GetDefaultColumns 读取数据模型字段的呈现方式 func GetDefaultColumns(name string) map[string]Column { - mod := gou.Select(name) + mod := model.Select(name) cmap := mod.Columns columns := map[string]Column{} diff --git a/share/filters.go b/share/filters.go index 7d5e1604fd..ae6791a63d 100644 --- a/share/filters.go +++ b/share/filters.go @@ -3,13 +3,13 @@ package share import ( "fmt" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/model" ) // GetDefaultFilters 读取数据模型索引字段的过滤器 func GetDefaultFilters(name string) map[string]Filter { - mod := gou.Select(name) + mod := model.Select(name) cmap := mod.Columns filters := map[string]Filter{} for _, index := range mod.MetaData.Indexes { diff --git a/share/importable.go b/share/importable.go index ce828a8b79..b8c39ec2ca 100644 --- a/share/importable.go +++ b/share/importable.go @@ -5,8 +5,7 @@ import ( "path/filepath" jsoniter "github.com/json-iterator/go" - "github.com/yaoapp/gou" - "github.com/yaoapp/gou/query/share" + "github.com/yaoapp/gou/helper" "github.com/yaoapp/kun/exception" "github.com/yaoapp/kun/log" "github.com/yaoapp/kun/maps" @@ -63,11 +62,11 @@ func LoadFrom(dir string) error { // 加载共享脚本 err = Walk(dir, ".js", func(root, filename string) { - name := SpecName(root, filename) - err := gou.Yao.Load(filename, name) - if err != nil { - log.Error("加载脚本失败 %s", err.Error()) - } + // name := SpecName(root, filename) + // err := gou.Yao.Load(filename, name) + // if err != nil { + // log.Error("加载脚本失败 %s", err.Error()) + // } }) return err } @@ -174,7 +173,7 @@ func ImportJSON(name string, in []interface{}, v interface{}) error { } data := maps.MapStrAny{"$in": in}.Dot() - content, err := jsoniter.Marshal(share.Bind(lib, data)) + content, err := jsoniter.Marshal(helper.Bind(lib, data)) if err != nil { return err } diff --git a/socket/socket.go b/socket/socket.go index 7a7e4723be..4a9ab9f4fb 100644 --- a/socket/socket.go +++ b/socket/socket.go @@ -1,36 +1,31 @@ package socket import ( - "fmt" - "path/filepath" - - "github.com/yaoapp/gou" - "github.com/yaoapp/kun/log" "github.com/yaoapp/yao/config" - "github.com/yaoapp/yao/share" ) // Load 加载API func Load(cfg config.Config) error { - var root = filepath.Join(cfg.Root, "sockets") - return LoadFrom(root, "") + // var root = filepath.Join(cfg.Root, "sockets") + // return LoadFrom(root, "") + return nil } // LoadFrom 从特定目录加载 -func LoadFrom(dir string, prefix string) error { +// func LoadFrom(dir string, prefix string) error { - if share.DirNotExists(dir) { - return fmt.Errorf("%s does not exists", dir) - } +// if share.DirNotExists(dir) { +// return fmt.Errorf("%s does not exists", dir) +// } - err := share.Walk(dir, ".sock.json", func(root, filename string) { - name := prefix + share.SpecName(root, filename) - content := share.ReadFile(filename) - _, err := gou.LoadSocket(string(content), name) - if err != nil { - log.With(log.F{"root": root, "file": filename}).Error(err.Error()) - } - }) +// err := share.Walk(dir, ".sock.json", func(root, filename string) { +// name := prefix + share.SpecName(root, filename) +// content := share.ReadFile(filename) +// _, err := gou.LoadSocket(string(content), name) +// if err != nil { +// log.With(log.F{"root": root, "file": filename}).Error(err.Error()) +// } +// }) - return err -} +// return err +// } diff --git a/socket/socket_test.go b/socket/socket_test.go index 1f41a5660d..e7c142d1c6 100644 --- a/socket/socket_test.go +++ b/socket/socket_test.go @@ -4,20 +4,19 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/socket" "github.com/yaoapp/yao/config" ) func TestLoad(t *testing.T) { Load(config.Conf) - LoadFrom("not a path", "404.") check(t) } func check(t *testing.T) { keys := []string{} - for key := range gou.Sockets { + for key := range socket.Sockets { keys = append(keys, key) } - assert.Equal(t, 2, len(keys)) + assert.Equal(t, 0, len(keys)) } diff --git a/store/store.go b/store/store.go index 4b5e3db610..ee9f891c71 100644 --- a/store/store.go +++ b/store/store.go @@ -1,36 +1,36 @@ package store import ( - "fmt" - "path/filepath" - - "github.com/yaoapp/gou" - "github.com/yaoapp/kun/log" + "github.com/yaoapp/gou/application" + "github.com/yaoapp/gou/store" "github.com/yaoapp/yao/config" "github.com/yaoapp/yao/share" ) // Load load store func Load(cfg config.Config) error { - var root = filepath.Join(cfg.Root, "stores") - return LoadFrom(root, "") + exts := []string{"*.yao", "*.json", "*.jsonc"} + return application.App.Walk("stores", func(root, file string, isdir bool) error { + _, err := store.Load(file, share.ID(root, file)) + return err + }, exts...) } -// LoadFrom load from dir -func LoadFrom(dir string, prefix string) error { +// // LoadFrom load from dir +// func LoadFrom(dir string, prefix string) error { - if share.DirNotExists(dir) { - return fmt.Errorf("%s does not exists", dir) - } +// if share.DirNotExists(dir) { +// return fmt.Errorf("%s does not exists", dir) +// } - err := share.Walk(dir, ".json", func(root, filename string) { - name := prefix + share.SpecName(root, filename) - content := share.ReadFile(filename) - _, err := gou.LoadStore(string(content), name) - if err != nil { - log.With(log.F{"root": root, "file": filename}).Error(err.Error()) - } - }) +// err := share.Walk(dir, ".json", func(root, filename string) { +// name := prefix + share.SpecName(root, filename) +// content := share.ReadFile(filename) +// _, err := gou.LoadStore(string(content), name) +// if err != nil { +// log.With(log.F{"root": root, "file": filename}).Error(err.Error()) +// } +// }) - return err -} +// return err +// } diff --git a/store/store_test.go b/store/store_test.go index ce45a60c28..d6c22b766a 100644 --- a/store/store_test.go +++ b/store/store_test.go @@ -12,7 +12,6 @@ import ( func TestLoad(t *testing.T) { connector.Load(config.Conf) Load(config.Conf) - LoadFrom("not a path", "404.") check(t) } diff --git a/studio/router.go b/studio/router.go index 9ad8339539..90ce469b11 100644 --- a/studio/router.go +++ b/studio/router.go @@ -10,7 +10,7 @@ import ( "github.com/gin-gonic/gin" jsoniter "github.com/json-iterator/go" - "github.com/yaoapp/gou" + v8 "github.com/yaoapp/gou/runtime/v8" ) var regExcp = regexp.MustCompile("^Exception\\|([0-9]+):(.+)$") @@ -202,12 +202,18 @@ func setRouter(router *gin.Engine) { return } - req := gou.Yao.New(service, fun.Method) - if sid, has := c.Get("__sid"); has { - req.WithSid(fmt.Sprintf("%s", sid)) + sid, _ := c.Get("__sid") + script, err := v8.SelectRoot(service) + if err != nil { + throw(c, 500, err.Error()) + } + + ctx, err := script.NewContext(fmt.Sprintf("%v", sid), nil) + if err != nil { + throw(c, 500, err.Error()) } + res, err := ctx.Call(fun.Method, fun.Args...) - res, err := req.RootCall(fun.Args...) if err != nil { // parse Exception code := 500 diff --git a/studio/studio.go b/studio/studio.go index 4e3ab05463..436951f77a 100644 --- a/studio/studio.go +++ b/studio/studio.go @@ -11,9 +11,9 @@ import ( "syscall" "github.com/gin-gonic/gin" - "github.com/yaoapp/gou" "github.com/yaoapp/gou/fs" "github.com/yaoapp/gou/fs/dsl" + v8 "github.com/yaoapp/gou/runtime/v8" "github.com/yaoapp/kun/log" "github.com/yaoapp/yao/config" "github.com/yaoapp/yao/share" @@ -135,7 +135,7 @@ func loadScriptFrom(dir string) error { messages := []string{} err := share.Walk(dir, ".js", func(root, filename string) { name := share.SpecName(root, filename) - err := gou.Yao.RootLoad(filename, name) + _, err := v8.LoadRoot(filename, name) if err != nil { messages = append(messages, err.Error()) } diff --git a/studio/studio_test.go b/studio/studio_test.go index e3d08cd9f0..cc2a111e02 100644 --- a/studio/studio_test.go +++ b/studio/studio_test.go @@ -10,30 +10,27 @@ import ( jsoniter "github.com/json-iterator/go" "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" "github.com/yaoapp/yao/config" "github.com/yaoapp/yao/helper" - "github.com/yaoapp/yao/runtime" ) type kv map[string]interface{} type arr []interface{} func TestLoad(t *testing.T) { - runtime.Load(config.Conf) err := Load(config.Conf) if err != nil { t.Fatal(err) } assert.NotNil(t, dfs) - res, err := gou.Yao.Engine.RootCall(map[string]interface{}{}, "table", "Ping") - assert.Nil(t, err) - assert.Equal(t, "PONG", res) + // res, err := gou.Yao.Engine.RootCall(map[string]interface{}{}, "table", "Ping") + // assert.Nil(t, err) + // assert.Equal(t, "PONG", res) - _, err = gou.Yao.Engine.Call(map[string]interface{}{}, "table", "Ping") - assert.NotNil(t, err) - assert.Contains(t, err.Error(), "The table does not loaded") + // _, err = gou.Yao.Engine.Call(map[string]interface{}{}, "table", "Ping") + // assert.NotNil(t, err) + // assert.Contains(t, err.Error(), "The table does not loaded") } func TestStartStop(t *testing.T) { diff --git a/system/process_test.go b/system/process_test.go index cb0bfbe96e..bfad991df2 100644 --- a/system/process_test.go +++ b/system/process_test.go @@ -1,7 +1,7 @@ package system // func TestProcessReturn(t *testing.T) { -// output, err := gou.NewProcess("yao.system.Exec", "echo", "hello").Exec() +// output, err := process.New("yao.system.Exec", "echo", "hello").Exec() // if err != nil { // t.Fatal(err) // } diff --git a/table/api.go b/table/api.go deleted file mode 100644 index 609b964d44..0000000000 --- a/table/api.go +++ /dev/null @@ -1,79 +0,0 @@ -package table - -import ( - "fmt" - - "github.com/yaoapp/gou" - "github.com/yaoapp/yao/share" -) - -// apiSearchDefault search 接口默认值 -func apiSearchDefault(model *gou.Model, withs map[string]gou.With) share.API { - query := gou.QueryParam{} - if model.MetaData.Option.Timestamps { - query.Orders = []gou.QueryOrder{ - {Column: "created_at", Option: "desc"}, - } - } - - if withs != nil { - query.Withs = withs - } - - return share.API{ - Name: "search", - // Guard: "bearer-jwt", - Process: fmt.Sprintf("models.%s.Paginate", model.Name), - Default: []interface{}{query, 1, 20}, - } -} - -// apiFindDefault find 接口默认值 -func apiFindDefault(model *gou.Model, withs map[string]gou.With) share.API { - - query := gou.QueryParam{} - if withs != nil { - query.Withs = withs - } - - return share.API{ - Name: "find", - // Guard: "bearer-jwt", - Process: fmt.Sprintf("models.%s.Find", model.Name), - Default: []interface{}{nil, query}, - } -} - -// apiDefault 接口默认值 -func apiDefault(model *gou.Model, name string, process string) share.API { - return share.API{ - Name: name, - // Guard: "bearer-jwt", - Process: fmt.Sprintf("models.%s.%s", model.Name, process), - } -} - -// apiFindDefault 接口默认值 -func apiDefaultWhere(model *gou.Model, withs map[string]gou.With, name string, process string) share.API { - - query := gou.QueryParam{} - if withs != nil { - query.Withs = withs - } - - return share.API{ - Name: name, - // Guard: "bearer-jwt", - Process: fmt.Sprintf("models.%s.%s", model.Name, process), - Default: []interface{}{query}, - } -} - -// apiDefaultSetting 数据表格配置默认值 -func apiDefaultSetting() share.API { - return share.API{ - Name: "setting", - // Guard: "bearer-jwt", - Process: fmt.Sprintf("xiang.table.setting"), - } -} diff --git a/table/json.go b/table/json.go deleted file mode 100644 index 4861f2721e..0000000000 --- a/table/json.go +++ /dev/null @@ -1,42 +0,0 @@ -package table - -// // UnmarshalJSON for json marshalJSON -// func (table *Table) UnmarshalJSON(data []byte) error { - -// var v interface{} -// err := jsoniter.Unmarshal(data, &v) -// if err != nil { -// return err -// } - -// // values := []interface{}{} -// // switch v.(type) { -// // case string: // "kind rollup 所有类型, city" -// // strarr := strings.Split(v.(string), ",") -// // for _, str := range strarr { -// // groups.PushString(str) -// // } -// // break -// // case []interface{}: // ["name", {"field":"foo"}, "id rollup 所有类型"] -// // values = v.([]interface{}) -// // break -// // } - -// // for _, value := range values { -// // switch value.(type) { -// // case string: // "kind rollup 所有类型" -// // groups.PushString(value.(string)) -// // break -// // case map[string]interface{}: // {"field":"foo"} -// // groups.PushMap(value.(map[string]interface{})) -// // break -// // } -// // } - -// return nil -// } - -// // MarshalJSON for json marshalJSON -// func (table Table) MarshalJSON() ([]byte, error) { -// return jsoniter.Marshal(nil) -// } diff --git a/table/lang.go b/table/lang.go deleted file mode 100644 index 4b23f07179..0000000000 --- a/table/lang.go +++ /dev/null @@ -1,98 +0,0 @@ -package table - -// Lang for applying a language pack -func (table *Table) Lang(trans func(widget string, inst string, value *string) bool) { - inst := table.Table - widget := "table" - - trans(widget, inst, &table.Name) - trans(widget, inst, &table.Decription) - - // Columns - for name, column := range table.Columns { - new := name - trans(widget, inst, &new) - trans(widget, inst, &column.Label) - - // Props - transMap(widget, inst, column.Edit.Props, trans) - transMap(widget, inst, column.View.Props, trans) - transMap(widget, inst, column.Form.Props, trans) - - delete(table.Columns, name) - table.Columns[new] = column - } - - // Filters - for name, filter := range table.Filters { - new := name - trans(widget, inst, &new) - trans(widget, inst, &filter.Label) - delete(table.Filters, name) - - // Props - transMap(widget, inst, filter.Input.Props, trans) - table.Filters[new] = filter - } - - // List - transMap(widget, inst, table.List.Layout, trans) - transMap(widget, inst, table.List.Option, trans) - - // Edit - transMap(widget, inst, table.Edit.Layout, trans) - transMap(widget, inst, table.Edit.Option, trans) -} - -func transMap(widget string, inst string, values map[string]interface{}, trans func(widget string, inst string, value *string) bool) { - for key, value := range values { - - switch value.(type) { - - case string: - v := value.(string) - trans(widget, inst, &v) - values[key] = v - break - - case []interface{}: - v := value.([]interface{}) - transArr(widget, inst, v, trans) - values[key] = v - break - - case map[string]interface{}: - v := value.(map[string]interface{}) - transMap(widget, inst, v, trans) - values[key] = v - break - } - - } -} - -func transArr(widget string, inst string, values []interface{}, trans func(widget string, inst string, value *string) bool) { - for key, value := range values { - switch value.(type) { - - case string: - v := value.(string) - trans(widget, inst, &v) - values[key] = v - break - - case []interface{}: - v := value.([]interface{}) - transArr(widget, inst, v, trans) - values[key] = v - break - - case map[string]interface{}: - v := value.(map[string]interface{}) - transMap(widget, inst, v, trans) - values[key] = v - break - } - - } -} diff --git a/table/process.go b/table/process.go deleted file mode 100644 index da08c436ea..0000000000 --- a/table/process.go +++ /dev/null @@ -1,445 +0,0 @@ -package table - -import ( - "crypto/md5" - "encoding/hex" - "fmt" - "os" - "path/filepath" - "strings" - "time" - - jsoniter "github.com/json-iterator/go" - "github.com/yaoapp/gou" - "github.com/yaoapp/kun/any" - "github.com/yaoapp/kun/log" - "github.com/yaoapp/kun/maps" - "github.com/yaoapp/yao/xfs" -) - -func init() { - // 注册处理器 - gou.RegisterProcessHandler("xiang.table.Search", ProcessSearch) - gou.RegisterProcessHandler("xiang.table.Find", ProcessFind) - gou.RegisterProcessHandler("xiang.table.Select", ProcessSelect) - gou.RegisterProcessHandler("xiang.table.Save", ProcessSave) - gou.RegisterProcessHandler("xiang.table.Delete", ProcessDelete) - gou.RegisterProcessHandler("xiang.table.Insert", ProcessInsert) - gou.RegisterProcessHandler("xiang.table.UpdateWhere", ProcessUpdateWhere) - gou.RegisterProcessHandler("xiang.table.DeleteWhere", ProcessDeleteWhere) - gou.RegisterProcessHandler("xiang.table.QuickSave", ProcessQuickSave) - gou.RegisterProcessHandler("xiang.table.UpdateIn", ProcessUpdateIn) - gou.RegisterProcessHandler("xiang.table.DeleteIn", ProcessDeleteIn) - gou.RegisterProcessHandler("xiang.table.Export", ProcessExport) - gou.RegisterProcessHandler("xiang.table.Setting", ProcessSetting) -} - -// ProcessSearch xiang.table.Search -// 按条件查询数据记录, 请求成功返回符合查询条件带有分页信息的数据对象 -func ProcessSearch(process *gou.Process) interface{} { - - // 读取表格名称 - process.ValidateArgNums(1) - name := process.ArgsString(0) - table := Select(name) - - api := table.APIs["search"].ValidateLoop("xiang.table.search") - - // Before Hook - process.Args = table.Before(table.Hooks.BeforeSearch, process.Args, process.Sid) - - // 参数表 - process.ValidateArgNums(4) - param := api.MergeDefaultQueryParam(process.ArgsQueryParams(1), 0, process.Sid) - log.With(log.F{"param": param}).Trace("==== ProcessSearch ============= SID: %s", process.Sid) - page := process.ArgsInt(2, api.DefaultInt(1)) - pagesize := process.ArgsInt(3, api.DefaultInt(2)) - - // 查询数据 - response := gou.NewProcess(api.Process, param, page, pagesize). - WithGlobal(process.Global). - WithSID(process.Sid). - Run() - - // After Hook - return table.After(table.Hooks.AfterSearch, response, []interface{}{param, page, pagesize}, process.Sid) -} - -// ProcessFind xiang.table.Find -// 按主键值查询单条数据, 请求成功返回对应主键的数据记录 -func ProcessFind(process *gou.Process) interface{} { - - process.ValidateArgNums(1) - name := process.ArgsString(0) - table := Select(name) - api := table.APIs["find"].ValidateLoop("xiang.table.find") - - // Before Hook - process.Args = table.Before(table.Hooks.BeforeFind, process.Args, process.Sid) - - // 参数表 - process.ValidateArgNums(2) - id := process.Args[1] - queryParam := gou.QueryParam{} - if process.NumOfArgs() == 3 { - queryParam = process.ArgsQueryParams(2) - } - param := api.MergeDefaultQueryParam(queryParam, 1, process.Sid) - - // 查询数据 - response := gou.NewProcess(api.Process, id, param). - WithGlobal(process.Global). - WithSID(process.Sid). - Run() - - // After Hook - return table.After(table.Hooks.AfterFind, response, []interface{}{id, param}, process.Sid) -} - -// ProcessSave xiang.table.Save -// 保存单条记录。如数据记录中包含主键字段则更新,不包含主键字段则创建记录;返回创建或更新的记录主键值 -func ProcessSave(process *gou.Process) interface{} { - - // 读取表格名称 - process.ValidateArgNums(1) - name := process.ArgsString(0) - table := Select(name) - api := table.APIs["save"].ValidateLoop("xiang.table.save") - - // Before Hook - process.Args = table.Before(table.Hooks.BeforeSave, process.Args, process.Sid) - - // 参数处理 - process.ValidateArgNums(2) - - // 查询数据 - response := gou.NewProcess(api.Process, process.Args[1]). - WithGlobal(process.Global). - WithSID(process.Sid). - Run() - - // After Hook - return table.After(table.Hooks.AfterSave, response, []interface{}{process.Args[1]}, process.Sid) -} - -// ProcessDelete xiang.table.Delete -// 删除指定主键值的数据记录, 请求成功返回null -func ProcessDelete(process *gou.Process) interface{} { - process.ValidateArgNums(2) - name := process.ArgsString(0) - table := Select(name) - api := table.APIs["delete"].ValidateLoop("xiang.table.delete") - - // Before Hook - process.Args = table.Before(table.Hooks.BeforeDelete, process.Args, process.Sid) - - id := process.Args[1] - response := gou.NewProcess(api.Process, id). - WithGlobal(process.Global). - WithSID(process.Sid). - Run() - - // After Hook - return table.After(table.Hooks.AfterDelete, response, []interface{}{id}, process.Sid) -} - -// ProcessDeleteWhere xiang.table.DeleteWhere -// 按条件批量删除数据, 请求成功返回删除行数 -func ProcessDeleteWhere(process *gou.Process) interface{} { - - process.ValidateArgNums(2) - name := process.ArgsString(0) - table := Select(name) - api := table.APIs["delete-where"].ValidateLoop("xiang.table.DeleteWhere") - - // 批量删除 - param := api.MergeDefaultQueryParam(process.ArgsQueryParams(1), 0, process.Sid) - if param.Limit == 0 { // 限定删除行 - param.Limit = 10 - } - - return gou.NewProcess(api.Process, param). - WithGlobal(process.Global). - WithSID(process.Sid). - Run() -} - -// ProcessDeleteIn xiang.table.DeleteIn -// 按条件批量删除数据, 请求成功返回删除行数 -func ProcessDeleteIn(process *gou.Process) interface{} { - - process.ValidateArgNums(3) - name := process.ArgsString(0) - table := Select(name) - api := table.APIs["delete-in"].ValidateLoop("xiang.table.DeleteIn") - - // 批量删除 - ids := strings.Split(process.ArgsString(1), ",") - primary := process.ArgsString(2, "id") - param := gou.QueryParam{ - Wheres: []gou.QueryWhere{ - {Column: primary, OP: "in", Value: ids}, - }, - } - - return gou.NewProcess(api.Process, param). - WithGlobal(process.Global). - WithSID(process.Sid). - Run() -} - -// ProcessUpdateWhere xiang.table.UpdateWhere -// 按条件批量更新数据, 请求成功返回更新行数 -func ProcessUpdateWhere(process *gou.Process) interface{} { - - process.ValidateArgNums(3) - name := process.ArgsString(0) - table := Select(name) - api := table.APIs["update-where"].ValidateLoop("xiang.table.UpdateWhere") - - // 批量更新 - param := api.MergeDefaultQueryParam(process.ArgsQueryParams(1), 0, process.Sid) - if param.Limit == 0 { // 限定删除行 - param.Limit = 10 - } - return gou.NewProcess(api.Process, param, process.Args[2]). - WithGlobal(process.Global). - WithSID(process.Sid). - Run() -} - -// ProcessUpdateIn xiang.table.UpdateWhere -// 按条件批量更新数据, 请求成功返回更新行数 -func ProcessUpdateIn(process *gou.Process) interface{} { - - process.ValidateArgNums(4) - name := process.ArgsString(0) - table := Select(name) - api := table.APIs["update-in"].ValidateLoop("xiang.table.UpdateIn") - - // 批量删除 - ids := strings.Split(process.ArgsString(1), ",") - primary := process.ArgsString(2, "id") - param := gou.QueryParam{ - Wheres: []gou.QueryWhere{ - {Column: primary, OP: "in", Value: ids}, - }, - } - return gou.NewProcess(api.Process, param, process.Args[3]). - WithGlobal(process.Global). - WithSID(process.Sid). - Run() -} - -// ProcessInsert xiang.table.Insert -// 插入多条数据记录,请求成功返回插入行数 -func ProcessInsert(process *gou.Process) interface{} { - process.ValidateArgNums(3) - name := process.ArgsString(0) - table := Select(name) - api := table.APIs["insert"].ValidateLoop("xiang.table.Insert") - - return gou.NewProcess(api.Process, process.Args[1:]...). - WithGlobal(process.Global). - WithSID(process.Sid).Run() -} - -// ProcessSetting xiang.table.Setting -// 读取数据表格配置信息, 请求成功返回配置信息对象 -func ProcessSetting(process *gou.Process) interface{} { - process.ValidateArgNums(2) - name := process.ArgsString(0) - field := process.ArgsString(1) - table := Select(name) - api := table.APIs["setting"] - - fields := strings.Split(field, ",") - if api.ProcessIs("xiang.table.Setting") { - - setting := maps.Map{ - "name": table.Name, - "title": table.Title, - "decription": table.Decription, - "columns": table.Columns, - "filters": table.Filters, - "list": table.List, - "edit": table.Edit, - "view": table.View, - "insert": table.Insert, - } - - if len(fields) == 1 && setting.Has(fields[0]) { - field := strings.TrimSpace(fields[0]) - return setting.Get(field) - } - - if len(fields) > 1 { - res := maps.Map{} - for _, field := range fields { - field = strings.TrimSpace(field) - if setting.Has(field) { - res.Set(field, setting.Get(field)) - } - } - return res - } - return setting - } - - return gou.NewProcess(api.Process, fields). - WithGlobal(process.Global). - WithSID(process.Sid).Run() -} - -// ProcessQuickSave xiang.table.QuickSave -// 保存多条记录。如数据记录中包含主键字段则更新,不包含主键字段则创建记录;返回创建或更新的记录主键值 -func ProcessQuickSave(process *gou.Process) interface{} { - process.ValidateArgNums(2) - name := process.ArgsString(0) - table := Select(name) - api := table.APIs["quicksave"].ValidateLoop("xiang.table.quicksave") - - args := []interface{}{} - payload := process.ArgsMap(1) - ids := []int{} - if payload.Has("delete") { - if v, ok := payload["delete"].([]int); ok { - ids = v - } else if vany, ok := payload["delete"].([]interface{}); ok { - for _, v := range vany { - ids = append(ids, any.Of(v).CInt()) - } - } - } - args = append(args, ids) - args = append(args, payload.Get("data")) - if payload.Has("query") { - args = append(args, payload.Get("query")) - } - - return gou.NewProcess(api.Process, args...). - WithGlobal(process.Global). - WithSID(process.Sid).Run() -} - -// ProcessSelect xiang.table.Select -// 单表数据查询,一般用于下拉菜单检索 -func ProcessSelect(process *gou.Process) interface{} { - process.ValidateArgNums(1) - name := process.ArgsString(0) - table := Select(name) - api := table.APIs["select"].ValidateLoop("xiang.table.select") - - // Before Hook - process.Args = table.Before(table.Hooks.BeforeSelect, process.Args, process.Sid) - - response := gou.NewProcess(api.Process, process.Args[1:]...). - WithGlobal(process.Global). - WithSID(process.Sid).Run() - - // After Hook - return table.After(table.Hooks.AfterSelect, response, process.Args[1:], process.Sid) -} - -// ProcessExport xiang.table.Export (:table, :queryParam, :chunkSize) -// Export query result to Excel -func ProcessExport(process *gou.Process) interface{} { - // var testDataM = map[string]string{} - - debug := os.Getenv("YAO_EXPORT_DEBUG") != "" - process.ValidateArgNums(1) - name := process.ArgsString(0) - table := Select(name) - api := table.APIs["search"].ValidateLoop("xiang.table.search") - - // Make DIR - hash := md5.Sum([]byte(time.Now().Format("20060102-15:04:05"))) - fingerprint := string(hex.EncodeToString(hash[:])) - fingerprint = strings.ToUpper(fingerprint) - dir := time.Now().Format("20060102") - ext := filepath.Ext("export.xlsx") - filename := filepath.Join(dir, fmt.Sprintf("%s%s", fingerprint, ext)) - xfs.Stor.MustMkdirAll(dir, os.ModePerm) - - page := 1 - for page > 0 { - - // Before Hook - process.Args = table.Before(table.Hooks.BeforeSearch, process.Args, process.Sid) - - // 参数表 - process.ValidateArgNums(3) - param := api.MergeDefaultQueryParam(process.ArgsQueryParams(1), 0, process.Sid) - pagesize := process.ArgsInt(2, api.DefaultInt(2)) - if process.NumOfArgs() == 4 { // for search hook - pagesize = process.ArgsInt(3, api.DefaultInt(1)) - } - - // fmt.Printf("\n%d/%d\n", page, pagesize) - - if debug { - bytes, _ := jsoniter.Marshal(param) - log.Info("[Export] %s %s %d %d Params: %s", api.Process, filename, page, pagesize, string(bytes)) - } - - // 查询数据 - response := gou.NewProcess(api.Process, param, page, pagesize). - WithGlobal(process.Global). - WithSID(process.Sid). - Run() - - // for i, v := range response.(maps.MapStrAny)["data"].([]maps.MapStrAny) { - // fmt.Println("i=", i, "id=", v["id"], v["status"]) - // } - - if debug { - bytes, _ := jsoniter.Marshal(response) - log.Info("[Export] %s %d %d Prepare: %s", filename, page, pagesize, string(bytes)) - } - - // After Hook - respAfterHook := table.After(table.Hooks.AfterSearch, response, []interface{}{param, page, pagesize}, process.Sid) - - if debug { - bytes, _ := jsoniter.Marshal(respAfterHook) - log.Info("[Export] %s %d %d Prepare After: %s", filename, page, pagesize, string(bytes)) - } - - // utils.Dump(respAfterHook) - // for _, v := range respAfterHook.(map[string]interface{})["data"].([]interface{}) { - // name := v.(map[string]interface{})["name"].(string) - // if _, has := testDataM[name]; has { - // fmt.Printf("**** %s Has\n\n", testDataM[name]) - // } else { - // testDataM[name] = fmt.Sprintf("%s %d/%d", name, page, pagesize) - // } - // fmt.Println("i=", i, "id=", v.(map[string]interface{})["id"], v.(map[string]interface{})["status"]) - // } - - // fmt.Println("---") - // fmt.Println("") - - res, ok := respAfterHook.(map[string]interface{}) - if !ok { - res, ok = respAfterHook.(maps.MapStrAny) - if !ok { - page = -1 - continue - } - } - - if _, ok := res["next"]; !ok { - page = -1 - continue - } - - err := table.Export(filename, res["data"], page, pagesize) - if err != nil { - log.Error("Export %s %s", table.Table, err.Error()) - } - - page = any.Of(res["next"]).CInt() - } - - return filename -} diff --git a/table/process_test.go b/table/process_test.go deleted file mode 100644 index 669d0d20ee..0000000000 --- a/table/process_test.go +++ /dev/null @@ -1,547 +0,0 @@ -package table - -import ( - "fmt" - "path/filepath" - "testing" - - "github.com/gin-gonic/gin" - "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" - "github.com/yaoapp/kun/any" - "github.com/yaoapp/kun/maps" - "github.com/yaoapp/xun/capsule" - "github.com/yaoapp/yao/config" - "github.com/yaoapp/yao/flow" - _ "github.com/yaoapp/yao/helper" - "github.com/yaoapp/yao/model" - "github.com/yaoapp/yao/query" - "github.com/yaoapp/yao/runtime" - "github.com/yaoapp/yao/script" - "github.com/yaoapp/yao/share" -) - -func init() { - runtime.Load(config.Conf) - share.DBConnect(config.Conf.DB) - model.Load(config.Conf) - share.Load(config.Conf) - query.Load(config.Conf) - script.Load(config.Conf) - flow.LoadFrom(filepath.Join(config.Conf.Root, "flows", "hooks"), "hooks.") - Load(config.Conf) -} -func TestTableProcessSearch(t *testing.T) { - - args := []interface{}{ - "service", - gou.QueryParam{ - Wheres: []gou.QueryWhere{ - {Column: "status", Value: "enabled"}, - }, - }, - 1, - 2, - &gin.Context{}, - } - response := gou.NewProcess("xiang.table.Search", args...).Run() - assert.NotNil(t, response) - res := any.Of(response).Map() - assert.True(t, res.Has("data")) - assert.True(t, res.Has("next")) - assert.True(t, res.Has("page")) - assert.True(t, res.Has("pagecnt")) - assert.True(t, res.Has("pagesize")) - assert.True(t, res.Has("prev")) - assert.True(t, res.Has("total")) - assert.Equal(t, 1, res.Get("page")) - assert.Equal(t, 2, res.Get("pagesize")) -} - -func TestTableProcessSearchWithHook(t *testing.T) { - - args := []interface{}{"hooks.search"} - response := gou.NewProcess("xiang.table.Search", args...).Run() - // utils.Dump(response) - - assert.NotNil(t, response) - res := any.Of(response).Map() - assert.True(t, res.Has("data")) - assert.True(t, res.Has("next")) - assert.True(t, res.Has("page")) - assert.True(t, res.Has("pagecnt")) - assert.True(t, res.Has("pagesize")) - assert.True(t, res.Has("prev")) - assert.True(t, res.Has("total")) - assert.Equal(t, 1, res.Get("page")) - assert.Equal(t, 2, res.Get("pagesize")) - assert.Equal(t, float64(100), res.Get("after")) -} - -func TestTableProcessFind(t *testing.T) { - args := []interface{}{ - "service", - 1, - &gin.Context{}, - } - response := gou.NewProcess("xiang.table.Find", args...).Run() - assert.NotNil(t, response) - res := any.Of(response).Map() - assert.Equal(t, 1, any.Of(res.Get("id")).CInt()) -} - -func TestTableProcessFindWithHook(t *testing.T) { - args := []interface{}{"hooks.find"} - response := gou.NewProcess("xiang.table.Find", args...).Run() - assert.NotNil(t, response) - res := any.Of(response).Map() - assert.Equal(t, 1, any.Of(res.Get("id")).CInt()) - assert.Equal(t, float64(100), res.Get("after")) -} - -func TestTableProcessSave(t *testing.T) { - args := []interface{}{ - "service", - map[string]interface{}{ - "name": "腾讯黑岩云主机", - "short_name": "高性能云主机", - "kind_id": 3, - "manu_id": 1, - "price_options": []string{"按月订阅"}, - }, - } - response := gou.NewProcess("xiang.table.Save", args...).Run() - assert.NotNil(t, response) - assert.True(t, any.Of(response).IsInt()) - - id := any.Of(response).CInt() - - // 清空数据 - capsule.Query().Table("service").Where("id", id).Delete() -} - -func TestTableProcessSaveWithHook(t *testing.T) { - args := []interface{}{"hooks.save"} - response := gou.NewProcess("xiang.table.Save", args...).Run() - assert.NotNil(t, response) - res := any.Of(response).Map() - assert.True(t, any.Of(res.Get("id")).IsInt()) - assert.Equal(t, float64(100), res.Get("after")) - - id := any.Of(res.Get("id")).CInt() - - // 清空数据 - capsule.Query().Table("service").Where("id", id).Delete() -} - -func TestTableProcessDelete(t *testing.T) { - args := []interface{}{ - "service", - map[string]interface{}{ - "name": "腾讯黑岩云主机", - "short_name": "高性能云主机", - "kind_id": 3, - "manu_id": 1, - "price_options": []string{"按月订阅"}, - }, - } - process := gou.NewProcess("xiang.table.Save", args...) - response := ProcessSave(process) - assert.NotNil(t, response) - assert.True(t, any.Of(response).IsInt()) - - id := any.Of(response).CInt() - args = []interface{}{ - "service", - id, - } - process = gou.NewProcess("xiang.table.Delete", args...) - response = ProcessDelete(process) - assert.Nil(t, response) - - // 清空数据 - capsule.Query().Table("service").Where("id", id).Delete() -} - -func TestTableProcessInsert(t *testing.T) { - args := []interface{}{ - "service", - []string{"name", "short_name", "kind_id", "manu_id", "price_options"}, - [][]interface{}{ - {"I腾讯云主机I1", "高性能云主机", 3, 1, []string{"按月订阅"}}, - {"I腾讯云主机I2", "高性能云主机", 3, 1, []string{"按月订阅"}}, - }, - } - process := gou.NewProcess("xiang.table.Insert", args...) - response := ProcessInsert(process) - assert.Nil(t, response) - - // 清空数据 - capsule.Query().Table("service").Where("name", "like", "I腾讯云主机I%").Delete() -} - -func TestTableProcessDeleteWhere(t *testing.T) { - args := []interface{}{ - "service", - map[string]interface{}{ - "name": "腾讯黑岩云主机", - "short_name": "高性能云主机", - "kind_id": 3, - "manu_id": 1, - "price_options": []string{"按月订阅"}, - }, - } - process := gou.NewProcess("xiang.table.Save", args...) - response := ProcessSave(process) - assert.NotNil(t, response) - assert.True(t, any.Of(response).IsInt()) - - id := any.Of(response).CInt() - args = []interface{}{ - "service", - gou.QueryParam{ - Wheres: []gou.QueryWhere{ - {Column: "id", Value: id}, - }, - }, - } - process = gou.NewProcess("xiang.table.DeleteWhere", args...) - response = ProcessDeleteWhere(process) - - assert.NotNil(t, response) - assert.True(t, any.Of(response).IsInt()) - assert.Equal(t, any.Of(response).CInt(), 1) - - // 清空数据 - capsule.Query().Table("service").Where("id", id).Delete() -} - -func TestTableProcessDeleteIn(t *testing.T) { - args := []interface{}{ - "service", - map[string]interface{}{ - "name": "腾讯黑岩云主机", - "short_name": "高性能云主机", - "kind_id": 3, - "manu_id": 1, - "price_options": []string{"按月订阅"}, - }, - } - process := gou.NewProcess("xiang.table.Save", args...) - id := ProcessSave(process) - assert.NotNil(t, id) - assert.True(t, any.Of(id).IsNumber()) - - // id := any.Of(response).CInt() - args = []interface{}{"service", id, "id"} - process = gou.NewProcess("xiang.table.DeleteIn", args...) - id = ProcessDeleteIn(process) - - assert.NotNil(t, id) - assert.True(t, any.Of(id).IsNumber()) - assert.Equal(t, id, 1) - - // 清空数据 - capsule.Query().Table("service").Where("id", id).Delete() -} - -func TestTableProcessUpdateWhere(t *testing.T) { - args := []interface{}{ - "service", - map[string]interface{}{ - "name": "腾讯黑岩云主机", - "short_name": "高性能云主机", - "kind_id": 3, - "manu_id": 1, - "price_options": []string{"按月订阅"}, - }, - } - process := gou.NewProcess("xiang.table.Save", args...) - response := ProcessSave(process) - assert.NotNil(t, response) - assert.True(t, any.Of(response).IsInt()) - - id := any.Of(response).CInt() - args = []interface{}{ - "service", - gou.QueryParam{ - Wheres: []gou.QueryWhere{ - {Column: "id", Value: id}, - }, - }, - map[string]interface{}{ - "name": "腾讯黑岩云主机UP", - }, - } - process = gou.NewProcess("xiang.table.UpdateWhere", args...) - response = ProcessUpdateWhere(process) - - assert.NotNil(t, response) - assert.True(t, any.Of(response).IsInt()) - assert.Equal(t, any.Of(response).CInt(), 1) - - // 清空数据 - capsule.Query().Table("service").Where("id", id).Delete() -} - -func TestTableProcessUpdateIn(t *testing.T) { - args := []interface{}{ - "service", - map[string]interface{}{ - "name": "腾讯黑岩云主机", - "short_name": "高性能云主机", - "kind_id": 3, - "manu_id": 1, - "price_options": []string{"按月订阅"}, - }, - } - process := gou.NewProcess("xiang.table.Save", args...) - response := ProcessSave(process) - assert.NotNil(t, response) - assert.True(t, any.Of(response).IsInt()) - - id := any.Of(response).CInt() - args = []interface{}{ - "service", - id, - "id", - map[string]interface{}{ - "name": "腾讯黑岩云主机UP", - }, - } - process = gou.NewProcess("xiang.table.UpdateIn", args...) - response = ProcessUpdateIn(process) - - assert.NotNil(t, response) - assert.True(t, any.Of(response).IsInt()) - assert.Equal(t, any.Of(response).CInt(), 1) - - // 清空数据 - capsule.Query().Table("service").Where("id", id).Delete() -} - -func TestTableProcessSetting(t *testing.T) { - args := []interface{}{"service", ""} - process := gou.NewProcess("xiang.table.Setting", args...) - response := ProcessSetting(process) - assert.NotNil(t, response) - res := any.Of(response).Map() - assert.Equal(t, res.Get("name"), "云服务库") - assert.True(t, res.Has("title")) - assert.True(t, res.Has("decription")) - assert.True(t, res.Has("columns")) - assert.True(t, res.Has("filters")) - assert.True(t, res.Has("list")) - assert.True(t, res.Has("edit")) - assert.True(t, res.Has("view")) - assert.True(t, res.Has("insert")) -} -func TestTableProcessSettingList(t *testing.T) { - args := []interface{}{"service", "list"} - process := gou.NewProcess("xiang.table.Setting", args...) - response := ProcessSetting(process) - assert.NotNil(t, response) - res := any.Of(response).Map() - assert.True(t, res.Has("actions")) - assert.True(t, res.Has("layout")) - assert.True(t, res.Has("primary")) -} - -func TestTableProcessSettingListEdit(t *testing.T) { - args := []interface{}{"service", "list, edit"} - process := gou.NewProcess("xiang.table.Setting", args...) - response := ProcessSetting(process) - assert.NotNil(t, response) - res := any.Of(response).MapStr().Dot() - assert.True(t, res.Has("list.actions")) - assert.True(t, res.Has("list.layout")) - assert.True(t, res.Has("list.primary")) - assert.True(t, res.Has("edit.actions")) - assert.True(t, res.Has("edit.layout")) - assert.True(t, res.Has("edit.primary")) -} - -func TestTableProcessQuickSave(t *testing.T) { - args := []interface{}{ - "service", - map[string]interface{}{ - "name": "腾讯黑岩云主机", - "short_name": "高性能云主机", - "kind_id": 3, - "manu_id": 1, - "price_options": []string{"按月订阅"}, - }, - } - process := gou.NewProcess("xiang.table.Save", args...) - response := ProcessSave(process) - assert.NotNil(t, response) - assert.True(t, any.Of(response).IsInt()) - - id := any.Of(response).CInt() - args = []interface{}{ - "service", - id, - } - - process = gou.NewProcess("xiang.table.QuickSave", - "service", - map[string]interface{}{ - "delete": []int{id}, - "data": []map[string]interface{}{ - { - "name": "腾讯黑岩云主机2", - "short_name": "高性能云主机2", - "kind_id": 3, - "manu_id": 1, - "price_options": []string{"按月订阅"}, - }, - }, - "query": map[string]interface{}{"manu_id": 1}, - }) - res := process.Run() - newID, ok := res.([]interface{}) - assert.True(t, ok) - assert.NotEqual(t, id, newID[0]) - - // 清空数据 - capsule.Query().Table("service").WhereIn("id", []interface{}{id, newID[0]}).Delete() -} - -func TestTableProcessSelect(t *testing.T) { - args := []interface{}{ - "service", - map[string]interface{}{ - "name": "腾讯黑岩云主机", - "short_name": "高性能云主机", - "kind_id": 3, - "manu_id": 1, - "price_options": []string{"按月订阅"}, - }, - } - process := gou.NewProcess("xiang.table.Save", args...) - response := ProcessSave(process) - assert.NotNil(t, response) - assert.True(t, any.Of(response).IsInt()) - - id := any.Of(response).CInt() - - args = []interface{}{"service", "腾讯", "name", "id"} - - data := gou.NewProcess("xiang.table.select", args...).Run().([]maps.MapStrAny) - assert.Greater(t, len(data), 1) - for _, row := range data { - assert.Contains(t, row.Get("name"), "腾讯") - } - - // 清空数据 - capsule.Query().Table("service").WhereIn("id", []int{id}).Delete() -} - -func TestTableProcessSelectWithHook(t *testing.T) { - args := []interface{}{ - "service", - map[string]interface{}{ - "name": "腾讯黑岩云主机", - "short_name": "高性能云主机", - "kind_id": 3, - "manu_id": 1, - "price_options": []string{"按月订阅"}, - }, - } - process := gou.NewProcess("xiang.table.Save", args...) - response := ProcessSave(process) - assert.NotNil(t, response) - assert.True(t, any.Of(response).IsInt()) - - id := any.Of(response).CInt() - - args = []interface{}{"hooks.select"} - - data := gou.NewProcess("xiang.table.select", args...).Run().([]maps.MapStrAny) - assert.Greater(t, len(data), 1) - for _, row := range data { - assert.Contains(t, row.Get("name"), "腾讯") - assert.Equal(t, float64(100), row.Get("after")) - } - - // 清空数据 - capsule.Query().Table("service").WhereIn("id", []int{id}).Delete() -} - -func TestTableProcessExport(t *testing.T) { - - args := []interface{}{ - "service", - gou.QueryParam{Wheres: []gou.QueryWhere{{Column: "status", Value: "enabled"}}}, - 2, - } - response := gou.NewProcess("xiang.table.Export", args...).Run() - assert.NotNil(t, response) - // fmt.Println(response) - // res := any.Of(response).Map() - // assert.True(t, res.Has("data")) - // assert.True(t, res.Has("next")) - // assert.True(t, res.Has("page")) - // assert.True(t, res.Has("pagecnt")) - // assert.True(t, res.Has("pagesize")) - // assert.True(t, res.Has("prev")) - // assert.True(t, res.Has("total")) - // assert.Equal(t, 1, res.Get("page")) - // assert.Equal(t, 2, res.Get("pagesize")) -} - -func TestTableProcessExportWithHook(t *testing.T) { - - args := []interface{}{"hooks.search"} - response := gou.NewProcess("xiang.table.Export", args...).Run() - - assert.NotNil(t, response) - // res := any.Of(response).Map() - // assert.True(t, res.Has("data")) - // assert.True(t, res.Has("next")) - // assert.True(t, res.Has("page")) - // assert.True(t, res.Has("pagecnt")) - // assert.True(t, res.Has("pagesize")) - // assert.True(t, res.Has("prev")) - // assert.True(t, res.Has("total")) - // assert.Equal(t, 1, res.Get("page")) - // assert.Equal(t, 2, res.Get("pagesize")) - // assert.Equal(t, float64(100), res.Get("after")) -} - -func TestTableProcessExportWithScriptHook(t *testing.T) { - // testData() - args := []interface{}{"hooks.search_script"} - response := gou.NewProcess("xiang.table.Export", args...).Run() - // utils.Dump(response) - - assert.NotNil(t, response) - // res := any.Of(response).Map() - // assert.True(t, res.Has("data")) - // assert.True(t, res.Has("next")) - // assert.True(t, res.Has("page")) - // assert.True(t, res.Has("pagecnt")) - // assert.True(t, res.Has("pagesize")) - // assert.True(t, res.Has("prev")) - // assert.True(t, res.Has("total")) - // assert.Equal(t, 1, res.Get("page")) - // assert.Equal(t, 2, res.Get("pagesize")) - // assert.Equal(t, float64(100), res.Get("after")) -} - -func testData() { - m := gou.Select("service") - data := [][]interface{}{} - for i := 0; i < 2000; i++ { - col := []interface{}{fmt.Sprintf("NAME-%d", i), 1, 1} - data = append(data, col) - } - - m.DestroyWhere(gou.QueryParam{ - Wheres: []gou.QueryWhere{ - {Column: "id", OP: "ge", Value: 0}, - }, - }) - err := m.Insert([]string{"name", "kind_id", "manu_id"}, data) - fmt.Println(err) -} diff --git a/table/table.go b/table/table.go deleted file mode 100644 index 452abd713a..0000000000 --- a/table/table.go +++ /dev/null @@ -1,486 +0,0 @@ -package table - -import ( - "errors" - "fmt" - "io" - "os" - "path/filepath" - "strings" - - "github.com/gin-gonic/gin" - jsoniter "github.com/json-iterator/go" - "github.com/xuri/excelize/v2" - "github.com/yaoapp/gou" - "github.com/yaoapp/gou/helper" - "github.com/yaoapp/gou/lang" - "github.com/yaoapp/kun/any" - "github.com/yaoapp/kun/exception" - "github.com/yaoapp/kun/log" - "github.com/yaoapp/kun/maps" - "github.com/yaoapp/yao/config" - "github.com/yaoapp/yao/share" - "github.com/yaoapp/yao/xfs" -) - -// Tables 已载入模型 -var Tables = map[string]*Table{} - -// apiNames mapping -var apiNames = map[string]string{ - "/:name/search": "search", - "/:name/find/:id": "find", - "/:name/save": "save", - "/:name/delete/:id": "delete", - "/:name/insert": "insert", - "/:name/delete/in": "delete-in", - "/:name/delete/where": "delete-where", - "/:name/update/in": "update-in", - "/:name/update/where": "update-where", - "/:name/quicksave": "quicksave", - "/:name/select": "select", -} - -// Guard Table guard -func Guard(c *gin.Context) { - - if !strings.HasPrefix(c.FullPath(), "/api/xiang/table") { - c.Next() - return - } - - log.Trace("Table Guard FullPath: %s", c.FullPath()) - - routes := strings.Split(c.FullPath(), "/") - if len(routes) < 4 { - log.Trace("Table Guard Routes: %v", routes) - c.Next() - return - } - - path := "/" + strings.Join(routes[4:], "/") - apiName, has := apiNames[path] - if !has { - log.Trace("Table Guard API Name: %v", path) - c.Next() - return - } - - name, has := c.Params.Get("name") - if !has { - log.Trace("Table Guard Name: %v", c.Params) - c.Next() - return - } - - table, has := Tables[name] - if !has { - log.Trace("Table Guard Table: %s", name) - c.Next() - return - } - - api, has := table.APIs[apiName] - if !has { - log.Trace("Table Guard API: %s", apiName) - c.Next() - return - } - - log.Trace("Table Guard: %s %s %s %s", name, api.Guard, path, apiName) - - if api.Guard == "-" { - c.Next() - return - } - - if api.Guard == "" { - api.Guard = "bearer-jwt" - } - - guards := strings.Split(api.Guard, ",") - for _, guard := range guards { - guard = strings.TrimSpace(guard) - log.Trace("Table Guard: %s %s", name, guard) - if guard != "" { - if middleware, has := gou.HTTPGuards[guard]; has { - middleware(c) - continue - } - gou.ProcessGuard(guard)(c) - } - } - -} - -// Load 加载数据表格 -func Load(cfg config.Config) error { - if share.BUILDIN { - return LoadBuildIn("tables", "") - } - return LoadFrom(filepath.Join(cfg.Root, "tables"), "") -} - -// LoadFrom 从特定目录加载 -func LoadFrom(dir string, prefix string) error { - - if share.DirNotExists(dir) { - return fmt.Errorf("%s does not exists", dir) - } - - messages := []string{} - err := share.Walk(dir, ".json", func(root, filename string) { - name := share.SpecName(root, filename) - content := share.ReadFile(filename) - _, err := LoadTable(string(content), name) - if err != nil { - log.With(log.F{"root": root, "file": filename}).Error(err.Error()) - messages = append(messages, fmt.Sprintf("%s %s", name, err.Error())) - } - }) - - if len(messages) > 0 { - return fmt.Errorf("%s", strings.Join(messages, ";")) - } - - return err -} - -// LoadBuildIn 从制品中读取 -func LoadBuildIn(dir string, prefix string) error { - return nil -} - -// LoadTable 载入数据表格 -func LoadTable(source string, name string) (*Table, error) { - var input io.Reader = nil - if strings.HasPrefix(source, "file://") || strings.HasPrefix(source, "fs://") { - filename := strings.TrimPrefix(source, "file://") - filename = strings.TrimPrefix(filename, "fs://") - file, err := os.Open(filename) - if err != nil { - return nil, err - } - defer file.Close() - input = file - } else { - input = strings.NewReader(source) - } - - table := Table{ - Source: source, - Table: name, - } - err := helper.UnmarshalFile(input, &table) - if err != nil { - // exception.Err(err, 400).Ctx(maps.Map{"name": name}).Throw() - return &table, err - } - - table.loadColumns() - table.loadFilters() - table.loadAPIs() - - err = table.Validate() - if err != nil { - log.Error("[Table] %s is not valid: %s ", table.Table, err.Error()) - return nil, err - } - - Tables[name] = &table - - // Apply a language pack - if lang.Default != nil { - lang.Default.Apply(Tables[name]) - } - - return Tables[name], nil -} - -// Select 读取已加载表格配置 -func Select(name string) *Table { - tab, has := Tables[name] - if !has { - exception.New( - fmt.Sprintf("Table:%s; 尚未加载", name), - 400, - ).Throw() - } - return tab -} - -// Reload 更新数据表格配置 -func (table *Table) Reload() (*Table, error) { - new, err := LoadTable(table.Source, table.Name) - if err != nil { - return nil, err - } - *table = *new - return table, nil -} - -// loadAPIs 加载数据管理 API -func (table *Table) loadAPIs() { - if table.Bind.Model == "" { - return - } - defaults := getDefaultAPIs(table.Bind) - defaults["setting"] = apiDefaultSetting() - - for name := range table.APIs { - if _, has := defaults[name]; !has { - delete(table.APIs, name) - continue - } - - api := defaults[name] - api.Name = name - if table.APIs[name].Process != "" { - api.Process = table.APIs[name].Process - } - - api.Guard = "bearer-jwt" - if table.APIs[name].Guard != "" { - api.Guard = table.APIs[name].Guard - } - - if table.APIs[name].Default != nil { - // fmt.Printf("\n%s.APIs[%s].Default: entry\n", table.Table, name) - if len(table.APIs[name].Default) == len(api.Default) { - for i := range table.APIs[name].Default { - // fmt.Printf("%s.APIs[%s].Default[%d]:%v\n", table.Table, name, i, table.APIs[name].Default[i]) - if table.APIs[name].Default[i] != nil { - api.Default[i] = table.APIs[name].Default[i] - } - } - } - } - - defaults[name] = api - } - - table.APIs = defaults -} - -// getDefaultAPIs 读取数据模型绑定的APIs -func getDefaultAPIs(bind Bind) map[string]share.API { - name := bind.Model - model := gou.Select(name) - apis := map[string]share.API{ - "search": apiSearchDefault(model, bind.Withs), - "find": apiFindDefault(model, bind.Withs), - "save": apiDefault(model, "save", "Save"), - "delete": apiDefault(model, "delete", "Delete"), - "insert": apiDefault(model, "insert", "Insert"), - "delete-in": apiDefault(model, "delete-in", "DeleteWhere"), - "delete-where": apiDefaultWhere(model, bind.Withs, "delete-where", "DeleteWhere"), - "update-in": apiDefault(model, "update-in", "UpdateWhere"), - "update-where": apiDefaultWhere(model, bind.Withs, "update-where", "UpdateWhere"), - "quicksave": apiDefault(model, "quicksave", "EachSaveAfterDelete"), // 批量保存 - "select": apiDefault(model, "select", "SelectOption"), // 选择 - } - - return apis -} - -// Before 运行 Before hook -func (table *Table) Before(process string, processArgs []interface{}, sid string) []interface{} { - if process == "" { - return processArgs - } - args := []interface{}{} - res := []interface{}{} - if len(processArgs) > 0 { - args = processArgs[1:] - res = append(res, processArgs[0]) - } - - response, err := gou.NewProcess(process, args...).WithSID(sid).Exec() - if err != nil { - log.With(log.F{"process": process, "args": args}).Warn("Hook执行失败: %s", err.Error()) - return processArgs - } - - if fixedArgs, ok := response.([]interface{}); ok { - res = append(res, fixedArgs...) - return res - } - - log.With(log.F{"process": process, "args": args}).Warn("Hook执行失败: 无效的处理器") - return processArgs -} - -// After 运行 After hook -func (table *Table) After(process string, data interface{}, args []interface{}, sid string) interface{} { - if process == "" { - return data - } - args = append([]interface{}{data}, args...) - response, err := gou.NewProcess(process, args...).WithSID(sid).Exec() - if err != nil { - log.With(log.F{"process": process, "args": args}).Warn("Hook执行失败: %s", err.Error()) - return data - } - return response -} - -// loadFilters 加载查询过滤器 -func (table *Table) loadFilters() { - if table.Bind.Model == "" { - return - } - defaults := share.GetDefaultFilters(table.Bind.Model) - for name, filter := range table.Filters { - defaults[name] = filter - } - table.Filters = defaults -} - -// loadColumns 加载字段呈现方式 -func (table *Table) loadColumns() { - if table.Bind.Model == "" { - return - } - defaults := share.GetDefaultColumns(table.Bind.Model) - for name, column := range table.Columns { - defaults[name] = column - } - table.Columns = defaults -} - -// Export Export query result to Excel -func (table *Table) Export(filename string, data interface{}, page int, chunkSize int) error { - - debug := os.Getenv("YAO_EXPORT_DEBUG") != "" - - if debug { - bytes, _ := jsoniter.Marshal(data) - log.Info("[Export] %s %d %d Before: %s", filename, page, chunkSize, string(bytes)) - } - - rows := []maps.MapStr{} - if values, ok := data.([]maps.MapStrAny); ok { - for _, row := range values { - rows = append(rows, row.Dot()) - } - } else if values, ok := data.([]map[string]interface{}); ok { - for _, row := range values { - rows = append(rows, maps.Of(row).Dot()) - } - } else if values, ok := data.([]interface{}); ok { - for _, row := range values { - rows = append(rows, any.Of(row).MapStr().Dot()) - } - } - - if debug { - bytes, _ := jsoniter.Marshal(rows) - log.Info("[Export] %s %d %d After: %s", filename, page, chunkSize, string(bytes)) - } - - columns, err := table.exportSetting() - if err != nil { - return err - } - - if len(columns) == 0 { - return fmt.Errorf("the table does not support export") - } - - filename = filepath.Join(xfs.Stor.Root, filename) - if _, err := os.Stat(filename); errors.Is(err, os.ErrNotExist) { - f := excelize.NewFile() - index := f.GetActiveSheetIndex() - name := f.GetSheetName(index) - f.SetSheetName(name, table.Name) - for i, column := range columns { - axis, err := excelize.CoordinatesToCellName(i+1, 1) - if err != nil { - return err - } - f.SetCellValue(table.Name, axis, column["name"]) - } - if err := f.SaveAs(filename); err != nil { - fmt.Println(err) - return err - } - } - - f, err := excelize.OpenFile(filename) - if err != nil { - return err - } - - defer f.Close() - offset := (page-1)*chunkSize + 2 - for line, row := range rows { - for i, column := range columns { - v := row.Get(column["field"]) - if v != nil { - axis, err := excelize.CoordinatesToCellName(i+1, line+offset) - if err != nil { - return err - } - f.SetCellValue(table.Name, axis, v) - } - } - // fmt.Println("--", line, page, offset, "--") - } - - return f.Save() -} - -func (table *Table) exportSetting() ([]map[string]string, error) { - // Validate params - if table.List.Layout == nil { - return nil, fmt.Errorf("the table layout does not found") - } - - columns, has := table.List.Layout["columns"] - if !has { - return nil, fmt.Errorf("the columns table layout does not found") - } - - fields, ok := columns.([]interface{}) - if !ok { - return nil, fmt.Errorf("Table Layout columns format error") - } - - setting := []map[string]string{} - for _, field := range fields { - f, ok := field.(map[string]interface{}) - if !ok { - continue - } - - n, has := f["name"] - if !has { - continue - } - - name, ok := n.(string) - if !ok { - continue - } - - column, has := table.Columns[name] - if !has { - continue - } - - field := column.Export - if field == "" { - if value, has := column.View.Props["value"]; has { - if valueStr, ok := value.(string); ok { - field = strings.TrimPrefix(valueStr, ":") - } - } - } - - if field != "" && name != "" { - setting = append(setting, map[string]string{"name": name, "field": field}) - } - } - - return setting, nil -} diff --git a/table/table_test.go b/table/table_test.go deleted file mode 100644 index 566ceb596c..0000000000 --- a/table/table_test.go +++ /dev/null @@ -1,64 +0,0 @@ -package table - -import ( - "testing" - - "github.com/stretchr/testify/assert" - - "github.com/yaoapp/yao/config" - "github.com/yaoapp/yao/model" - "github.com/yaoapp/yao/share" -) - -func TestLoad(t *testing.T) { - - share.DBConnect(config.Conf.DB) - share.Load(config.Conf) - model.Load(config.Conf) - - Tables = make(map[string]*Table) - Load(config.Conf) - LoadFrom("not a path", "404.") - check(t) - - table, has := Tables["service"] - assert.Equal(t, table.Table, "service") - assert.True(t, has) - - _, has = table.Columns["id"] - assert.True(t, has) - - price, has := table.Columns["计费方式"] - assert.True(t, has) - if has { - assert.True(t, price.Edit.Props["multiple"].(bool)) - } - - _, has = table.Filters["id"] - assert.True(t, has) - - keywords, has := table.Filters["关键词"] - assert.True(t, has) - if has { - assert.True(t, keywords.Bind == "where.name.like") - } -} - -func check(t *testing.T) { - keys := []string{} - for key := range Tables { - keys = append(keys, key) - } - assert.Equal(t, 11, len(keys)) - - // demo := Select("demo") - // utils.Dump(demo) - - // assert.NotNil(t, demo.Columns["類型"]) - // assert.NotNil(t, demo.Columns["類型"].Edit.Props["options"]) - - // options := demo.Columns["類型"].Edit.Props["options"].([]interface{}) - // opt1 := options[0].(map[string]interface{}) - // assert.Equal(t, "貓", opt1["label"]) - -} diff --git a/table/types.go b/table/types.go deleted file mode 100644 index 1df50c15e8..0000000000 --- a/table/types.go +++ /dev/null @@ -1,58 +0,0 @@ -package table - -import ( - "github.com/yaoapp/gou" - "github.com/yaoapp/yao/share" -) - -// Table 数据表格配置结构 -type Table struct { - Table string `json:"-"` - Source string `json:"-"` - Guard string `json:"guard,omitempty"` - Name string `json:"name"` - Version string `json:"version"` - Title string `json:"title,omitempty"` - Decription string `json:"decription,omitempty"` - Bind Bind `json:"bind,omitempty"` - Hooks Hooks `json:"hooks,omitempty"` - APIs map[string]share.API `json:"apis,omitempty"` - Columns map[string]share.Column `json:"columns,omitempty"` - Filters map[string]share.Filter `json:"filters,omitempty"` - List share.Page `json:"list,omitempty"` - Edit share.Page `json:"edit,omitempty"` - View share.Page `json:"view,omitempty"` - Insert share.Page `json:"insert,omitempty"` -} - -// Bind 绑定数据模型 -type Bind struct { - Model string `json:"model"` - Withs map[string]gou.With `json:"withs,omitempty"` -} - -// Hooks 表格数据模型 -type Hooks struct { - BeforeFind string `json:"before:find,omitempty"` - AfterFind string `json:"after:find,omitempty"` - BeforeSearch string `json:"before:search,omitempty"` - AfterSearch string `json:"after:search,omitempty"` - BeforeSave string `json:"before:save,omitempty"` - AfterSave string `json:"after:save,omitempty"` - BeforeDelete string `json:"before:delete,omitempty"` - AfterDelete string `json:"after:delete,omitempty"` - BeforeInsert string `json:"before:insert,omitempty"` - AfterInsert string `json:"after:insert,omitempty"` - BeforeDeleteIn string `json:"before:delete-in,omitempty"` - AfterDeleteIn string `json:"after:delete-in,omitempty"` - BeforeDeleteWhere string `json:"before:delete-where,omitempty"` - AfterDeleteWhere string `json:"after:delete-where,omitempty"` - BeforeUpdateIn string `json:"before:update-in,omitempty"` - AfterUpdateIn string `json:"after:update-in,omitempty"` - BeforeUpdateWhere string `json:"before:update-where,omitempty"` - AfterUpdateWhere string `json:"after:update-where,omitempty"` - BeforeQuicksave string `json:"before:quicksave,omitempty"` - AfterQuicksave string `json:"after:quicksave,omitempty"` - BeforeSelect string `json:"before:select,omitempty"` - AfterSelect string `json:"after:select,omitempty"` -} diff --git a/table/validate.go b/table/validate.go deleted file mode 100644 index 6f5be474f2..0000000000 --- a/table/validate.go +++ /dev/null @@ -1,132 +0,0 @@ -package table - -import "fmt" - -// Validate 校验表格格式 -func (table Table) Validate() error { - err := table.validateList() - if err != nil { - return err - } - - err = table.validateEdit() - if err != nil { - return err - } - - return nil -} - -func (table Table) validateEdit() error { - if table.Edit.Layout == nil { - return nil - } - - fieldset, ok := table.Edit.Layout["fieldset"].([]interface{}) - if !ok { - return fmt.Errorf("edit.layout.columns is required") - } - - for idx, set := range fieldset { - set, ok := set.(map[string]interface{}) - if !ok { - return fmt.Errorf("edit.layout.fieldset.%d format error", idx) - } - - columns, ok := set["columns"].([]interface{}) - if !ok { - return fmt.Errorf("edit.layout.fieldset.%d.columns format error", idx) - } - - for cidx, column := range columns { - col, ismap := column.(map[string]interface{}) - name, isstr := column.(string) - if !ismap && !isstr { - return fmt.Errorf("edit.layout.fieldset.%d.columns.%d format error", idx, cidx) - } - - if ismap { - v, has := col["name"] - if !has { - return fmt.Errorf("edit.layout.fieldset.%d.columns.%d.name is required", idx, cidx) - } - namestr, ok := v.(string) - if !ok { - return fmt.Errorf("edit.layout.fieldset.%d.columns.%d.name format error", idx, cidx) - } - name = namestr - } - - if _, has := table.Columns[name]; !has { - return fmt.Errorf("edit.layout.fieldset.%d.columns.%d.name %s is not found in columns", idx, cidx, name) - } - } - - } - - return nil -} - -func (table Table) validateList() error { - - if table.List.Layout == nil { - return nil - } - - // table.List.Layout - columns, ok := table.List.Layout["columns"].([]interface{}) - if !ok { - return fmt.Errorf("list.layout.columns is required") - } - - for idx, column := range columns { - - col, ismap := column.(map[string]interface{}) - name, isstr := column.(string) - if !ismap && !isstr { - return fmt.Errorf("list.layout.columns.%d format error", idx) - } - - if ismap { - v, has := col["name"] - if !has { - return fmt.Errorf("list.layout.columns.%d.name is required", idx) - } - namestr, ok := v.(string) - if !ok { - return fmt.Errorf("list.layout.columns.%d.name format error", idx) - } - name = namestr - } - - if _, has := table.Columns[name]; !has { - return fmt.Errorf("list.layout.columns.%d.name %s is not found in columns", idx, name) - } - } - - filters, ok := table.List.Layout["filters"].([]interface{}) - if ok { - for idx, filter := range filters { - fli, ok := filter.(map[string]interface{}) - if !ok { - return fmt.Errorf("list.layout.filters.%d format error", idx) - } - - name, has := fli["name"] - if !has { - return fmt.Errorf("list.layout.filters.%d.name is required", idx) - } - - namestr, ok := name.(string) - if !ok { - return fmt.Errorf("list.layout.filters.%d.name format error", idx) - } - - if _, has := table.Filters[namestr]; !has { - return fmt.Errorf("list.layout.filters.%d.name %s is not found in filters", idx, namestr) - } - } - } - - return nil -} diff --git a/task/task.go b/task/task.go index 07d36e7e8b..106483192a 100644 --- a/task/task.go +++ b/task/task.go @@ -1,36 +1,36 @@ package task import ( - "fmt" - "path/filepath" - - "github.com/yaoapp/gou" - "github.com/yaoapp/kun/log" + "github.com/yaoapp/gou/application" + "github.com/yaoapp/gou/task" "github.com/yaoapp/yao/config" "github.com/yaoapp/yao/share" ) // Load load task func Load(cfg config.Config) error { - var root = filepath.Join(cfg.Root, "tasks") - return LoadFrom(root, "") + exts := []string{"*.yao", "*.json", "*.jsonc"} + return application.App.Walk("tasks", func(root, file string, isdir bool) error { + _, err := task.Load(file, share.ID(root, file)) + return err + }, exts...) } -// LoadFrom load from dir -func LoadFrom(dir string, prefix string) error { +// // LoadFrom load from dir +// func LoadFrom(dir string, prefix string) error { - if share.DirNotExists(dir) { - return fmt.Errorf("%s does not exists", dir) - } +// if share.DirNotExists(dir) { +// return fmt.Errorf("%s does not exists", dir) +// } - err := share.Walk(dir, ".json", func(root, filename string) { - name := prefix + share.SpecName(root, filename) - content := share.ReadFile(filename) - _, err := gou.LoadTask(string(content), name) - if err != nil { - log.With(log.F{"root": root, "file": filename}).Error(err.Error()) - } - }) +// err := share.Walk(dir, ".json", func(root, filename string) { +// name := prefix + share.SpecName(root, filename) +// content := share.ReadFile(filename) +// _, err := gou.LoadTask(string(content), name) +// if err != nil { +// log.With(log.F{"root": root, "file": filename}).Error(err.Error()) +// } +// }) - return err -} +// return err +// } diff --git a/task/task_test.go b/task/task_test.go index 71f178a4ec..e1e9781d81 100644 --- a/task/task_test.go +++ b/task/task_test.go @@ -10,7 +10,6 @@ import ( func TestLoad(t *testing.T) { Load(config.Conf) - LoadFrom("not a path", "404.") check(t) } diff --git a/user/captcha.go b/user/captcha.go deleted file mode 100644 index ceaa58421c..0000000000 --- a/user/captcha.go +++ /dev/null @@ -1,134 +0,0 @@ -package user - -import ( - "errors" - "image/color" - - "github.com/mojocn/base64Captcha" - "github.com/yaoapp/kun/exception" - "github.com/yaoapp/kun/log" -) - -var captchaStore = base64Captcha.DefaultMemStore - -// CaptchaOption 验证码配置 -type CaptchaOption struct { - Type string - Height int - Width int - Length int - Lang string - Background string -} - -// NewCaptchaOption 创建验证码配置 -func NewCaptchaOption() CaptchaOption { - return CaptchaOption{ - Width: 240, - Height: 80, - Length: 4, - Lang: "zh", - Background: "#FFFFFF", - } -} - -// MakeCaptcha 制作验证码 -func MakeCaptcha(option CaptchaOption) (string, string) { - - if option.Width == 0 { - option.Width = 240 - } - - if option.Height == 0 { - option.Width = 80 - } - - if option.Length == 0 { - option.Length = 4 - } - - if option.Lang == "" { - option.Lang = "zh" - } - - var driver base64Captcha.Driver - switch option.Type { - case "audio": - driver = base64Captcha.NewDriverAudio(option.Length, option.Lang) - break - case "math": - background := background(option.Background) - driver = base64Captcha.NewDriverMath( - option.Height, option.Width, 3, - base64Captcha.OptionShowHollowLine, background, - base64Captcha.DefaultEmbeddedFonts, []string{}, - ) - break - default: - driver = base64Captcha.NewDriverDigit( - option.Height, option.Width, 5, - 0.7, 80, - ) - break - } - - c := base64Captcha.NewCaptcha(driver, captchaStore) - id, content, err := c.Generate() - if err != nil { - exception.New("生成验证码出错 %s", 500, err).Throw() - } - - log.Debug("图形/音频 ID:%s 验证码:%s", id, captchaStore.Get(id, false)) - return id, content -} - -// ValidateCaptcha 校验验证码 -func ValidateCaptcha(id string, value string) bool { - return captchaStore.Verify(id, value, true) -} - -func background(s string) *color.RGBA { - if s == "" { - s = "#555555" - } - bg, err := parseHexColorFast(s) - if err != nil { - exception.New("背景色格式错误 %s", 400, s).Throw() - } - return &bg -} - -func parseHexColorFast(s string) (c color.RGBA, err error) { - c.A = 0xff - - if s[0] != '#' { - return c, errors.New("invalid format") - } - - hexToByte := func(b byte) byte { - switch { - case b >= '0' && b <= '9': - return b - '0' - case b >= 'a' && b <= 'f': - return b - 'a' + 10 - case b >= 'A' && b <= 'F': - return b - 'A' + 10 - } - err = errors.New("invalid format") - return 0 - } - - switch len(s) { - case 7: - c.R = hexToByte(s[1])<<4 + hexToByte(s[2]) - c.G = hexToByte(s[3])<<4 + hexToByte(s[4]) - c.B = hexToByte(s[5])<<4 + hexToByte(s[6]) - case 4: - c.R = hexToByte(s[1]) * 17 - c.G = hexToByte(s[2]) * 17 - c.B = hexToByte(s[3]) * 17 - default: - err = errors.New("invalid format") - } - return -} diff --git a/user/captcha_test.go b/user/captcha_test.go deleted file mode 100644 index 7c5f604cfe..0000000000 --- a/user/captcha_test.go +++ /dev/null @@ -1,45 +0,0 @@ -package user - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestCaptcha(t *testing.T) { - id, content := MakeCaptcha(CaptchaOption{ - Type: "audio", - Width: 240, - Height: 80, - Length: 4, - Lang: "zh", - }) - assert.IsType(t, "string", id) - assert.IsType(t, "string", content) - captchaStore.Get(id, false) - assert.True(t, ValidateCaptcha(id, captchaStore.Get(id, false))) - - id, content = MakeCaptcha(CaptchaOption{ - Type: "math", - Width: 240, - Height: 80, - Length: 4, - Lang: "zh", - }) - assert.IsType(t, "string", id) - assert.IsType(t, "string", content) - captchaStore.Get(id, false) - assert.True(t, ValidateCaptcha(id, captchaStore.Get(id, false))) - - id, content = MakeCaptcha(CaptchaOption{ - Type: "digit", - Width: 240, - Height: 80, - Length: 4, - Lang: "zh", - }) - assert.IsType(t, "string", id) - assert.IsType(t, "string", content) - captchaStore.Get(id, false) - assert.True(t, ValidateCaptcha(id, captchaStore.Get(id, false))) -} diff --git a/user/process.go b/user/process.go deleted file mode 100644 index ba89385f80..0000000000 --- a/user/process.go +++ /dev/null @@ -1,80 +0,0 @@ -package user - -import ( - "github.com/yaoapp/gou" - "github.com/yaoapp/kun/any" - "github.com/yaoapp/kun/exception" - "github.com/yaoapp/kun/log" - "github.com/yaoapp/kun/maps" -) - -func init() { - gou.RegisterProcessHandler("xiang.user.Captcha", ProcessCaptcha) - gou.RegisterProcessHandler("xiang.user.Login", ProcessLogin) -} - -// ProcessLogin xiang.user.Login 用户登录 -func ProcessLogin(process *gou.Process) interface{} { - process.ValidateArgNums(1) - payload := process.ArgsMap(0).Dot() - log.With(log.F{"payload": payload}).Debug("ProcessLogin") - - id := any.Of(payload.Get("captcha.id")).CString() - value := any.Of(payload.Get("captcha.code")).CString() - if id == "" { - exception.New("请输入验证码ID", 400).Ctx(maps.Map{"id": id, "code": value}).Throw() - } - if value == "" { - exception.New("请输入验证码", 400).Ctx(maps.Map{"id": id, "code": value}).Throw() - } - if !ValidateCaptcha(id, value) { - log.With(log.F{"id": id, "code": value}).Debug("ProcessLogin") - exception.New("验证码不正确", 403).Ctx(maps.Map{"id": id, "code": value}).Throw() - return nil - } - - email := any.Of(payload.Get("email")).CString() - mobile := any.Of(payload.Get("mobile")).CString() - password := any.Of(payload.Get("password")).CString() - if email != "" { - return Auth("email", email, password) - } else if mobile != "" { - return Auth("mobile", mobile, password) - } - - exception.New("参数错误", 400).Ctx(payload).Throw() - return nil -} - -// ProcessCaptcha xiang.user.Captcha 验证码 -func ProcessCaptcha(process *gou.Process) interface{} { - process.ValidateArgNums(1) - option := CaptchaOption{ - Width: any.Of(process.ArgsURLValue(0, "width", "240")).CInt(), - Height: any.Of(process.ArgsURLValue(0, "height", "80")).CInt(), - Length: any.Of(process.ArgsURLValue(0, "height", "4")).CInt(), - Type: process.ArgsURLValue(0, "type", "math"), - Background: process.ArgsURLValue(0, "background", "#FFFFFF"), - Lang: process.ArgsURLValue(0, "lang", "zh"), - } - id, content := MakeCaptcha(option) - return maps.Map{ - "id": id, - "content": content, - } -} - -// ProcessToken xiang.user.Token 使用 Key & Secret 换取 Token -func ProcessToken(process *gou.Process) interface{} { - return nil -} - -// ProcessTokenRefresh xiang.user.TokenRefresh 刷新Token -func ProcessTokenRefresh(process *gou.Process) interface{} { - return nil -} - -// ProcessInfo xiang.user.Info 读取当前用户资料 -func ProcessInfo(process *gou.Process) interface{} { - return nil -} diff --git a/user/user.go b/user/user.go deleted file mode 100644 index df29f11fa1..0000000000 --- a/user/user.go +++ /dev/null @@ -1,85 +0,0 @@ -package user - -import ( - "time" - - "github.com/golang-jwt/jwt" - "github.com/yaoapp/gou" - "github.com/yaoapp/gou/session" - "github.com/yaoapp/kun/any" - "github.com/yaoapp/kun/exception" - "github.com/yaoapp/kun/maps" - "github.com/yaoapp/yao/helper" - "golang.org/x/crypto/bcrypt" -) - -// JwtClaims JWT claims -type JwtClaims struct { - ID int - Type string - Name string - jwt.StandardClaims -} - -var loginTypes = map[string]string{ - "email": "email", - "mobile": "mobile", -} - -// Auth 用户身份鉴权 -func Auth(field string, value string, password string) maps.Map { - column, has := loginTypes[field] - if !has { - exception.New("登录方式(%s)尚未支持", 400, field).Throw() - } - - user := gou.Select("xiang.user") - rows, err := user.Get(gou.QueryParam{ - Select: []interface{}{"id", "password", "name", "type", "email", "mobile", "extra"}, - Limit: 1, - Wheres: []gou.QueryWhere{ - {Column: column, Value: value}, - {Column: "status", Value: "enabled"}, - }, - }) - - if err != nil { - exception.New("数据库查询错误", 500, field).Throw() - } - - if len(rows) == 0 { - exception.New("用户不存在(%s)", 404, value).Throw() - } - - row := rows[0] - passwordHash := row.Get("password").(string) - row.Del("password") - - err = bcrypt.CompareHashAndPassword([]byte(passwordHash), []byte(password)) - if err != nil { - exception.New("登录密码错误", 403, value).Throw() - } - - expiresAt := time.Now().Unix() + 3600 - - // token := MakeToken(row, expiresAt) - sid := session.ID() - id := any.Of(row.Get("id")).CInt() - token := helper.JwtMake(id, map[string]interface{}{}, map[string]interface{}{ - "expires_at": expiresAt, - "sid": sid, - "issuer": "xiang", - }) - session.Global().Expire(time.Duration(token.ExpiresAt)*time.Second).ID(sid).Set("user_id", id) - session.Global().ID(sid).Set("user", row) - session.Global().ID(sid).Set("issuer", "xiang") - - // 读取菜单 - menus := gou.NewProcess("flows.xiang.menu").Run() - return maps.Map{ - "expires_at": token.ExpiresAt, - "token": token.Token, - "user": row, - "menus": menus, - } -} diff --git a/utils/datetime/now.go b/utils/datetime/now.go index 14943978c5..148f225e66 100644 --- a/utils/datetime/now.go +++ b/utils/datetime/now.go @@ -3,30 +3,30 @@ package datetime import ( "time" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" ) // ProcessTimestamp utils.now.Timestamp -func ProcessTimestamp(process *gou.Process) interface{} { +func ProcessTimestamp(process *process.Process) interface{} { return time.Now().Unix() } // ProcessTimestampms utils.now.Timestampms -func ProcessTimestampms(process *gou.Process) interface{} { +func ProcessTimestampms(process *process.Process) interface{} { return time.Now().UnixMilli() } // ProcessDate utils.now.Date -func ProcessDate(process *gou.Process) interface{} { +func ProcessDate(process *process.Process) interface{} { return time.Now().Local().Format("2006-01-02") } // ProcessTime utils.now.Time -func ProcessTime(process *gou.Process) interface{} { +func ProcessTime(process *process.Process) interface{} { return time.Now().Local().Format("15:04:05") } // ProcessDateTime utils.now.DateTime -func ProcessDateTime(process *gou.Process) interface{} { +func ProcessDateTime(process *process.Process) interface{} { return time.Now().Local().Format("2006-01-02 15:04:05") } diff --git a/utils/datetime_test.go b/utils/datetime_test.go index 52d9bbf835..331061f929 100644 --- a/utils/datetime_test.go +++ b/utils/datetime_test.go @@ -5,13 +5,13 @@ import ( "time" "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" ) func TestProcessNow(t *testing.T) { - assert.LessOrEqual(t, time.Now().Unix(), gou.NewProcess("utils.now.Timestamp").Run().(int64)) - assert.LessOrEqual(t, time.Now().UnixMilli(), gou.NewProcess("utils.now.Timestampms").Run().(int64)) - assert.NotNil(t, gou.NewProcess("utils.now.Date").Run()) - assert.NotNil(t, gou.NewProcess("utils.now.Time").Run()) - assert.NotNil(t, gou.NewProcess("utils.now.DateTime").Run()) + assert.LessOrEqual(t, time.Now().Unix(), process.New("utils.now.Timestamp").Run().(int64)) + assert.LessOrEqual(t, time.Now().UnixMilli(), process.New("utils.now.Timestampms").Run().(int64)) + assert.NotNil(t, process.New("utils.now.Date").Run()) + assert.NotNil(t, process.New("utils.now.Time").Run()) + assert.NotNil(t, process.New("utils.now.DateTime").Run()) } diff --git a/utils/process.go b/utils/process.go index db9cd75081..f40d1e8a38 100644 --- a/utils/process.go +++ b/utils/process.go @@ -1,87 +1,87 @@ package utils import ( - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" "github.com/yaoapp/yao/utils/datetime" "github.com/yaoapp/yao/utils/str" "github.com/yaoapp/yao/utils/tree" ) func init() { - gou.AliasProcess("xiang.helper.Captcha", "yao.utils.Captcha") // deprecated - gou.AliasProcess("xiang.helper.CaptchaValidate", "yao.utils.CaptchaValidate") // deprecated + process.Alias("xiang.helper.Captcha", "yao.utils.Captcha") // deprecated + process.Alias("xiang.helper.CaptchaValidate", "yao.utils.CaptchaValidate") // deprecated // **************************************** // * Migrate Processes Version 0.10.2+ // **************************************** // Application - gou.AliasProcess("xiang.main.Ping", "utils.app.Ping") - gou.AliasProcess("xiang.main.Inspect", "utils.app.Inspect") + process.Alias("xiang.main.Ping", "utils.app.Ping") + process.Alias("xiang.main.Inspect", "utils.app.Inspect") // FMT - gou.AliasProcess("xiang.helper.Print", "utils.fmt.Print") + process.Alias("xiang.helper.Print", "utils.fmt.Print") // ENV - gou.AliasProcess("xiang.helper.EnvSet", "utils.env.Get") - gou.AliasProcess("xiang.helper.EnvGet", "utils.env.Get") - gou.AliasProcess("xiang.helper.EnvMultiSet", "utils.env.SetMany") - gou.AliasProcess("xiang.helper.EnvMultiGet", "utils.env.GetMany") + process.Alias("xiang.helper.EnvSet", "utils.env.Get") + process.Alias("xiang.helper.EnvGet", "utils.env.Get") + process.Alias("xiang.helper.EnvMultiSet", "utils.env.SetMany") + process.Alias("xiang.helper.EnvMultiGet", "utils.env.GetMany") // Flow - gou.AliasProcess("xiang.helper.For", "utils.flow.For") - gou.AliasProcess("xiang.helper.Each", "utils.flow.Each") - gou.AliasProcess("xiang.helper.Case", "utils.flow.Case") - gou.AliasProcess("xiang.helper.IF", "utils.flow.IF") - gou.AliasProcess("xiang.helper.Throw", "utils.flow.Throw") - gou.AliasProcess("xiang.helper.Return", "utils.flow.Return") + process.Alias("xiang.helper.For", "utils.flow.For") + process.Alias("xiang.helper.Each", "utils.flow.Each") + process.Alias("xiang.helper.Case", "utils.flow.Case") + process.Alias("xiang.helper.IF", "utils.flow.IF") + process.Alias("xiang.helper.Throw", "utils.flow.Throw") + process.Alias("xiang.helper.Return", "utils.flow.Return") // JWT - gou.AliasProcess("xiang.helper.JwtMake", "utils.jwt.Make") - gou.AliasProcess("xiang.helper.JwtValidate", "utils.jwt.Verify") + process.Alias("xiang.helper.JwtMake", "utils.jwt.Make") + process.Alias("xiang.helper.JwtValidate", "utils.jwt.Verify") // Password // utils.pwd.Hash - gou.AliasProcess("xiang.helper.PasswordValidate", "utils.pwd.Verify") + process.Alias("xiang.helper.PasswordValidate", "utils.pwd.Verify") // Captcha - gou.AliasProcess("xiang.helper.Captcha", "utils.captcha.Make") - gou.AliasProcess("xiang.helper.CaptchaValidate", "utils.captcha.Verify") + process.Alias("xiang.helper.Captcha", "utils.captcha.Make") + process.Alias("xiang.helper.CaptchaValidate", "utils.captcha.Verify") // String - gou.AliasProcess("xiang.helper.StrConcat", "utils.str.Concat") - gou.RegisterProcessHandler("utils.str.Join", str.ProcessJoin) - gou.RegisterProcessHandler("utils.str.JoinPath", str.ProcessJoinPath) + process.Alias("xiang.helper.StrConcat", "utils.str.Concat") + process.Register("utils.str.Join", str.ProcessJoin) + process.Register("utils.str.JoinPath", str.ProcessJoinPath) // Array - gou.AliasProcess("xiang.helper.ArrayPluck", "utils.arr.Pluck") - gou.AliasProcess("xiang.helper.ArraySplit", "utils.arr.Split") - gou.AliasProcess("xiang.helper.ArrayTree", "utils.arr.Tree") - gou.AliasProcess("xiang.helper.ArrayUnique", "utils.arr.Unique") - gou.AliasProcess("xiang.helper.ArrayIndexes", "utils.arr.Indexes") - gou.AliasProcess("xiang.helper.ArrayGet", "utils.arr.Get") - gou.AliasProcess("xiang.helper.ArrayColumn", "utils.arr.Column") // doc - gou.AliasProcess("xiang.helper.ArrayKeep", "utils.arr.Keep") - gou.AliasProcess("xiang.helper.ArrayMapSet", "utils.arr.MapSet") + process.Alias("xiang.helper.ArrayPluck", "utils.arr.Pluck") + process.Alias("xiang.helper.ArraySplit", "utils.arr.Split") + process.Alias("xiang.helper.ArrayTree", "utils.arr.Tree") + process.Alias("xiang.helper.ArrayUnique", "utils.arr.Unique") + process.Alias("xiang.helper.ArrayIndexes", "utils.arr.Indexes") + process.Alias("xiang.helper.ArrayGet", "utils.arr.Get") + process.Alias("xiang.helper.ArrayColumn", "utils.arr.Column") // doc + process.Alias("xiang.helper.ArrayKeep", "utils.arr.Keep") + process.Alias("xiang.helper.ArrayMapSet", "utils.arr.MapSet") // Tree - gou.RegisterProcessHandler("utils.tree.Flatten", tree.ProcessFlatten) + process.Register("utils.tree.Flatten", tree.ProcessFlatten) // Map - gou.AliasProcess("xiang.helper.MapGet", "utils.map.Get") - gou.AliasProcess("xiang.helper.MapSet", "utils.map.Set") - gou.AliasProcess("xiang.helper.MapDel", "utils.map.Del") - gou.AliasProcess("xiang.helper.MapDel", "utils.map.DelMany") - gou.AliasProcess("xiang.helper.MapKeys", "utils.map.Keys") - gou.AliasProcess("xiang.helper.MapValues", "utils.map.Values") - gou.AliasProcess("xiang.helper.MapToArray", "utils.map.Array") // doc + process.Alias("xiang.helper.MapGet", "utils.map.Get") + process.Alias("xiang.helper.MapSet", "utils.map.Set") + process.Alias("xiang.helper.MapDel", "utils.map.Del") + process.Alias("xiang.helper.MapDel", "utils.map.DelMany") + process.Alias("xiang.helper.MapKeys", "utils.map.Keys") + process.Alias("xiang.helper.MapValues", "utils.map.Values") + process.Alias("xiang.helper.MapToArray", "utils.map.Array") // doc // utils.map.Merge // Time - gou.AliasProcess("xiang.flow.Sleep", "utils.time.Sleep") - gou.RegisterProcessHandler("utils.now.Time", datetime.ProcessTime) - gou.RegisterProcessHandler("utils.now.Date", datetime.ProcessDate) - gou.RegisterProcessHandler("utils.now.DateTime", datetime.ProcessDateTime) - gou.RegisterProcessHandler("utils.now.Timestamp", datetime.ProcessTimestamp) - gou.RegisterProcessHandler("utils.now.Timestampms", datetime.ProcessTimestampms) + process.Alias("xiang.flow.Sleep", "utils.time.Sleep") + process.Register("utils.now.Time", datetime.ProcessTime) + process.Register("utils.now.Date", datetime.ProcessDate) + process.Register("utils.now.DateTime", datetime.ProcessDateTime) + process.Register("utils.now.Timestamp", datetime.ProcessTimestamp) + process.Register("utils.now.Timestampms", datetime.ProcessTimestampms) } diff --git a/utils/str/str.go b/utils/str/str.go index 04459d8427..80515c71b8 100644 --- a/utils/str/str.go +++ b/utils/str/str.go @@ -5,11 +5,11 @@ import ( "path/filepath" "strings" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" ) // ProcessJoin utils.str.Join -func ProcessJoin(process *gou.Process) interface{} { +func ProcessJoin(process *process.Process) interface{} { process.ValidateArgNums(2) args := process.ArgsArray(0) sep := process.ArgsString(1) @@ -21,7 +21,7 @@ func ProcessJoin(process *gou.Process) interface{} { } // ProcessJoinPath utils.str.JoinPath -func ProcessJoinPath(process *gou.Process) interface{} { +func ProcessJoinPath(process *process.Process) interface{} { process.ValidateArgNums(2) paths := []string{} for _, arg := range process.Args { diff --git a/utils/str_test.go b/utils/str_test.go index 8c0692899c..a3644b35a8 100644 --- a/utils/str_test.go +++ b/utils/str_test.go @@ -6,16 +6,16 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" ) func TestProcessStrJoin(t *testing.T) { - res := gou.NewProcess("utils.str.Join", []interface{}{"FOO", 20, "BAR"}, ",").Run().(string) + res := process.New("utils.str.Join", []interface{}{"FOO", 20, "BAR"}, ",").Run().(string) assert.Equal(t, "FOO,20,BAR", res) } func TestProcessStrJoinPath(t *testing.T) { - res := gou.NewProcess("utils.str.JoinPath", "data", 20, "app").Run().(string) + res := process.New("utils.str.JoinPath", "data", 20, "app").Run().(string) shouldBe := fmt.Sprintf("data%s20%sapp", string(os.PathSeparator), string(os.PathSeparator)) assert.Equal(t, shouldBe, res) } diff --git a/utils/tree/tree.go b/utils/tree/tree.go index 5906f638e1..5088085c9b 100644 --- a/utils/tree/tree.go +++ b/utils/tree/tree.go @@ -3,11 +3,11 @@ package tree import ( "fmt" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" ) // ProcessFlatten utils.tree.Flatten cast to array -func ProcessFlatten(process *gou.Process) interface{} { +func ProcessFlatten(process *process.Process) interface{} { process.ValidateArgNums(1) array := process.ArgsArray(0) option := process.ArgsMap(1, map[string]interface{}{"primary": "id", "children": "children", "parent": "parent"}) diff --git a/utils/tree_test.go b/utils/tree_test.go index ccdf712a05..4b1a6a45f5 100644 --- a/utils/tree_test.go +++ b/utils/tree_test.go @@ -5,7 +5,7 @@ import ( jsoniter "github.com/json-iterator/go" "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" ) func TestProcessTreeFlatten(t *testing.T) { @@ -26,7 +26,7 @@ func TestProcessTreeFlatten(t *testing.T) { t.Fatal(err) } - rows := gou.NewProcess("utils.tree.Flatten", data, map[string]interface{}{"primary": "id", "children": "children", "parent": "parent"}).Run().([]interface{}) + rows := process.New("utils.tree.Flatten", data, map[string]interface{}{"primary": "id", "children": "children", "parent": "parent"}).Run().([]interface{}) assert.Equal(t, 4, len(rows)) assert.Equal(t, float64(1), rows[1].(map[string]interface{})["parent"]) } diff --git a/websocket/websocket.go b/websocket/websocket.go index 860a0c6ded..991cf40f12 100644 --- a/websocket/websocket.go +++ b/websocket/websocket.go @@ -1,36 +1,38 @@ package websocket import ( - "fmt" - "path/filepath" - - "github.com/yaoapp/gou" - "github.com/yaoapp/kun/log" "github.com/yaoapp/yao/config" - "github.com/yaoapp/yao/share" ) // Load 加载API func Load(cfg config.Config) error { - var root = filepath.Join(cfg.Root, "websockets") - return LoadFrom(root, "") + // exts := []string{"*.http.yao", "*.http.json", "*.http.jsonc"} + // return application.App.Walk("websockets", func(root, file string, isdir bool) error { + // _, err := websocket.Load(file, share.ID(root, file)) + // return err + // }, exts...) + + // var root = filepath.Join(cfg.Root, "websockets") + // return LoadFrom(root, "") + + return nil } -// LoadFrom 从特定目录加载 -func LoadFrom(dir string, prefix string) error { +// // LoadFrom 从特定目录加载 +// func LoadFrom(dir string, prefix string) error { - if share.DirNotExists(dir) { - return fmt.Errorf("%s does not exists", dir) - } +// if share.DirNotExists(dir) { +// return fmt.Errorf("%s does not exists", dir) +// } - err := share.Walk(dir, ".ws.json", func(root, filename string) { - name := prefix + share.SpecName(root, filename) - content := share.ReadFile(filename) - _, err := gou.LoadWebSocket(string(content), name) - if err != nil { - log.With(log.F{"root": root, "file": filename}).Error(err.Error()) - } - }) +// err := share.Walk(dir, ".ws.json", func(root, filename string) { +// name := prefix + share.SpecName(root, filename) +// content := share.ReadFile(filename) +// _, err := gou.LoadWebSocket(string(content), name) +// if err != nil { +// log.With(log.F{"root": root, "file": filename}).Error(err.Error()) +// } +// }) - return err -} +// return err +// } diff --git a/websocket/websocket_test.go b/websocket/websocket_test.go index a2b4fd4c5f..047674cc33 100644 --- a/websocket/websocket_test.go +++ b/websocket/websocket_test.go @@ -8,33 +8,26 @@ import ( "time" "github.com/gin-gonic/gin" - "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" "github.com/yaoapp/gou/websocket" "github.com/yaoapp/yao/config" - "github.com/yaoapp/yao/runtime" - "github.com/yaoapp/yao/script" ) func TestLoad(t *testing.T) { - runtime.Load(config.Conf) Load(config.Conf) - LoadFrom("not a path", "404.") check(t) } func TestWebSocketOpen(t *testing.T) { - runtime.Load(config.Conf) - Load(config.Conf) - script.Load(config.Conf) - srv, url := serve(t) - defer srv.Stop() + // Load(config.Conf) + // script.Load(config.Conf) + // srv, url := serve(t) + // defer srv.Stop() - ws := gou.SelectWebSocket("message") - err := ws.Open(url, "messageV2", "chatV3") - if err != nil { - t.Fatal(err) - } + // ws := websocket.Se("message") + // err := ws.Open(url, "messageV2", "chatV3") + // if err != nil { + // t.Fatal(err) + // } } func serve(t *testing.T) (*websocket.Upgrader, string) { @@ -64,9 +57,9 @@ func serve(t *testing.T) (*websocket.Upgrader, string) { } func check(t *testing.T) { - keys := []string{} - for key := range gou.WebSockets { - keys = append(keys, key) - } - assert.Equal(t, 1, len(keys)) + // keys := []string{} + // for key := range gou.WebSockets { + // keys = append(keys, key) + // } + // assert.Equal(t, 1, len(keys)) } diff --git a/widget/widget.go b/widget/widget.go index 8bd89b0ffd..2acba93cb7 100644 --- a/widget/widget.go +++ b/widget/widget.go @@ -1,107 +1,111 @@ package widget import ( - "errors" - "fmt" - "io/ioutil" - "os" - "path/filepath" - - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/application" "github.com/yaoapp/gou/widget" - "github.com/yaoapp/kun/log" "github.com/yaoapp/yao/config" - "github.com/yaoapp/yao/share" - "github.com/yaoapp/yao/table" ) // Load Widgets func Load(cfg config.Config) error { - var root = filepath.Join(cfg.Root, "widgets") - return LoadFrom(root) + + register := moduleRegister() + + return application.App.Walk("widgets", func(root, file string, isdir bool) error { + if !isdir { + return nil + } + _, err := widget.Load(file, nil, register) + return err + }, config.DSLExtensions...) + + // var root = filepath.Join(cfg.Root, "widgets") + // return LoadFrom(root) } -// LoadFrom widget -func LoadFrom(dir string) error { +// // LoadFrom widget +// func LoadFrom(dir string) error { - register := moduleRegister() +// register := moduleRegister() - if share.DirNotExists(dir) { - return fmt.Errorf("%s does not exists", dir) - } +// if share.DirNotExists(dir) { +// return fmt.Errorf("%s does not exists", dir) +// } - paths, err := ioutil.ReadDir(dir) - if err != nil { - return err - } +// paths, err := ioutil.ReadDir(dir) +// if err != nil { +// return err +// } - for _, path := range paths { +// for _, path := range paths { - if !path.IsDir() { - continue - } +// if !path.IsDir() { +// continue +// } - name := path.Name() - if _, err := os.Stat(filepath.Join(dir, name, "widget.json")); errors.Is(err, os.ErrNotExist) { - // path/to/whatever does not exist - continue - } - w, err := gou.LoadWidget(filepath.Join(dir, name), name, register) - if err != nil { - return err - } +// name := path.Name() +// if _, err := os.Stat(filepath.Join(dir, name, "widget.json")); errors.Is(err, os.ErrNotExist) { +// // path/to/whatever does not exist +// continue +// } +// w, err := gou.LoadWidget(filepath.Join(dir, name), name, register) +// if err != nil { +// return err +// } - // Load instances - err = w.Load() - if err != nil { - return err - } - } +// // Load instances +// err = w.Load() +// if err != nil { +// return err +// } +// } - return err -} +// return err +// } func moduleRegister() widget.ModuleRegister { - return widget.ModuleRegister{ - "Apis": func(name string, source []byte) error { - _, err := gou.LoadAPIReturn(string(source), name) - log.Trace("[Widget] Register api %s", name) - if err != nil { - log.Error("[Widget] Register api %s %v", name, err) - } - return err - }, - "Models": func(name string, source []byte) error { - _, err := gou.LoadModelReturn(string(source), name) - log.Trace("[Widget] Register model %s", name) - if err != nil { - log.Error("[Widget] Register model %s %v", name, err) - } - return err - }, - "Tables": func(name string, source []byte) error { - log.Trace("[Widget] Register table %s", name) - _, err := table.LoadTable(string(source), name) - if err != nil { - log.Error("[Widget] Register table %s %v", name, err) - } - return nil - }, - "Tasks": func(name string, source []byte) error { - log.Trace("[Widget] Register task %s", name) - _, err := gou.LoadTask(string(source), name) - if err != nil { - log.Error("[Widget] Register task %s %v", name, err) - } - return nil - }, - "Schedules": func(name string, source []byte) error { - log.Trace("[Widget] Register schedule %s", name) - _, err := gou.LoadSchedule(string(source), name) - if err != nil { - log.Error("[Widget] Register schedule %s %v", name, err) - } - return nil - }, - } + // return widget.ModuleRegister{ + // "Apis": func(name string, source []byte) error { + // _, err := api.Load(string(source), name) + // log.Trace("[Widget] Register api %s", name) + // if err != nil { + // log.Error("[Widget] Register api %s %v", name, err) + // } + // return err + // }, + // "Models": func(name string, source []byte) error { + // _, err := model.Load(string(source), name) + // log.Trace("[Widget] Register model %s", name) + // if err != nil { + // log.Error("[Widget] Register model %s %v", name, err) + // } + // return err + // }, + // "Tables": func(name string, source []byte) error { + // log.Trace("[Widget] Register table %s", name) + // _, err := table.LoadTable(string(source), name) + // if err != nil { + // log.Error("[Widget] Register table %s %v", name, err) + // } + // return nil + // }, + // "Tasks": func(name string, source []byte) error { + // log.Trace("[Widget] Register task %s", name) + // _, err := gou.LoadTask(string(source), name) + // if err != nil { + // log.Error("[Widget] Register task %s %v", name, err) + // } + // return nil + // }, + // "Schedules": func(name string, source []byte) error { + // log.Trace("[Widget] Register schedule %s", name) + // _, err := gou.LoadSchedule(string(source), name) + // if err != nil { + // log.Error("[Widget] Register schedule %s %v", name, err) + // } + // return nil + // }, + // } + + return nil } diff --git a/widget/widget_test.go b/widget/widget_test.go index 1c45425a12..819384ac7f 100644 --- a/widget/widget_test.go +++ b/widget/widget_test.go @@ -4,19 +4,17 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" "github.com/yaoapp/kun/any" "github.com/yaoapp/yao/config" - "github.com/yaoapp/yao/runtime" "github.com/yaoapp/yao/share" ) func TestLoad(t *testing.T) { - runtime.Load(config.Conf) + // runtime.Load(config.Conf) share.DBConnect(config.Conf.DB) // 创建数据库连接 Load(config.Conf) - LoadFrom("not a path") - v, err := gou.NewProcess("widgets.dyform.Save", "pad", "pay").Exec() + v, err := process.New("widgets.dyform.Save", "pad", "pay").Exec() if err != nil { t.Fatal(err) } diff --git a/widgets/action/action_test.go b/widgets/action/action_test.go index 21dcfccdf4..c836fa0043 100644 --- a/widgets/action/action_test.go +++ b/widgets/action/action_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" ) func TestNewProcess(t *testing.T) { @@ -46,7 +46,7 @@ func testData() map[string]*Process { } } -func testHandler(p *Process, process *gou.Process) (interface{}, error) { +func testHandler(p *Process, process *process.Process) (interface{}, error) { args := p.Args(process) return args, nil } diff --git a/widgets/action/guard.go b/widgets/action/guard.go index 965ce060d0..3346cde51c 100644 --- a/widgets/action/guard.go +++ b/widgets/action/guard.go @@ -4,7 +4,7 @@ import ( "strings" "github.com/gin-gonic/gin" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/api" "github.com/yaoapp/kun/log" ) @@ -19,11 +19,11 @@ func (p *Process) UseGuard(c *gin.Context, id string) error { } if guard != "" { - if middleware, has := gou.HTTPGuards[guard]; has { + if middleware, has := api.HTTPGuards[guard]; has { middleware(c) continue } - gou.ProcessGuard(guard)(c) + api.ProcessGuard(guard)(c) } } return nil diff --git a/widgets/action/process.go b/widgets/action/process.go index 52bada6e02..ecca6798d5 100644 --- a/widgets/action/process.go +++ b/widgets/action/process.go @@ -4,7 +4,7 @@ import ( "fmt" "strings" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" "github.com/yaoapp/gou/session" "github.com/yaoapp/kun/any" "github.com/yaoapp/kun/exception" @@ -103,7 +103,7 @@ func (p *Process) WithAfter(after *hook.After) *Process { } // Args get the process args -func (p *Process) Args(process *gou.Process) []interface{} { +func (p *Process) Args(process *process.Process) []interface{} { process.ValidateArgNums(1) args := []interface{}{} args = append(args, p.Default...) @@ -122,7 +122,7 @@ func (p *Process) Args(process *gou.Process) []interface{} { } // Exec exec the process -func (p *Process) Exec(process *gou.Process) (interface{}, error) { +func (p *Process) Exec(process *process.Process) (interface{}, error) { if p.Handler == nil { return nil, fmt.Errorf("%s handler does not set", p.Name) } @@ -130,7 +130,7 @@ func (p *Process) Exec(process *gou.Process) (interface{}, error) { } // MustExec exec the process -func (p *Process) MustExec(process *gou.Process) interface{} { +func (p *Process) MustExec(process *process.Process) interface{} { res, err := p.Exec(process) if err != nil { exception.New(err.Error(), 500).Throw() diff --git a/widgets/action/types.go b/widgets/action/types.go index 6050e18232..33ceb82f6e 100644 --- a/widgets/action/types.go +++ b/widgets/action/types.go @@ -1,7 +1,7 @@ package action import ( - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" "github.com/yaoapp/yao/widgets/hook" ) @@ -19,4 +19,4 @@ type Process struct { } // Handler action handler -type Handler func(p *Process, process *gou.Process) (interface{}, error) +type Handler func(p *Process, process *process.Process) (interface{}, error) diff --git a/widgets/api.go b/widgets/api.go index 1562c4cf0a..5ada74bfed 100644 --- a/widgets/api.go +++ b/widgets/api.go @@ -5,7 +5,7 @@ import ( "os" "strings" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/api" "github.com/yaoapp/yao/widgets/chart" "github.com/yaoapp/yao/widgets/form" "github.com/yaoapp/yao/widgets/list" @@ -35,7 +35,7 @@ func userApis(apis map[string]interface{}) { // Group string `json:"group,omitempty"` // Guard string `json:"guard,omitempty"` // Paths []Path `json:"paths,omitempty"` - for group, api := range gou.APIs { + for group, api := range api.APIs { if strings.HasPrefix(group, "widgets") { continue } @@ -85,7 +85,7 @@ func userApis(apis map[string]interface{}) { func tableApis(apis map[string]interface{}) { - api, has := gou.APIs["widgets.table"] + api, has := api.APIs["widgets.table"] if !has { return } @@ -115,7 +115,7 @@ func tableApis(apis map[string]interface{}) { func formApis(apis map[string]interface{}) { - api, has := gou.APIs["widgets.form"] + api, has := api.APIs["widgets.form"] if !has { return } @@ -138,7 +138,7 @@ func formApis(apis map[string]interface{}) { func listApis(apis map[string]interface{}) { - api, has := gou.APIs["widgets.list"] + api, has := api.APIs["widgets.list"] if !has { return } @@ -158,7 +158,7 @@ func listApis(apis map[string]interface{}) { func chartApis(apis map[string]interface{}) { - api, has := gou.APIs["widgets.chart"] + api, has := api.APIs["widgets.chart"] if !has { return } @@ -173,10 +173,10 @@ func chartApis(apis map[string]interface{}) { } } -func widgetApis(apis map[string]interface{}, api *gou.API, widgetID string, dsl string, groupGuard string, pathGuards []map[string]string) { +func widgetApis(apis map[string]interface{}, apiInst *api.API, widgetID string, dsl string, groupGuard string, pathGuards []map[string]string) { - pathMapping := map[string]gou.Path{} - for _, path := range api.HTTP.Paths { + pathMapping := map[string]api.Path{} + for _, path := range apiInst.HTTP.Paths { pathMapping[path.Path] = path } @@ -203,7 +203,7 @@ func widgetApis(apis map[string]interface{}, api *gou.API, widgetID string, dsl guard = groupGuard } - fullpath := fmt.Sprintf("/apis/%s%s", api.HTTP.Group, path.Path) + fullpath := fmt.Sprintf("/apis/%s%s", apiInst.HTTP.Group, path.Path) paths = append(paths, map[string]interface{}{ "name": path.Label, "description": path.Description, @@ -221,11 +221,11 @@ func widgetApis(apis map[string]interface{}, api *gou.API, widgetID string, dsl apis[dsl] = map[string]interface{}{ "DSL": dsl, - "name": api.HTTP.Name, - "version": api.HTTP.Version, - "group": fmt.Sprintf("/%s", api.HTTP.Group), + "name": apiInst.HTTP.Name, + "version": apiInst.HTTP.Version, + "group": fmt.Sprintf("/%s", apiInst.HTTP.Group), "guard": groupGuard, - "description": api.HTTP.Description, + "description": apiInst.HTTP.Description, "paths": paths, } } diff --git a/widgets/app/app.go b/widgets/app/app.go index 7b86efc4e0..1db118a4a7 100644 --- a/widgets/app/app.go +++ b/widgets/app/app.go @@ -6,12 +6,12 @@ import ( "os" "path/filepath" "regexp" - "strconv" "strings" "time" jsoniter "github.com/json-iterator/go" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/api" + "github.com/yaoapp/gou/process" "github.com/yaoapp/gou/session" "github.com/yaoapp/kun/exception" "github.com/yaoapp/kun/log" @@ -90,13 +90,13 @@ func exportAPI() error { return fmt.Errorf("the app does not init") } - http := gou.HTTP{ + http := api.HTTP{ Name: "Widget App API", Description: "Widget App API", Version: share.VERSION, Guard: "bearer-jwt", Group: "__yao/app", - Paths: []gou.Path{}, + Paths: []api.Path{}, } process := "yao.app.Xgen" @@ -104,96 +104,96 @@ func exportAPI() error { process = Setting.Setting } - path := gou.Path{ + path := api.Path{ Label: "App Setting", Description: "App Setting", Guard: "-", Path: "/setting", Method: "GET", Process: process, - In: []string{}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) // POST - path = gou.Path{ + path = api.Path{ Label: "App Setting", Description: "App Setting", Guard: "-", Path: "/setting", Method: "POST", Process: process, - In: []string{":payload"}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{":payload"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) process = "yao.app.Menu" - args := []string{} + args := []interface{}{} if Setting.Menu.Process != "" { if Setting.Menu.Args != nil { args = Setting.Menu.Args } } - path = gou.Path{ + path = api.Path{ Label: "App Menu", Description: "App Menu", Path: "/menu", Method: "GET", Process: process, In: args, - Out: gou.Out{Status: 200, Type: "application/json"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) process = "yao.app.Icons" - path = gou.Path{ + path = api.Path{ Label: "App Icons", Description: "App Icons", Path: "/icons/:name", Guard: "-", Method: "GET", Process: process, - In: []string{"$param.name"}, - Out: gou.Out{Status: 200}, + In: []interface{}{"$param.name"}, + Out: api.Out{Status: 200}, } http.Paths = append(http.Paths, path) - path = gou.Path{ + path = api.Path{ Label: "Setup", Description: "Setup", Path: "/setup", Guard: "-", Method: "POST", Process: "yao.app.Setup", - In: []string{":payload"}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{":payload"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) - path = gou.Path{ + path = api.Path{ Label: "Check", Description: "Check", Path: "/check", Guard: "-", Method: "POST", Process: "yao.app.Check", - In: []string{":payload"}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{":payload"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) - path = gou.Path{ + path = api.Path{ Label: "Serivce", Description: "Serivce", Path: "/service/:name", Guard: "bearer-jwt", Method: "POST", Process: "yao.app.Service", - In: []string{"$param.name", ":payload"}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{"$param.name", ":payload"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) @@ -204,7 +204,7 @@ func exportAPI() error { } // load apis - _, err = gou.LoadAPIReturn(string(source), "widgets.app") + _, err = api.Load(string(source), "widgets.app") return err } @@ -215,57 +215,58 @@ func Export() error { } func exportProcess() { - gou.RegisterProcessHandler("yao.app.setting", processSetting) - gou.RegisterProcessHandler("yao.app.xgen", processXgen) - gou.RegisterProcessHandler("yao.app.menu", processMenu) - gou.RegisterProcessHandler("yao.app.icons", processIcons) - gou.RegisterProcessHandler("yao.app.setup", processSetup) - gou.RegisterProcessHandler("yao.app.check", processCheck) - gou.RegisterProcessHandler("yao.app.service", processService) + process.Register("yao.app.setting", processSetting) + process.Register("yao.app.xgen", processXgen) + process.Register("yao.app.menu", processMenu) + process.Register("yao.app.icons", processIcons) + process.Register("yao.app.setup", processSetup) + process.Register("yao.app.check", processCheck) + process.Register("yao.app.service", processService) } -func processService(process *gou.Process) interface{} { +func processService(process *process.Process) interface{} { process.ValidateArgNums(2) - service := fmt.Sprintf("__yao_service.%s", process.ArgsString(0)) + // service := fmt.Sprintf("__yao_service.%s", process.ArgsString(0)) payload := process.ArgsMap(1) if payload == nil || len(payload) == 0 { exception.New("content is required", 400).Throw() } - method, ok := payload["method"].(string) - if !ok || service == "" { - exception.New("method is required", 400).Throw() - } + // method, ok := payload["method"].(string) + // if !ok || service == "" { + // exception.New("method is required", 400).Throw() + // } - args := []interface{}{} - if v, ok := payload["args"].([]interface{}); ok { - args = v - } + // args := []interface{}{} + // if v, ok := payload["args"].([]interface{}); ok { + // args = v + // } - req := gou.Yao.New(service, method) - if process.Sid != "" { - req.WithSid(process.Sid) - } + // req := gou.Yao.New(service, method) + // if process.Sid != "" { + // req.WithSid(process.Sid) + // } - res, err := req.Call(args...) - if err != nil { - // parse Exception - code := 500 - message := err.Error() - match := regExcp.FindStringSubmatch(message) - if len(match) > 0 { - code, err = strconv.Atoi(match[1]) - if err == nil { - message = strings.TrimSpace(match[2]) - } - } - exception.New(message, code).Throw() - } + // res, err := req.Call(args...) + // if err != nil { + // // parse Exception + // code := 500 + // message := err.Error() + // match := regExcp.FindStringSubmatch(message) + // if len(match) > 0 { + // code, err = strconv.Atoi(match[1]) + // if err == nil { + // message = strings.TrimSpace(match[2]) + // } + // } + // exception.New(message, code).Throw() + // } + + return nil - return res } -func processCheck(process *gou.Process) interface{} { +func processCheck(process *process.Process) interface{} { process.ValidateArgNums(1) payload := process.ArgsMap(0) time.Sleep(3 * time.Second) @@ -276,7 +277,7 @@ func processCheck(process *gou.Process) interface{} { return nil } -func processSetup(process *gou.Process) interface{} { +func processSetup(process *process.Process) interface{} { process.ValidateArgNums(1) payload := process.ArgsMap(0) time.Sleep(3 * time.Second) @@ -285,7 +286,7 @@ func processSetup(process *gou.Process) interface{} { exception.New("Something error", 500).Throw() } - lang := process.Lang() + lang := session.Lang(process) if sid, has := payload["sid"].(string); has { lang, err := session.Global().ID(sid).Get("__yao_lang") if err != nil { @@ -310,7 +311,7 @@ func processSetup(process *gou.Process) interface{} { } } -func processIcons(process *gou.Process) interface{} { +func processIcons(process *process.Process) interface{} { process.ValidateArgNums(1) name := process.ArgsString(0) file, err := filepath.Abs(filepath.Join(config.Conf.Root, "icons", name)) @@ -324,13 +325,14 @@ func processIcons(process *gou.Process) interface{} { return string(content) } -func processMenu(process *gou.Process) interface{} { +func processMenu(p *process.Process) interface{} { if Setting.Menu.Process != "" { - return gou. - NewProcess(Setting.Menu.Process, process.Args...). - WithGlobal(process.Global). - WithSID(process.Sid). + + return process. + New(Setting.Menu.Process, p.Args...). + WithGlobal(p.Global). + WithSID(p.Sid). Run() } @@ -350,14 +352,14 @@ func processMenu(process *gou.Process) interface{} { "limit": 200, "orders": []map[string]interface{}{{"column": "rank", "option": "asc"}}, } - return gou. - NewProcess("models.xiang.menu.get", args). - WithGlobal(process.Global). - WithSID(process.Sid). + return process. + New("models.xiang.menu.get", args). + WithGlobal(p.Global). + WithSID(p.Sid). Run() } -func processSetting(process *gou.Process) interface{} { +func processSetting(process *process.Process) interface{} { if Setting == nil { exception.New("the app does not init", 500).Throw() return nil @@ -384,7 +386,7 @@ func processSetting(process *gou.Process) interface{} { session.Global().ID(sid).Set("__yao_lang", lang) } - setting, err := i18n.Trans(process.Lang(config.Conf.Lang), []string{"app.app"}, Setting) + setting, err := i18n.Trans(session.Lang(process, config.Conf.Lang), []string{"app.app"}, Setting) if err != nil { exception.New(err.Error(), 500).Throw() } @@ -393,7 +395,7 @@ func processSetting(process *gou.Process) interface{} { return *setting.(*DSL) } -func processXgen(process *gou.Process) interface{} { +func processXgen(process *process.Process) interface{} { if Setting == nil { exception.New("the app does not init", 500).Throw() @@ -444,7 +446,7 @@ func processXgen(process *gou.Process) interface{} { } // Translate - newLayout, err := i18n.Trans(process.Lang(config.Conf.Lang), []string{"login.admin"}, layout) + newLayout, err := i18n.Trans(session.Lang(process, config.Conf.Lang), []string{"login.admin"}, layout) if err != nil { log.Error("[Login] Xgen i18n.Trans login.admin %s", err.Error()) } @@ -481,7 +483,7 @@ func processXgen(process *gou.Process) interface{} { } // Translate - newLayout, err := i18n.Trans(process.Lang(config.Conf.Lang), []string{"login.user"}, layout) + newLayout, err := i18n.Trans(session.Lang(process, config.Conf.Lang), []string{"login.user"}, layout) if err != nil { log.Error("[Login] Xgen %s", err.Error()) } @@ -521,7 +523,7 @@ func processXgen(process *gou.Process) interface{} { xgenSetting["favicon"] = Setting.Favicon } - setting, err := i18n.Trans(process.Lang(config.Conf.Lang), []string{"app.app"}, xgenSetting) + setting, err := i18n.Trans(session.Lang(process, config.Conf.Lang), []string{"app.app"}, xgenSetting) if err != nil { exception.New(err.Error(), 500).Throw() } @@ -563,7 +565,7 @@ func (dsl *DSL) icons(cfg config.Config) { // Permissions get the permission blacklist // {".":[]} -func Permissions(process *gou.Process, widget string, id string) map[string]bool { +func Permissions(process *process.Process, widget string, id string) map[string]bool { permissions := map[string]bool{} sessionData, _ := session.Global().ID(process.Sid).Get("__permissions") data, ok := sessionData.(map[string]interface{}) diff --git a/widgets/app/app_test.go b/widgets/app/app_test.go index 0fe5825e79..ecb374e173 100644 --- a/widgets/app/app_test.go +++ b/widgets/app/app_test.go @@ -5,13 +5,13 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" "github.com/yaoapp/gou/lang" + "github.com/yaoapp/gou/process" + "github.com/yaoapp/gou/session" "github.com/yaoapp/kun/any" "github.com/yaoapp/yao/config" "github.com/yaoapp/yao/flow" "github.com/yaoapp/yao/i18n" - "github.com/yaoapp/yao/runtime" "github.com/yaoapp/yao/script" _ "github.com/yaoapp/yao/utils" "github.com/yaoapp/yao/widgets/login" @@ -119,34 +119,34 @@ func TestExport(t *testing.T) { t.Fatal(err) } - api, has := gou.APIs["widgets.app"] - assert.True(t, has) - assert.Equal(t, 7, len(api.HTTP.Paths)) + // api, has := gou.APIs["widgets.app"] + // assert.True(t, has) + // assert.Equal(t, 7, len(api.HTTP.Paths)) - _, has = gou.ThirdHandlers["yao.app.setting"] - assert.True(t, has) + // _, has = gou.ThirdHandlers["yao.app.setting"] + // assert.True(t, has) - _, has = gou.ThirdHandlers["yao.app.xgen"] - assert.True(t, has) + // _, has = gou.ThirdHandlers["yao.app.xgen"] + // assert.True(t, has) - _, has = gou.ThirdHandlers["yao.app.menu"] - assert.True(t, has) + // _, has = gou.ThirdHandlers["yao.app.menu"] + // assert.True(t, has) - _, has = gou.ThirdHandlers["yao.app.check"] - assert.True(t, has) + // _, has = gou.ThirdHandlers["yao.app.check"] + // assert.True(t, has) - _, has = gou.ThirdHandlers["yao.app.setup"] - assert.True(t, has) + // _, has = gou.ThirdHandlers["yao.app.setup"] + // assert.True(t, has) - _, has = gou.ThirdHandlers["yao.app.service"] - assert.True(t, has) + // _, has = gou.ThirdHandlers["yao.app.service"] + // assert.True(t, has) } func TestProcessSetting(t *testing.T) { loadApp(t) backup := config.Conf.Lang config.Conf.Lang = "en-us" - res, err := gou.NewProcess("yao.app.Setting").Exec() + res, err := process.New("yao.app.Setting").Exec() if err != nil { t.Fatal(err) } @@ -163,7 +163,7 @@ func TestProcessSetting(t *testing.T) { assert.Equal(t, true, setting.Sid != "") // Set - res, err = gou.NewProcess("yao.app.Setting", map[string]interface{}{"lang": "zh-hk", "sid": setting.Sid}).Exec() + res, err = process.New("yao.app.Setting", map[string]interface{}{"lang": "zh-hk", "sid": setting.Sid}).Exec() if err != nil { t.Fatal(err) } @@ -171,7 +171,8 @@ func TestProcessSetting(t *testing.T) { setting2, ok := res.(DSL) assert.Equal(t, setting.Sid, setting2.Sid) - lang := gou.NewProcess("yao.app.Setting").WithSID(setting.Sid).Lang() + p := process.New("yao.app.Setting").WithSID(setting.Sid) + lang := session.Lang(p) assert.Equal(t, "zh-hk", lang) config.Conf.Lang = backup @@ -181,7 +182,7 @@ func TestProcessXgen(t *testing.T) { loadApp(t) backup := config.Conf.Lang config.Conf.Lang = "en-us" - res, err := gou.NewProcess("yao.app.Xgen").Exec() + res, err := process.New("yao.app.Xgen").Exec() if err != nil { t.Fatal(err) } @@ -206,7 +207,7 @@ func TestProcessXgen(t *testing.T) { assert.Equal(t, true, xgen.Get("sid").(string) != "") // Set - res, err = gou.NewProcess("yao.app.Xgen", map[string]interface{}{"lang": "zh-hk", "sid": xgen.Get("sid")}).Exec() + res, err = process.New("yao.app.Xgen", map[string]interface{}{"lang": "zh-hk", "sid": xgen.Get("sid")}).Exec() if err != nil { t.Fatal(err) } @@ -214,14 +215,15 @@ func TestProcessXgen(t *testing.T) { xgen2 := any.Of(res).MapStr().Dot() assert.Equal(t, xgen.Get("sid"), xgen2.Get("sid")) - lang := gou.NewProcess("yao.app.Setting").WithSID(xgen2.Get("sid").(string)).Lang() + p := process.New("yao.app.Setting").WithSID(xgen2.Get("sid").(string)) + lang := session.Lang(p) assert.Equal(t, "zh-hk", lang) config.Conf.Lang = backup } func TestProcessMenu(t *testing.T) { loadApp(t) - res, err := gou.NewProcess("yao.app.Menu").Exec() + res, err := process.New("yao.app.Menu").Exec() if err != nil { t.Fatal(err) } @@ -233,7 +235,7 @@ func TestProcessMenu(t *testing.T) { func TestProcessIcons(t *testing.T) { loadApp(t) - res, err := gou.NewProcess("yao.app.Icons", "app.png").Exec() + res, err := process.New("yao.app.Icons", "app.png").Exec() if err != nil { t.Fatal(err) } @@ -242,31 +244,31 @@ func TestProcessIcons(t *testing.T) { func TestProcessCheck(t *testing.T) { loadApp(t) - res, err := gou.NewProcess("yao.app.Check", map[string]interface{}{}).Exec() + res, err := process.New("yao.app.Check", map[string]interface{}{}).Exec() if err != nil { t.Fatal(err) } assert.Nil(t, res) - _, err = gou.NewProcess("yao.app.Check", map[string]interface{}{"error": "1"}).Exec() + _, err = process.New("yao.app.Check", map[string]interface{}{"error": "1"}).Exec() assert.NotNil(t, err) } func TestProcessSetup(t *testing.T) { loadApp(t) - res, err := gou.NewProcess("yao.app.Setup", map[string]interface{}{"sid": "hello"}).Exec() + res, err := process.New("yao.app.Setup", map[string]interface{}{"sid": "hello"}).Exec() if err != nil { t.Fatal(err) } assert.Equal(t, "http://127.0.0.1:5099/admin/", res.(map[string]interface{})["admin"]) - _, err = gou.NewProcess("yao.app.Setup", map[string]interface{}{"error": "1"}).Exec() + _, err = process.New("yao.app.Setup", map[string]interface{}{"error": "1"}).Exec() assert.NotNil(t, err) } func TestProcessService(t *testing.T) { loadApp(t) - res, err := gou.NewProcess( + res, err := process.New( "yao.app.Service", "foo", map[string]interface{}{"method": "Bar", "args": []interface{}{"hello", "world"}}, @@ -279,7 +281,7 @@ func TestProcessService(t *testing.T) { } func loadApp(t *testing.T) { - runtime.Load(config.Conf) + // runtime.Load(config.Conf) err := script.Load(config.Conf) if err != nil { diff --git a/widgets/app/types.go b/widgets/app/types.go index 4c6ab30f77..dcd81978b9 100644 --- a/widgets/app/types.go +++ b/widgets/app/types.go @@ -20,8 +20,8 @@ type DSL struct { // MenuDSL the menu DSL type MenuDSL struct { - Process string `json:"process,omitempty"` - Args []string `json:"args,omitempty"` + Process string `json:"process,omitempty"` + Args []interface{} `json:"args,omitempty"` } // OptionalDSL the Optional DSL diff --git a/widgets/chart/api.go b/widgets/chart/api.go index 8ff0d61f83..2832c955ce 100644 --- a/widgets/chart/api.go +++ b/widgets/chart/api.go @@ -5,7 +5,7 @@ import ( "github.com/gin-gonic/gin" jsoniter "github.com/json-iterator/go" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/api" "github.com/yaoapp/yao/share" "github.com/yaoapp/yao/widgets/action" ) @@ -61,48 +61,48 @@ func (chart *DSL) getAction(path string) (*action.Process, error) { // export API func exportAPI() error { - http := gou.HTTP{ + http := api.HTTP{ Name: "Widget Chart API", Description: "Widget Chart API", Version: share.VERSION, Guard: "widget-chart", Group: "__yao/chart", - Paths: []gou.Path{}, + Paths: []api.Path{}, } // GET /api/__yao/chart/:id/setting -> Default process: yao.chart.Xgen - path := gou.Path{ + path := api.Path{ Label: "Setting", Description: "Setting", Path: "/:id/setting", Method: "GET", Process: "yao.chart.Setting", - In: []string{"$param.id"}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{"$param.id"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) // GET /api/__yao/chart/:id/data -> Default process: yao.chart.Data $param.id :query - path = gou.Path{ + path = api.Path{ Label: "Data", Description: "Data", Path: "/:id/data", Method: "GET", Process: "yao.chart.Data", - In: []string{"$param.id", ":query"}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{"$param.id", ":query"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) // GET /api/__yao/chart/:id/component/:xpath/:method -> Default process: yao.chart.Component $param.id $param.xpath $param.method :query - path = gou.Path{ + path = api.Path{ Label: "Component", Description: "Component", Path: "/:id/component/:xpath/:method", Method: "GET", Process: "yao.chart.Component", - In: []string{"$param.id", "$param.xpath", "$param.method", ":query"}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{"$param.id", "$param.xpath", "$param.method", ":query"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) @@ -113,6 +113,6 @@ func exportAPI() error { } // load apis - _, err = gou.LoadAPIReturn(string(source), "widgets.chart") + _, err = api.Load(string(source), "widgets.chart") return err } diff --git a/widgets/chart/chart.go b/widgets/chart/chart.go index 31776db704..6633e3018f 100644 --- a/widgets/chart/chart.go +++ b/widgets/chart/chart.go @@ -6,7 +6,7 @@ import ( "strings" jsoniter "github.com/json-iterator/go" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" "github.com/yaoapp/kun/exception" "github.com/yaoapp/yao/config" "github.com/yaoapp/yao/share" @@ -116,8 +116,8 @@ func Get(chart interface{}) (*DSL, error) { switch chart.(type) { case string: id = chart.(string) - case *gou.Process: - id = chart.(*gou.Process).ArgsString(0) + case *process.Process: + id = chart.(*process.Process).ArgsString(0) default: return nil, fmt.Errorf("%v type does not support", chart) } diff --git a/widgets/chart/chart_test.go b/widgets/chart/chart_test.go index ba0d60351e..3e970b25a6 100644 --- a/widgets/chart/chart_test.go +++ b/widgets/chart/chart_test.go @@ -7,7 +7,6 @@ import ( "github.com/yaoapp/yao/config" "github.com/yaoapp/yao/i18n" "github.com/yaoapp/yao/model" - "github.com/yaoapp/yao/runtime" "github.com/yaoapp/yao/script" "github.com/yaoapp/yao/share" ) @@ -22,7 +21,7 @@ func TestLoad(t *testing.T) { } func prepare(t *testing.T, language ...string) { - runtime.Load(config.Conf) + // runtime.Load(config.Conf) i18n.Load(config.Conf) share.DBConnect(config.Conf.DB) // removed later diff --git a/widgets/chart/handler.go b/widgets/chart/handler.go index 5aa6f6bf4e..44169d856b 100644 --- a/widgets/chart/handler.go +++ b/widgets/chart/handler.go @@ -3,7 +3,7 @@ package chart import ( "fmt" - "github.com/yaoapp/gou" + gouProcess "github.com/yaoapp/gou/process" "github.com/yaoapp/kun/log" "github.com/yaoapp/yao/widgets/action" ) @@ -13,7 +13,7 @@ import ( // ******************************** // Life-Circle: Before Hook → Run Process → Compute View → After Hook // Execute Compute View On: Data -func processHandler(p *action.Process, process *gou.Process) (interface{}, error) { +func processHandler(p *action.Process, process *gouProcess.Process) (interface{}, error) { chart, err := Get(process) if err != nil { @@ -51,7 +51,7 @@ func processHandler(p *action.Process, process *gou.Process) (interface{}, error } // Execute Process - act, err := gou.ProcessOf(name, args...) + act, err := gouProcess.Of(name, args...) if err != nil { log.Error("[chart] %s %s -> %s %s", chart.ID, p.Name, name, err.Error()) return nil, fmt.Errorf("[chart] %s %s -> %s %s", chart.ID, p.Name, name, err.Error()) diff --git a/widgets/chart/process.go b/widgets/chart/process.go index 6179599d42..aaec9dc63f 100644 --- a/widgets/chart/process.go +++ b/widgets/chart/process.go @@ -3,20 +3,20 @@ package chart import ( "fmt" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" "github.com/yaoapp/kun/exception" "github.com/yaoapp/yao/widgets/app" ) // Export process func exportProcess() { - gou.RegisterProcessHandler("yao.chart.setting", processSetting) - gou.RegisterProcessHandler("yao.chart.xgen", processXgen) - gou.RegisterProcessHandler("yao.chart.component", processComponent) - gou.RegisterProcessHandler("yao.chart.data", processData) + process.Register("yao.chart.setting", processSetting) + process.Register("yao.chart.xgen", processXgen) + process.Register("yao.chart.component", processComponent) + process.Register("yao.chart.data", processData) } -func processXgen(process *gou.Process) interface{} { +func processXgen(process *process.Process) interface{} { chart := MustGet(process) data := process.ArgsMap(1, map[string]interface{}{}) @@ -29,7 +29,7 @@ func processXgen(process *gou.Process) interface{} { return setting } -func processComponent(process *gou.Process) interface{} { +func processComponent(process *process.Process) interface{} { process.ValidateArgNums(3) chart := MustGet(process) @@ -58,13 +58,13 @@ func processComponent(process *gou.Process) interface{} { return res } -func processSetting(process *gou.Process) interface{} { +func processSetting(process *process.Process) interface{} { chart := MustGet(process) process.Args = append(process.Args, process.Args[0]) // chart name return chart.Action.Setting.MustExec(process) } -func processData(process *gou.Process) interface{} { +func processData(process *process.Process) interface{} { chart := MustGet(process) return chart.Action.Data.MustExec(process) } diff --git a/widgets/chart/process_test.go b/widgets/chart/process_test.go index b9f85449d8..ab75e2b6c9 100644 --- a/widgets/chart/process_test.go +++ b/widgets/chart/process_test.go @@ -5,7 +5,8 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/model" + "github.com/yaoapp/gou/process" "github.com/yaoapp/gou/session" "github.com/yaoapp/kun/any" "github.com/yaoapp/kun/maps" @@ -16,7 +17,7 @@ import ( func TestProcessData(t *testing.T) { load(t) args := []interface{}{"dashboard", map[string]interface{}{"range": "2022-01-02", "status": "checked"}} - res, err := gou.NewProcess("yao.chart.Data", args...).Exec() + res, err := process.New("yao.chart.Data", args...).Exec() if err != nil { t.Fatal(err) } @@ -33,7 +34,7 @@ func TestProcessComponent(t *testing.T) { map[string]interface{}{"select": []string{"name", "status"}, "limit": 2}, } - res, err := gou.NewProcess("yao.chart.Component", args...).Exec() + res, err := process.New("yao.chart.Component", args...).Exec() if err != nil { t.Fatal(err) } @@ -55,14 +56,14 @@ func TestProcessComponentError(t *testing.T) { "remote", map[string]interface{}{"select": []string{"name", "status"}, "limit": 2}, } - _, err := gou.NewProcess("yao.chart.Component", args...).Exec() + _, err := process.New("yao.chart.Component", args...).Exec() assert.Contains(t, err.Error(), "fields.filter.edit.props.状态.::not-exist") } func TestProcessSetting(t *testing.T) { load(t) args := []interface{}{"dashboard"} - res, err := gou.NewProcess("yao.chart.Setting", args...).Exec() + res, err := process.New("yao.chart.Setting", args...).Exec() if err != nil { t.Fatal(err) } @@ -74,7 +75,7 @@ func TestProcessSetting(t *testing.T) { func TestProcessXgen(t *testing.T) { load(t) args := []interface{}{"dashboard"} - res, err := gou.NewProcess("yao.chart.Xgen", args...).Exec() + res, err := process.New("yao.chart.Xgen", args...).Exec() if err != nil { t.Fatal(err) } @@ -94,7 +95,7 @@ func TestProcessXgenWithPermissions(t *testing.T) { }) args := []interface{}{"dashboard"} - res, err := gou.NewProcess("yao.chart.Xgen", args...).Exec() + res, err := process.New("yao.chart.Xgen", args...).Exec() if err != nil { t.Fatal(err) } @@ -106,7 +107,7 @@ func TestProcessXgenWithPermissions(t *testing.T) { assert.Equal(t, nil, data.Get("fields.chart.综合评分")) session.Global().Set("__permissions", nil) - res, err = gou.NewProcess("yao.chart.Xgen", args...).Exec() + res, err = process.New("yao.chart.Xgen", args...).Exec() if err != nil { t.Fatal(err) } @@ -130,7 +131,7 @@ func load(t *testing.T) { } func testData(t *testing.T) { - pet := gou.Select("pet") + pet := model.Select("pet") err := pet.Insert( []string{"name", "type", "status", "mode", "stay", "cost", "doctor_id"}, [][]interface{}{ @@ -145,7 +146,7 @@ func testData(t *testing.T) { } func clear(t *testing.T) { - for _, m := range gou.Models { + for _, m := range model.Models { err := m.DropTable() if err != nil { t.Fatal(err) diff --git a/widgets/component/compute.go b/widgets/component/compute.go index bf6636c212..05173a885a 100644 --- a/widgets/component/compute.go +++ b/widgets/component/compute.go @@ -6,7 +6,7 @@ import ( "strings" jsoniter "github.com/json-iterator/go" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" "github.com/yaoapp/kun/maps" ) @@ -42,7 +42,7 @@ func (compute *Compute) Value(data maps.MapStr, sid string, global map[string]in } // Run process - process, err := gou.ProcessOf(compute.Process, args...) + process, err := process.Of(compute.Process, args...) if err != nil { return nil, err } diff --git a/widgets/component/process.go b/widgets/component/process.go index 940208da59..812387d976 100644 --- a/widgets/component/process.go +++ b/widgets/component/process.go @@ -5,29 +5,30 @@ import ( "strings" jsoniter "github.com/json-iterator/go" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/model" + "github.com/yaoapp/gou/process" "github.com/yaoapp/kun/any" "github.com/yaoapp/kun/exception" ) // Export process func exportProcess() { - gou.RegisterProcessHandler("yao.component.selectoptions", processSelectOptions) + process.Register("yao.component.selectoptions", processSelectOptions) } -func processSelectOptions(process *gou.Process) interface{} { +func processSelectOptions(process *process.Process) interface{} { process.ValidateArgNums(1) query := process.ArgsMap(0, map[string]interface{}{}) if !query.Has("model") { exception.New("query.model required", 400).Throw() } - model, ok := query.Get("model").(string) + modelName, ok := query.Get("model").(string) if !ok { exception.New("query.model must be a string", 400).Throw() } - m := gou.Select(model) + m := model.Select(modelName) valueField := query.Get("value") if valueField == nil { @@ -55,10 +56,10 @@ func processSelectOptions(process *gou.Process) interface{} { } } - wheres := []gou.QueryWhere{} + wheres := []model.QueryWhere{} switch input := query.Get("wheres").(type) { case string: - where := gou.QueryWhere{} + where := model.QueryWhere{} err := jsoniter.Unmarshal([]byte(input), &where) if err != nil { exception.New("query.wheres error %s", 400, err.Error()).Throw() @@ -68,7 +69,7 @@ func processSelectOptions(process *gou.Process) interface{} { case []string: for _, data := range input { - where := gou.QueryWhere{} + where := model.QueryWhere{} err := jsoniter.Unmarshal([]byte(data), &where) if err != nil { exception.New("query.wheres error %s", 400, err.Error()).Throw() @@ -89,7 +90,7 @@ func processSelectOptions(process *gou.Process) interface{} { } } - rows, err := m.Get(gou.QueryParam{ + rows, err := m.Get(model.QueryParam{ Select: []interface{}{valueField, labelField}, Wheres: wheres, Limit: limit, diff --git a/widgets/component/props.go b/widgets/component/props.go index 65fd0fe914..1e633be42a 100644 --- a/widgets/component/props.go +++ b/widgets/component/props.go @@ -6,7 +6,8 @@ import ( "strings" jsoniter "github.com/json-iterator/go" - "github.com/yaoapp/gou" + gouProcess "github.com/yaoapp/gou/process" + "github.com/yaoapp/gou/types" "github.com/yaoapp/kun/log" ) @@ -26,7 +27,7 @@ func (cProp CloudPropsDSL) UploadPath() string { } // ExecUpload execute upload -func (cProp CloudPropsDSL) ExecUpload(process *gou.Process, upload gou.UploadFile) (interface{}, error) { +func (cProp CloudPropsDSL) ExecUpload(process *gouProcess.Process, upload types.UploadFile) (interface{}, error) { if upload.TempFile == "" { log.Error("[component] %s.$%s upload file is required", cProp.Xpath, cProp.Name) @@ -41,7 +42,7 @@ func (cProp CloudPropsDSL) ExecUpload(process *gou.Process, upload gou.UploadFil } // Create process - p, err := gou.ProcessOf(name, upload) + p, err := gouProcess.Of(name, upload) if err != nil { log.Error("[component] %s.$%s %s", cProp.Xpath, cProp.Name, err.Error()) return nil, fmt.Errorf("[component] %s.$%s %s", cProp.Xpath, cProp.Name, err.Error()) @@ -58,7 +59,7 @@ func (cProp CloudPropsDSL) ExecUpload(process *gou.Process, upload gou.UploadFil } // ExecQuery execute query -func (cProp CloudPropsDSL) ExecQuery(process *gou.Process, query map[string]interface{}) (interface{}, error) { +func (cProp CloudPropsDSL) ExecQuery(process *gouProcess.Process, query map[string]interface{}) (interface{}, error) { if query == nil { query = map[string]interface{}{} @@ -80,7 +81,7 @@ func (cProp CloudPropsDSL) ExecQuery(process *gou.Process, query map[string]inte } // Create process - p, err := gou.ProcessOf(name, query) + p, err := gouProcess.Of(name, query) if err != nil { log.Error("[component] %s.$%s %s", cProp.Xpath, cProp.Name, err.Error()) return nil, fmt.Errorf("[component] %s.$%s %s", cProp.Xpath, cProp.Name, err.Error()) diff --git a/widgets/compute/compute.go b/widgets/compute/compute.go index 901d7a6059..5cdcc91f75 100644 --- a/widgets/compute/compute.go +++ b/widgets/compute/compute.go @@ -5,7 +5,7 @@ import ( "reflect" "strings" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" "github.com/yaoapp/kun/any" "github.com/yaoapp/kun/maps" "github.com/yaoapp/yao/widgets/field" @@ -14,7 +14,7 @@ import ( var views = map[string]bool{"find": true, "get": true, "search": true, "data": true} // ComputeEdit edit compute edit -func (c *Computable) ComputeEdit(name string, process *gou.Process, args []interface{}, getField func(string) (*field.ColumnDSL, string, string, error)) error { +func (c *Computable) ComputeEdit(name string, process *process.Process, args []interface{}, getField func(string) (*field.ColumnDSL, string, string, error)) error { namer := strings.Split(strings.ToLower(name), ".") name = namer[len(namer)-1] @@ -86,7 +86,7 @@ func (c *Computable) ComputeEdit(name string, process *gou.Process, args []inter } // EditRow edit row -func (c *Computable) editRow(process *gou.Process, res map[string]interface{}, getField func(string) (*field.ColumnDSL, string, string, error)) error { +func (c *Computable) editRow(process *process.Process, res map[string]interface{}, getField func(string) (*field.ColumnDSL, string, string, error)) error { messages := []string{} row := maps.MapOf(res).Dot() @@ -121,7 +121,7 @@ func (c *Computable) editRow(process *gou.Process, res map[string]interface{}, g } // EditRows edit row -func (c *Computable) editRows(process *gou.Process, columns []string, res [][]interface{}, getField func(string) (*field.ColumnDSL, string, string, error)) error { +func (c *Computable) editRows(process *process.Process, columns []string, res [][]interface{}, getField func(string) (*field.ColumnDSL, string, string, error)) error { messages := []string{} keys := map[string]int{} @@ -157,7 +157,7 @@ func (c *Computable) editRows(process *gou.Process, columns []string, res [][]in } // ComputeView view view -func (c *Computable) ComputeView(name string, process *gou.Process, res interface{}, getField func(string) (*field.ColumnDSL, string, string, error)) error { +func (c *Computable) ComputeView(name string, process *process.Process, res interface{}, getField func(string) (*field.ColumnDSL, string, string, error)) error { namer := strings.Split(strings.ToLower(name), ".") name = namer[len(namer)-1] @@ -180,7 +180,7 @@ func (c *Computable) ComputeView(name string, process *gou.Process, res interfac } // ViewRows viewrows -func (c *Computable) viewRows(name string, process *gou.Process, res interface{}, getField func(string) (*field.ColumnDSL, string, string, error)) error { +func (c *Computable) viewRows(name string, process *process.Process, res interface{}, getField func(string) (*field.ColumnDSL, string, string, error)) error { switch res.(type) { case []interface{}: @@ -214,7 +214,7 @@ func (c *Computable) viewRows(name string, process *gou.Process, res interface{} } // ViewRow row -func (c *Computable) viewRow(name string, process *gou.Process, res map[string]interface{}, getField func(string) (*field.ColumnDSL, string, string, error)) error { +func (c *Computable) viewRow(name string, process *process.Process, res map[string]interface{}, getField func(string) (*field.ColumnDSL, string, string, error)) error { messages := []string{} row := maps.MapOf(res).Dot() @@ -263,6 +263,6 @@ func (c *Computable) viewRow(name string, process *gou.Process, res map[string]i } // ComputeFilter filter -func (c *Computable) ComputeFilter(name string, process *gou.Process, args []interface{}, getFilter func(string) (*field.FilterDSL, string, string, error)) error { +func (c *Computable) ComputeFilter(name string, process *process.Process, args []interface{}, getFilter func(string) (*field.FilterDSL, string, string, error)) error { return nil } diff --git a/widgets/dashboard/api.go b/widgets/dashboard/api.go index f3e380fc28..afbdc7ab2e 100644 --- a/widgets/dashboard/api.go +++ b/widgets/dashboard/api.go @@ -5,7 +5,7 @@ import ( "github.com/gin-gonic/gin" jsoniter "github.com/json-iterator/go" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/api" "github.com/yaoapp/yao/share" "github.com/yaoapp/yao/widgets/action" ) @@ -61,48 +61,48 @@ func (dashboard *DSL) getAction(path string) (*action.Process, error) { // export API func exportAPI() error { - http := gou.HTTP{ + http := api.HTTP{ Name: "Widget Dashboard API", Description: "Widget Dashboard API", Version: share.VERSION, Guard: "widget-dashboard", Group: "__yao/dashboard", - Paths: []gou.Path{}, + Paths: []api.Path{}, } // GET /api/__yao/dashboard/:id/setting -> Default process: yao.dashboard.Xgen - path := gou.Path{ + path := api.Path{ Label: "Setting", Description: "Setting", Path: "/:id/setting", Method: "GET", Process: "yao.dashboard.Setting", - In: []string{"$param.id"}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{"$param.id"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) // GET /api/__yao/dashboard/:id/data -> Default process: yao.dashboard.Data $param.id :query - path = gou.Path{ + path = api.Path{ Label: "Data", Description: "Data", Path: "/:id/data", Method: "GET", Process: "yao.dashboard.Data", - In: []string{"$param.id", ":query"}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{"$param.id", ":query"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) // GET /api/__yao/dashboard/:id/component/:xpath/:method -> Default process: yao.dashboard.Component $param.id $param.xpath $param.method :query - path = gou.Path{ + path = api.Path{ Label: "Component", Description: "Component", Path: "/:id/component/:xpath/:method", Method: "GET", Process: "yao.dashboard.Component", - In: []string{"$param.id", "$param.xpath", "$param.method", ":query"}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{"$param.id", "$param.xpath", "$param.method", ":query"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) @@ -113,6 +113,6 @@ func exportAPI() error { } // load apis - _, err = gou.LoadAPIReturn(string(source), "widgets.dashboard") + _, err = api.Load(string(source), "widgets.dashboard") return err } diff --git a/widgets/dashboard/dashboard.go b/widgets/dashboard/dashboard.go index 44227f819e..7a83fe8949 100644 --- a/widgets/dashboard/dashboard.go +++ b/widgets/dashboard/dashboard.go @@ -6,7 +6,7 @@ import ( "strings" jsoniter "github.com/json-iterator/go" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" "github.com/yaoapp/kun/exception" "github.com/yaoapp/yao/config" "github.com/yaoapp/yao/share" @@ -116,8 +116,8 @@ func Get(dashboard interface{}) (*DSL, error) { switch dashboard.(type) { case string: id = dashboard.(string) - case *gou.Process: - id = dashboard.(*gou.Process).ArgsString(0) + case *process.Process: + id = dashboard.(*process.Process).ArgsString(0) default: return nil, fmt.Errorf("%v type does not support", dashboard) } diff --git a/widgets/dashboard/dashboard_test.go b/widgets/dashboard/dashboard_test.go index 33e7c08ae5..4b035ffbc7 100644 --- a/widgets/dashboard/dashboard_test.go +++ b/widgets/dashboard/dashboard_test.go @@ -8,7 +8,6 @@ import ( "github.com/yaoapp/yao/flow" "github.com/yaoapp/yao/i18n" "github.com/yaoapp/yao/model" - "github.com/yaoapp/yao/runtime" "github.com/yaoapp/yao/script" "github.com/yaoapp/yao/share" ) @@ -23,7 +22,7 @@ func TestLoad(t *testing.T) { } func prepare(t *testing.T, language ...string) { - runtime.Load(config.Conf) + // runtime.Load(config.Conf) i18n.Load(config.Conf) share.DBConnect(config.Conf.DB) // removed later diff --git a/widgets/dashboard/handler.go b/widgets/dashboard/handler.go index 780e37226a..8cc99df496 100644 --- a/widgets/dashboard/handler.go +++ b/widgets/dashboard/handler.go @@ -3,7 +3,7 @@ package dashboard import ( "fmt" - "github.com/yaoapp/gou" + gouProcess "github.com/yaoapp/gou/process" "github.com/yaoapp/kun/log" "github.com/yaoapp/yao/widgets/action" ) @@ -13,7 +13,7 @@ import ( // ******************************** // Life-Circle: Before Hook → Run Process → Compute View → After Hook // Execute Compute View On: Data -func processHandler(p *action.Process, process *gou.Process) (interface{}, error) { +func processHandler(p *action.Process, process *gouProcess.Process) (interface{}, error) { dashboard, err := Get(process) if err != nil { @@ -51,7 +51,7 @@ func processHandler(p *action.Process, process *gou.Process) (interface{}, error } // Execute Process - act, err := gou.ProcessOf(name, args...) + act, err := gouProcess.Of(name, args...) if err != nil { log.Error("[dashboard] %s %s -> %s %s", dashboard.ID, p.Name, name, err.Error()) return nil, fmt.Errorf("[dashboard] %s %s -> %s %s", dashboard.ID, p.Name, name, err.Error()) diff --git a/widgets/dashboard/process.go b/widgets/dashboard/process.go index 9a8d5c111d..a85fc521fe 100644 --- a/widgets/dashboard/process.go +++ b/widgets/dashboard/process.go @@ -3,20 +3,20 @@ package dashboard import ( "fmt" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" "github.com/yaoapp/kun/exception" "github.com/yaoapp/yao/widgets/app" ) // Export process func exportProcess() { - gou.RegisterProcessHandler("yao.dashboard.setting", processSetting) - gou.RegisterProcessHandler("yao.dashboard.xgen", processXgen) - gou.RegisterProcessHandler("yao.dashboard.component", processComponent) - gou.RegisterProcessHandler("yao.dashboard.data", processData) + process.Register("yao.dashboard.setting", processSetting) + process.Register("yao.dashboard.xgen", processXgen) + process.Register("yao.dashboard.component", processComponent) + process.Register("yao.dashboard.data", processData) } -func processXgen(process *gou.Process) interface{} { +func processXgen(process *process.Process) interface{} { dashboard := MustGet(process) data := process.ArgsMap(1, map[string]interface{}{}) @@ -29,7 +29,7 @@ func processXgen(process *gou.Process) interface{} { return setting } -func processComponent(process *gou.Process) interface{} { +func processComponent(process *process.Process) interface{} { process.ValidateArgNums(3) dashboard := MustGet(process) @@ -58,13 +58,13 @@ func processComponent(process *gou.Process) interface{} { return res } -func processSetting(process *gou.Process) interface{} { +func processSetting(process *process.Process) interface{} { dashboard := MustGet(process) process.Args = append(process.Args, process.Args[0]) // dashboard name return dashboard.Action.Setting.MustExec(process) } -func processData(process *gou.Process) interface{} { +func processData(process *process.Process) interface{} { dashboard := MustGet(process) return dashboard.Action.Data.MustExec(process) } diff --git a/widgets/dashboard/process_test.go b/widgets/dashboard/process_test.go index ff46e2614f..673ed6c28c 100644 --- a/widgets/dashboard/process_test.go +++ b/widgets/dashboard/process_test.go @@ -5,7 +5,8 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/model" + "github.com/yaoapp/gou/process" "github.com/yaoapp/gou/session" "github.com/yaoapp/kun/any" "github.com/yaoapp/kun/maps" @@ -16,7 +17,7 @@ import ( func TestProcessData(t *testing.T) { load(t) args := []interface{}{"workspace", map[string]interface{}{"range": "2022-01-02", "status": "checked"}} - res, err := gou.NewProcess("yao.dashboard.Data", args...).Exec() + res, err := process.New("yao.dashboard.Data", args...).Exec() if err != nil { t.Fatal(err) } @@ -33,7 +34,7 @@ func TestProcessComponent(t *testing.T) { map[string]interface{}{"select": []string{"name", "status"}, "limit": 2}, } - res, err := gou.NewProcess("yao.dashboard.Component", args...).Exec() + res, err := process.New("yao.dashboard.Component", args...).Exec() if err != nil { t.Fatal(err) } @@ -53,7 +54,7 @@ func TestProcessComponent(t *testing.T) { map[string]interface{}{"foo": "bar"}, } - res2, err := gou.NewProcess("yao.dashboard.Component", args...).Exec() + res2, err := process.New("yao.dashboard.Component", args...).Exec() if err != nil { t.Fatal(err) } @@ -69,7 +70,7 @@ func TestProcessComponent(t *testing.T) { map[string]interface{}{"foo": "bar"}, } - res2, err = gou.NewProcess("yao.dashboard.Component", args...).Exec() + res2, err = process.New("yao.dashboard.Component", args...).Exec() if err != nil { t.Fatal(err) } @@ -88,14 +89,14 @@ func TestProcessComponentError(t *testing.T) { "remote", map[string]interface{}{"select": []string{"name", "status"}, "limit": 2}, } - _, err := gou.NewProcess("yao.dashboard.Component", args...).Exec() + _, err := process.New("yao.dashboard.Component", args...).Exec() assert.Contains(t, err.Error(), "fields.filter.edit.props.状态.::not-exist") } func TestProcessSetting(t *testing.T) { load(t) args := []interface{}{"workspace"} - res, err := gou.NewProcess("yao.dashboard.Setting", args...).Exec() + res, err := process.New("yao.dashboard.Setting", args...).Exec() if err != nil { t.Fatal(err) } @@ -110,7 +111,7 @@ func TestProcessSetting(t *testing.T) { func TestProcessXgen(t *testing.T) { load(t) args := []interface{}{"workspace"} - res, err := gou.NewProcess("yao.dashboard.Xgen", args...).Exec() + res, err := process.New("yao.dashboard.Xgen", args...).Exec() if err != nil { t.Fatal(err) } @@ -134,7 +135,7 @@ func TestProcessXgenWithPermissions(t *testing.T) { }) args := []interface{}{"workspace"} - res, err := gou.NewProcess("yao.dashboard.Xgen", args...).Exec() + res, err := process.New("yao.dashboard.Xgen", args...).Exec() if err != nil { t.Fatal(err) } @@ -147,7 +148,7 @@ func TestProcessXgenWithPermissions(t *testing.T) { assert.Equal(t, nil, data.Get("fields.dashboard.图表展示2")) session.Global().Set("__permissions", nil) - res, err = gou.NewProcess("yao.dashboard.Xgen", args...).Exec() + res, err = process.New("yao.dashboard.Xgen", args...).Exec() if err != nil { t.Fatal(err) } @@ -172,7 +173,7 @@ func load(t *testing.T) { } func testData(t *testing.T) { - pet := gou.Select("pet") + pet := model.Select("pet") err := pet.Insert( []string{"name", "type", "status", "mode", "stay", "cost", "doctor_id"}, [][]interface{}{ @@ -187,7 +188,7 @@ func testData(t *testing.T) { } func clear(t *testing.T) { - for _, m := range gou.Models { + for _, m := range model.Models { err := m.DropTable() if err != nil { t.Fatal(err) diff --git a/widgets/expression/expression.go b/widgets/expression/expression.go index 8f23a9e3a3..6d1476ca5a 100644 --- a/widgets/expression/expression.go +++ b/widgets/expression/expression.go @@ -6,7 +6,7 @@ import ( "regexp" "strings" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" "github.com/yaoapp/kun/any" "github.com/yaoapp/kun/maps" ) @@ -167,18 +167,18 @@ func replace(value string, data maps.MapStrAny) (interface{}, bool) { return value, replaced } -func computeOf(process string, argsvars []string, data maps.MapStrAny) (interface{}, bool) { +func computeOf(processName string, argsvars []string, data maps.MapStrAny) (interface{}, bool) { args := []interface{}{} for _, name := range argsvars { arg, _ := valueOf(strings.TrimSpace(name), data) args = append(args, arg) } - if !strings.Contains(process, ".") { - process = fmt.Sprintf("yao.expression.%s", process) + if !strings.Contains(processName, ".") { + processName = fmt.Sprintf("yao.expression.%s", processName) } - p, err := gou.ProcessOf(process, args...) + p, err := process.Of(processName, args...) if err != nil { return err.Error(), true } diff --git a/widgets/expression/process.go b/widgets/expression/process.go index db221ea4f2..df43b975d9 100644 --- a/widgets/expression/process.go +++ b/widgets/expression/process.go @@ -4,18 +4,18 @@ import ( "fmt" "strings" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" "github.com/yaoapp/kun/any" "github.com/yaoapp/kun/maps" ) // Export process func exportProcess() { - gou.RegisterProcessHandler("yao.expression.selectoption", processSelectOption) - gou.RegisterProcessHandler("yao.expression.trimspace", processTrimSpace) + process.Register("yao.expression.selectoption", processSelectOption) + process.Register("yao.expression.trimspace", processTrimSpace) } -func processSelectOption(process *gou.Process) interface{} { +func processSelectOption(process *process.Process) interface{} { process.ValidateArgNums(1) input := process.Args[0] switch input.(type) { @@ -69,7 +69,7 @@ func processSelectOption(process *gou.Process) interface{} { return []map[string]interface{}{} } -func processTrimSpace(process *gou.Process) interface{} { +func processTrimSpace(process *process.Process) interface{} { process.ValidateArgNums(1) input := process.ArgsString(0) return strings.TrimSpace(input) diff --git a/widgets/form/action.go b/widgets/form/action.go index e1abdcd000..edac2c84dc 100644 --- a/widgets/form/action.go +++ b/widgets/form/action.go @@ -3,7 +3,7 @@ package form import ( "fmt" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/model" "github.com/yaoapp/yao/widgets/action" "github.com/yaoapp/yao/widgets/hook" "github.com/yaoapp/yao/widgets/table" @@ -120,7 +120,7 @@ func (act *ActionDSL) SetDefaultProcess() { } // BindModel bind model -func (act *ActionDSL) BindModel(m *gou.Model) { +func (act *ActionDSL) BindModel(m *model.Model) { name := m.ID act.Find.Bind(fmt.Sprintf("models.%s.Find", name)) diff --git a/widgets/form/api.go b/widgets/form/api.go index 088f98f319..e763690b51 100644 --- a/widgets/form/api.go +++ b/widgets/form/api.go @@ -5,7 +5,7 @@ import ( "github.com/gin-gonic/gin" jsoniter "github.com/json-iterator/go" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/api" "github.com/yaoapp/yao/share" "github.com/yaoapp/yao/widgets/action" ) @@ -73,84 +73,84 @@ func (form *DSL) getAction(path string) (*action.Process, error) { // export API func exportAPI() error { - http := gou.HTTP{ + http := api.HTTP{ Name: "Widget Form API", Description: "Widget Form API", Version: share.VERSION, Guard: "widget-form", Group: "__yao/form", - Paths: []gou.Path{}, + Paths: []api.Path{}, } // GET /api/__yao/form/:id/setting -> Default process: yao.form.Xgen - path := gou.Path{ + path := api.Path{ Label: "Setting", Description: "Setting", Path: "/:id/setting", Method: "GET", Process: "yao.form.Setting", - In: []string{"$param.id"}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{"$param.id"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) // GET /api/__yao/form/:id/find/:primary -> Default process: yao.form.Find $param.id $param.primary :query - path = gou.Path{ + path = api.Path{ Label: "Find", Description: "Find", Path: "/:id/find/:primary", Method: "GET", Process: "yao.form.Find", - In: []string{"$param.id", "$param.primary", ":query-param"}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{"$param.id", "$param.primary", ":query-param"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) // GET /api/__yao/form/:id/component/:xpath/:method -> Default process: yao.form.Component $param.id $param.xpath $param.method :query - path = gou.Path{ + path = api.Path{ Label: "Component", Description: "Component", Path: "/:id/component/:xpath/:method", Method: "GET", Process: "yao.form.Component", - In: []string{"$param.id", "$param.xpath", "$param.method", ":query"}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{"$param.id", "$param.xpath", "$param.method", ":query"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) // POST /api/__yao/form/:id/component/:xpath/:method -> Default process: yao.form.Component $param.id $param.xpath $param.method :payload - path = gou.Path{ + path = api.Path{ Label: "Component", Description: "Component", Path: "/:id/component/:xpath/:method", Method: "POST", Process: "yao.form.Component", - In: []string{"$param.id", "$param.xpath", "$param.method", ":payload"}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{"$param.id", "$param.xpath", "$param.method", ":payload"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) // POST /api/__yao/table/:id/upload/:xpath/:method -> Default process: yao.form.Upload $param.id $param.xpath $param.method $file.file - path = gou.Path{ + path = api.Path{ Label: "Upload", Description: "Upload", Path: "/:id/upload/:xpath/:method", Method: "POST", Process: "yao.form.Upload", - In: []string{"$param.id", "$param.xpath", "$param.method", "$file.file"}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{"$param.id", "$param.xpath", "$param.method", "$file.file"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) // GET /api/__yao/form/:id/download/:field -> Default process: yao.form.Download $param.id $param.xpath $param.field $query.name $query.token - path = gou.Path{ + path = api.Path{ Label: "Download", Description: "Download", Path: "/:id/download/:field", Method: "GET", Process: "yao.form.Download", - In: []string{"$param.id", "$param.field", "$query.name", "$query.token"}, - Out: gou.Out{ + In: []interface{}{"$param.id", "$param.field", "$query.name", "$query.token"}, + Out: api.Out{ Status: 200, Body: "{{content}}", Headers: map[string]string{"Content-Type": "{{type}}"}, @@ -159,50 +159,50 @@ func exportAPI() error { http.Paths = append(http.Paths, path) // POST /api/__yao/form/:id/save -> Default process: yao.form.Save $param.id :payload - path = gou.Path{ + path = api.Path{ Label: "Save", Description: "Save", Path: "/:id/save", Method: "POST", Process: "yao.form.Save", - In: []string{"$param.id", ":payload"}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{"$param.id", ":payload"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) // POST /api/__yao/form/:id/create -> Default process: yao.form.Create $param.id :payload - path = gou.Path{ + path = api.Path{ Label: "Create", Description: "Create", Path: "/:id/create", Method: "POST", Process: "yao.form.Create", - In: []string{"$param.id", ":payload"}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{"$param.id", ":payload"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) // POST /api/__yao/form/:id/update/:primary -> Default process: yao.form.Update $param.id $param.primary :payload - path = gou.Path{ + path = api.Path{ Label: "Update", Description: "Update", Path: "/:id/update/:primary", Method: "POST", Process: "yao.form.Update", - In: []string{"$param.id", "$param.primary", ":payload"}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{"$param.id", "$param.primary", ":payload"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) // POST /api/__yao/form/:id/delete/:primary -> Default process: yao.form.Delete $param.id $param.primary - path = gou.Path{ + path = api.Path{ Label: "Delete", Description: "Delete", Path: "/:id/delete/:primary", Method: "POST", Process: "yao.form.Delete", - In: []string{"$param.id", "$param.primary"}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{"$param.id", "$param.primary"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) @@ -213,6 +213,6 @@ func exportAPI() error { } // load apis - _, err = gou.LoadAPIReturn(string(source), "widgets.form") + _, err = api.Load(string(source), "widgets.form") return err } diff --git a/widgets/form/bind.go b/widgets/form/bind.go index 58aec8dc77..1930567f13 100644 --- a/widgets/form/bind.go +++ b/widgets/form/bind.go @@ -3,7 +3,7 @@ package form import ( "fmt" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/model" "github.com/yaoapp/yao/widgets/table" ) @@ -36,7 +36,7 @@ func (dsl *DSL) Bind() error { func (dsl *DSL) bindModel() error { id := dsl.Action.Bind.Model - m, has := gou.Models[id] + m, has := model.Models[id] if !has { return fmt.Errorf("%s does not exist", id) } diff --git a/widgets/form/fields.go b/widgets/form/fields.go index 08b19bea6a..f9cbe28947 100644 --- a/widgets/form/fields.go +++ b/widgets/form/fields.go @@ -4,14 +4,14 @@ import ( "fmt" "strings" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/model" "github.com/yaoapp/yao/widgets/component" "github.com/yaoapp/yao/widgets/field" "github.com/yaoapp/yao/widgets/table" ) // BindModel bind model -func (fields *FieldsDSL) BindModel(m *gou.Model) error { +func (fields *FieldsDSL) BindModel(m *model.Model) error { fields.formMap = map[string]field.ColumnDSL{} diff --git a/widgets/form/form.go b/widgets/form/form.go index 34e24cbef0..1cc0386cb9 100644 --- a/widgets/form/form.go +++ b/widgets/form/form.go @@ -6,7 +6,7 @@ import ( "strings" jsoniter "github.com/json-iterator/go" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" "github.com/yaoapp/kun/exception" "github.com/yaoapp/kun/log" "github.com/yaoapp/yao/config" @@ -173,8 +173,8 @@ func Get(form interface{}) (*DSL, error) { switch form.(type) { case string: id = form.(string) - case *gou.Process: - id = form.(*gou.Process).ArgsString(0) + case *process.Process: + id = form.(*process.Process).ArgsString(0) default: return nil, fmt.Errorf("%v type does not support", form) } diff --git a/widgets/form/form_test.go b/widgets/form/form_test.go index fa65d06f51..5f965ce4e3 100644 --- a/widgets/form/form_test.go +++ b/widgets/form/form_test.go @@ -8,12 +8,11 @@ import ( "github.com/yaoapp/yao/fs" "github.com/yaoapp/yao/i18n" "github.com/yaoapp/yao/model" - "github.com/yaoapp/yao/runtime" "github.com/yaoapp/yao/script" "github.com/yaoapp/yao/share" - "github.com/yaoapp/yao/table" "github.com/yaoapp/yao/widgets/expression" "github.com/yaoapp/yao/widgets/field" + "github.com/yaoapp/yao/widgets/table" "github.com/yaoapp/yao/widgets/test" ) @@ -28,7 +27,7 @@ func TestLoad(t *testing.T) { func prepare(t *testing.T, language ...string) { - runtime.Load(config.Conf) + // runtime.Load(config.Conf) err := test.LoadEngine(language...) if err != nil { t.Fatal(err) diff --git a/widgets/form/handler.go b/widgets/form/handler.go index 03aa37aea3..e130b7d8b0 100644 --- a/widgets/form/handler.go +++ b/widgets/form/handler.go @@ -4,7 +4,9 @@ import ( "fmt" "strings" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/model" + gouProcess "github.com/yaoapp/gou/process" + "github.com/yaoapp/gou/session" "github.com/yaoapp/kun/log" "github.com/yaoapp/yao/config" "github.com/yaoapp/yao/i18n" @@ -17,7 +19,7 @@ import ( // Life-Circle: Before Hook → Compute Edit → Run Process → Compute View → After Hook // Execute Compute Edit On: Save, Create, Update // Execute Compute View On: Find -func processHandler(p *action.Process, process *gou.Process) (interface{}, error) { +func processHandler(p *action.Process, process *gouProcess.Process) (interface{}, error) { form, err := Get(process) if err != nil { @@ -55,7 +57,7 @@ func processHandler(p *action.Process, process *gou.Process) (interface{}, error } // Execute Process - act, err := gou.ProcessOf(name, args...) + act, err := gouProcess.Of(name, args...) if err != nil { log.Error("[form] %s %s -> %s %s", form.ID, p.Name, name, err.Error()) return nil, fmt.Errorf("[form] %s %s -> %s %s", form.ID, p.Name, name, err.Error()) @@ -95,7 +97,7 @@ func processHandler(p *action.Process, process *gou.Process) (interface{}, error } // translateSetting -func (dsl *DSL) translate(name string, process *gou.Process, data interface{}) (interface{}, error) { +func (dsl *DSL) translate(name string, process *gouProcess.Process, data interface{}) (interface{}, error) { if strings.ToLower(name) != "yao.form.setting" { return data, nil @@ -103,7 +105,7 @@ func (dsl *DSL) translate(name string, process *gou.Process, data interface{}) ( widgets := []string{} if dsl.Action.Bind.Model != "" { - m := gou.Select(dsl.Action.Bind.Model) + m := model.Select(dsl.Action.Bind.Model) widgets = append(widgets, fmt.Sprintf("model.%s", m.ID)) } @@ -116,7 +118,7 @@ func (dsl *DSL) translate(name string, process *gou.Process, data interface{}) ( } widgets = append(widgets, fmt.Sprintf("form.%s", dsl.ID)) - res, err := i18n.Trans(process.Lang(config.Conf.Lang), widgets, data) + res, err := i18n.Trans(session.Lang(process, config.Conf.Lang), widgets, data) if err != nil { return nil, err } diff --git a/widgets/form/layout.go b/widgets/form/layout.go index 1cecc4c85f..52bc4adb14 100644 --- a/widgets/form/layout.go +++ b/widgets/form/layout.go @@ -4,14 +4,14 @@ import ( "fmt" jsoniter "github.com/json-iterator/go" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/model" "github.com/yaoapp/yao/widgets/component" "github.com/yaoapp/yao/widgets/mapping" "github.com/yaoapp/yao/widgets/table" ) // BindModel bind model -func (layout *LayoutDSL) BindModel(m *gou.Model, formID string, fields *FieldsDSL, option map[string]interface{}) { +func (layout *LayoutDSL) BindModel(m *model.Model, formID string, fields *FieldsDSL, option map[string]interface{}) { if layout.Primary == "" { layout.Primary = m.PrimaryKey } diff --git a/widgets/form/process.go b/widgets/form/process.go index d1f6419eac..92cb87385c 100644 --- a/widgets/form/process.go +++ b/widgets/form/process.go @@ -5,8 +5,9 @@ import ( "net/url" "strings" - "github.com/yaoapp/gou" "github.com/yaoapp/gou/fs" + gouProcess "github.com/yaoapp/gou/process" + "github.com/yaoapp/gou/types" "github.com/yaoapp/kun/exception" "github.com/yaoapp/kun/log" "github.com/yaoapp/yao/helper" @@ -15,19 +16,19 @@ import ( // Export process func exportProcess() { - gou.RegisterProcessHandler("yao.form.setting", processSetting) - gou.RegisterProcessHandler("yao.form.xgen", processXgen) - gou.RegisterProcessHandler("yao.form.component", processComponent) - gou.RegisterProcessHandler("yao.form.upload", processUpload) - gou.RegisterProcessHandler("yao.form.download", processDownload) - gou.RegisterProcessHandler("yao.form.find", processFind) - gou.RegisterProcessHandler("yao.form.save", processSave) - gou.RegisterProcessHandler("yao.form.create", processCreate) - gou.RegisterProcessHandler("yao.form.update", processUpdate) - gou.RegisterProcessHandler("yao.form.delete", processDelete) + gouProcess.Register("yao.form.setting", processSetting) + gouProcess.Register("yao.form.xgen", processXgen) + gouProcess.Register("yao.form.component", processComponent) + gouProcess.Register("yao.form.upload", processUpload) + gouProcess.Register("yao.form.download", processDownload) + gouProcess.Register("yao.form.find", processFind) + gouProcess.Register("yao.form.save", processSave) + gouProcess.Register("yao.form.create", processCreate) + gouProcess.Register("yao.form.update", processUpdate) + gouProcess.Register("yao.form.delete", processDelete) } -func processXgen(process *gou.Process) interface{} { +func processXgen(process *gouProcess.Process) interface{} { form := MustGet(process) data := process.ArgsMap(1, map[string]interface{}{}) @@ -40,7 +41,7 @@ func processXgen(process *gou.Process) interface{} { return setting } -func processComponent(process *gou.Process) interface{} { +func processComponent(process *gouProcess.Process) interface{} { process.ValidateArgNums(3) form := MustGet(process) @@ -69,7 +70,7 @@ func processComponent(process *gou.Process) interface{} { return res } -func processDownload(process *gou.Process) interface{} { +func processDownload(process *gouProcess.Process) interface{} { process.ValidateArgNums(4) form := MustGet(process) @@ -97,7 +98,7 @@ func processDownload(process *gou.Process) interface{} { } // Create process - p, err := gou.ProcessOf(name, file) + p, err := gouProcess.Of(name, file) if err != nil { log.Error("[downalod] %s.%s %s", form.ID, field, err.Error()) exception.New("[downalod] %s.%s %s", 400, form.ID, field, err.Error()).Throw() @@ -113,7 +114,7 @@ func processDownload(process *gou.Process) interface{} { return res } -func processUpload(process *gou.Process) interface{} { +func processUpload(process *gouProcess.Process) interface{} { process.ValidateArgNums(4) form := MustGet(process) @@ -128,7 +129,7 @@ func processUpload(process *gou.Process) interface{} { } // $file.file - tmpfile, ok := process.Args[3].(gou.UploadFile) + tmpfile, ok := process.Args[3].(types.UploadFile) if !ok { exception.New("parameters error: %v", 400, process.Args[3]).Throw() } @@ -148,33 +149,33 @@ func processUpload(process *gou.Process) interface{} { return res } -func processSetting(process *gou.Process) interface{} { +func processSetting(process *gouProcess.Process) interface{} { form := MustGet(process) process.Args = append(process.Args, process.Args[0]) // form name return form.Action.Setting.MustExec(process) } -func processSave(process *gou.Process) interface{} { +func processSave(process *gouProcess.Process) interface{} { form := MustGet(process) return form.Action.Save.MustExec(process) } -func processCreate(process *gou.Process) interface{} { +func processCreate(process *gouProcess.Process) interface{} { form := MustGet(process) return form.Action.Create.MustExec(process) } -func processFind(process *gou.Process) interface{} { +func processFind(process *gouProcess.Process) interface{} { form := MustGet(process) return form.Action.Find.MustExec(process) } -func processUpdate(process *gou.Process) interface{} { +func processUpdate(process *gouProcess.Process) interface{} { form := MustGet(process) return form.Action.Update.MustExec(process) } -func processDelete(process *gou.Process) interface{} { +func processDelete(process *gouProcess.Process) interface{} { form := MustGet(process) return form.Action.Delete.MustExec(process) } diff --git a/widgets/form/process_test.go b/widgets/form/process_test.go index e10f19e9e2..3ba8271b0b 100644 --- a/widgets/form/process_test.go +++ b/widgets/form/process_test.go @@ -7,9 +7,11 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" "github.com/yaoapp/gou/fs" + "github.com/yaoapp/gou/model" + "github.com/yaoapp/gou/process" "github.com/yaoapp/gou/session" + "github.com/yaoapp/gou/types" "github.com/yaoapp/kun/any" "github.com/yaoapp/kun/maps" "github.com/yaoapp/yao/config" @@ -24,7 +26,7 @@ func TestProcessFind(t *testing.T) { testData(t) args := []interface{}{"pet", 1} - res, err := gou.NewProcess("yao.form.find", args...).Exec() + res, err := process.New("yao.form.find", args...).Exec() if err != nil { t.Fatal(err) } @@ -47,13 +49,13 @@ func TestProcessSave(t *testing.T) { "doctor_id": 1, }} - res, err := gou.NewProcess("yao.form.Save", args...).Exec() + res, err := process.New("yao.form.Save", args...).Exec() if err != nil { t.Fatal(err) } assert.Equal(t, "4", fmt.Sprintf("%v", res)) - res, err = gou.NewProcess("yao.form.find", "pet", res).Exec() + res, err = process.New("yao.form.find", "pet", res).Exec() if err != nil { t.Fatal(err) } @@ -77,13 +79,13 @@ func TestProcessCreate(t *testing.T) { "doctor_id": 1, }} - res, err := gou.NewProcess("yao.form.Create", args...).Exec() + res, err := process.New("yao.form.Create", args...).Exec() if err != nil { t.Fatal(err) } assert.Equal(t, "6", fmt.Sprintf("%v", res)) - res, err = gou.NewProcess("yao.form.find", "pet", res).Exec() + res, err = process.New("yao.form.find", "pet", res).Exec() if err != nil { t.Fatal(err) } @@ -106,12 +108,12 @@ func TestProcessUpdate(t *testing.T) { "doctor_id": 1, }} - _, err := gou.NewProcess("yao.form.Update", args...).Exec() + _, err := process.New("yao.form.Update", args...).Exec() if err != nil { t.Fatal(err) } - res, err := gou.NewProcess("yao.form.find", "pet", 1).Exec() + res, err := process.New("yao.form.find", "pet", 1).Exec() if err != nil { t.Fatal(err) } @@ -126,12 +128,12 @@ func TestProcessDelete(t *testing.T) { testData(t) args := []interface{}{"pet", 1} - _, err := gou.NewProcess("yao.form.Delete", args...).Exec() + _, err := process.New("yao.form.Delete", args...).Exec() if err != nil { t.Fatal(err) } - _, err = gou.NewProcess("yao.form.find", "pet", 1).Exec() + _, err = process.New("yao.form.find", "pet", 1).Exec() assert.Contains(t, err.Error(), "ID=1") } @@ -146,7 +148,7 @@ func TestProcessComponent(t *testing.T) { map[string]interface{}{"select": []string{"name", "status"}, "limit": 2}, } - res, err := gou.NewProcess("yao.form.Component", args...).Exec() + res, err := process.New("yao.form.Component", args...).Exec() if err != nil { t.Fatal(err) } @@ -170,7 +172,7 @@ func TestProcessComponentError(t *testing.T) { "remote", map[string]interface{}{"select": []string{"name", "status"}, "limit": 2}, } - _, err := gou.NewProcess("yao.form.Component", args...).Exec() + _, err := process.New("yao.form.Component", args...).Exec() assert.Contains(t, err.Error(), "fields.filter.edit.props.状态.::not-exist") } @@ -182,10 +184,10 @@ func TestProcessUpload(t *testing.T) { "pet", "fields.form.相关图片.edit.props", "api", - gou.UploadFile{TempFile: tempFile(t)}, + types.UploadFile{TempFile: tempFile(t)}, } - res, err := gou.NewProcess("yao.form.Upload", args...).Exec() + res, err := process.New("yao.form.Upload", args...).Exec() if err != nil { t.Fatal(err) } @@ -208,7 +210,7 @@ func TestProcessDownload(t *testing.T) { } args := []interface{}{"pet", "images", "/text.txt", jwt.Token} - res, err := gou.NewProcess("yao.form.Download", args...).Exec() + res, err := process.New("yao.form.Download", args...).Exec() if err != nil { t.Fatal(err) } @@ -224,7 +226,7 @@ func TestProcessSetting(t *testing.T) { clear(t) testData(t) args := []interface{}{"pet"} - res, err := gou.NewProcess("yao.form.Setting", args...).Exec() + res, err := process.New("yao.form.Setting", args...).Exec() if err != nil { t.Fatal(err) } @@ -241,7 +243,7 @@ func TestProcessXgen(t *testing.T) { clear(t) testData(t) args := []interface{}{"pet"} - res, err := gou.NewProcess("yao.form.Xgen", args...).Exec() + res, err := process.New("yao.form.Xgen", args...).Exec() if err != nil { t.Fatal(err) } @@ -266,7 +268,7 @@ func TestProcessXgenWithPermissions(t *testing.T) { }) args := []interface{}{"pet"} - res, err := gou.NewProcess("yao.form.Xgen", args...).Exec() + res, err := process.New("yao.form.Xgen", args...).Exec() if err != nil { t.Fatal(err) } @@ -279,7 +281,7 @@ func TestProcessXgenWithPermissions(t *testing.T) { assert.NotEqual(t, "删除", data.Get("actions[0].title")) session.Global().Set("__permissions", nil) - res, err = gou.NewProcess("yao.form.Xgen", args...).Exec() + res, err = process.New("yao.form.Xgen", args...).Exec() if err != nil { t.Fatal(err) } @@ -303,7 +305,7 @@ func load(t *testing.T) { } func testData(t *testing.T) { - pet := gou.Select("pet") + pet := model.Select("pet") err := pet.Insert( []string{"name", "type", "status", "mode", "stay", "cost", "doctor_id"}, [][]interface{}{ @@ -333,7 +335,7 @@ func tempFile(t *testing.T) string { } func clear(t *testing.T) { - for _, m := range gou.Models { + for _, m := range model.Models { err := m.DropTable() if err != nil { t.Fatal(err) diff --git a/widgets/hook/hook.go b/widgets/hook/hook.go index 97d6055d97..08952eab1a 100644 --- a/widgets/hook/hook.go +++ b/widgets/hook/hook.go @@ -3,7 +3,7 @@ package hook import ( "fmt" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" ) // CopyBefore copy a before hook @@ -23,7 +23,7 @@ func CopyAfter(hook *After, new *After) { // Exec execute the hook func (hook *Before) Exec(args []interface{}, sid string, global map[string]interface{}) ([]interface{}, error) { - p, err := gou.ProcessOf(hook.String(), args...) + p, err := process.Of(hook.String(), args...) if err != nil { return nil, fmt.Errorf("%s %s", hook.String(), err.Error()) } @@ -56,7 +56,7 @@ func (hook *After) Exec(value interface{}, sid string, global map[string]interfa args = append(args, value) } - p, err := gou.ProcessOf(hook.String(), args...) + p, err := process.Of(hook.String(), args...) if err != nil { return nil, fmt.Errorf("[%s] %s", hook.String(), err.Error()) } diff --git a/widgets/list/action.go b/widgets/list/action.go index a432ba2d5c..67123062f1 100644 --- a/widgets/list/action.go +++ b/widgets/list/action.go @@ -1,7 +1,7 @@ package list import ( - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/model" "github.com/yaoapp/yao/widgets/action" "github.com/yaoapp/yao/widgets/hook" "github.com/yaoapp/yao/widgets/table" @@ -74,7 +74,7 @@ func (act *ActionDSL) SetDefaultProcess() { } // BindModel bind model -func (act *ActionDSL) BindModel(m *gou.Model) error { +func (act *ActionDSL) BindModel(m *model.Model) error { return nil } diff --git a/widgets/list/api.go b/widgets/list/api.go index 1953dff391..c02f57c22e 100644 --- a/widgets/list/api.go +++ b/widgets/list/api.go @@ -5,7 +5,7 @@ import ( "github.com/gin-gonic/gin" jsoniter "github.com/json-iterator/go" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/api" "github.com/yaoapp/yao/share" "github.com/yaoapp/yao/widgets/action" ) @@ -65,84 +65,84 @@ func (list *DSL) getAction(path string) (*action.Process, error) { // export API func exportAPI() error { - http := gou.HTTP{ + http := api.HTTP{ Name: "Widget List API", Description: "Widget List API", Version: share.VERSION, Guard: "widget-list", Group: "__yao/list", - Paths: []gou.Path{}, + Paths: []api.Path{}, } // GET /api/__yao/list/:id/setting -> Default process: yao.list.Xgen - path := gou.Path{ + path := api.Path{ Label: "Setting", Description: "Setting", Path: "/:id/setting", Method: "GET", Process: "yao.list.Setting", - In: []string{"$param.id"}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{"$param.id"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) // GET /api/__yao/list/:id/find -> Default process: yao.list.Get $param.id :query - path = gou.Path{ + path = api.Path{ Label: "Get", Description: "Get", Path: "/:id/get", Method: "GET", Process: "yao.list.Find", - In: []string{"$param.id", ":query-param"}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{"$param.id", ":query-param"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) // GET /api/__yao/list/:id/component/:xpath/:method -> Default process: yao.list.Component $param.id $param.xpath $param.method :query - path = gou.Path{ + path = api.Path{ Label: "Component", Description: "Component", Path: "/:id/component/:xpath/:method", Method: "GET", Process: "yao.list.Component", - In: []string{"$param.id", "$param.xpath", "$param.method", ":query"}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{"$param.id", "$param.xpath", "$param.method", ":query"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) // POST /api/__yao/list/:id/component/:xpath/:method -> Default process: yao.list.Component $param.id $param.xpath $param.method :payload - path = gou.Path{ + path = api.Path{ Label: "Component", Description: "Component", Path: "/:id/component/:xpath/:method", Method: "POST", Process: "yao.list.Component", - In: []string{"$param.id", "$param.xpath", "$param.method", ":payload"}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{"$param.id", "$param.xpath", "$param.method", ":payload"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) // POST /api/__yao/table/:id/upload/:xpath/:method -> Default process: yao.list.Upload $param.id $param.xpath $param.method $file.file - path = gou.Path{ + path = api.Path{ Label: "Upload", Description: "Upload", Path: "/:id/upload/:xpath/:method", Method: "POST", Process: "yao.list.Upload", - In: []string{"$param.id", "$param.xpath", "$param.method", "$file.file"}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{"$param.id", "$param.xpath", "$param.method", "$file.file"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) // GET /api/__yao/list/:id/download/:field -> Default process: yao.list.Download $param.id $param.xpath $param.field $query.name $query.token - path = gou.Path{ + path = api.Path{ Label: "Download", Description: "Download", Path: "/:id/download/:field", Method: "GET", Process: "yao.list.Download", - In: []string{"$param.id", "$param.field", "$query.name", "$query.token"}, - Out: gou.Out{ + In: []interface{}{"$param.id", "$param.field", "$query.name", "$query.token"}, + Out: api.Out{ Status: 200, Body: "{{content}}", Headers: map[string]string{"Content-Type": "{{type}}"}, @@ -151,14 +151,14 @@ func exportAPI() error { http.Paths = append(http.Paths, path) // POST /api/__yao/list/:id/save -> Default process: yao.list.Save $param.id :payload - path = gou.Path{ + path = api.Path{ Label: "Save", Description: "Save", Path: "/:id/save", Method: "POST", Process: "yao.list.Save", - In: []string{"$param.id", ":payload"}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{"$param.id", ":payload"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) @@ -169,6 +169,6 @@ func exportAPI() error { } // load apis - _, err = gou.LoadAPIReturn(string(source), "widgets.list") + _, err = api.Load(string(source), "widgets.list") return err } diff --git a/widgets/list/bind.go b/widgets/list/bind.go index 586b4ff2fa..09d02223f0 100644 --- a/widgets/list/bind.go +++ b/widgets/list/bind.go @@ -3,7 +3,7 @@ package list import ( "fmt" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/model" "github.com/yaoapp/yao/widgets/table" ) @@ -32,7 +32,7 @@ func (dsl *DSL) Bind() error { func (dsl *DSL) bindModel() error { id := dsl.Action.Bind.Model - m, has := gou.Models[id] + m, has := model.Models[id] if !has { return fmt.Errorf("%s does not exist", id) } diff --git a/widgets/list/fields.go b/widgets/list/fields.go index c9a662e947..b500a2cbc9 100644 --- a/widgets/list/fields.go +++ b/widgets/list/fields.go @@ -4,12 +4,12 @@ import ( "fmt" "strings" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/model" "github.com/yaoapp/yao/widgets/table" ) // BindModel bind model -func (fields *FieldsDSL) BindModel(m *gou.Model) error { +func (fields *FieldsDSL) BindModel(m *model.Model) error { // fields.listMap = map[string]field.ColumnDSL{} diff --git a/widgets/list/handler.go b/widgets/list/handler.go index fd9f509190..608c50434b 100644 --- a/widgets/list/handler.go +++ b/widgets/list/handler.go @@ -4,7 +4,9 @@ import ( "fmt" "strings" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/model" + gouProcess "github.com/yaoapp/gou/process" + "github.com/yaoapp/gou/session" "github.com/yaoapp/kun/log" "github.com/yaoapp/yao/config" "github.com/yaoapp/yao/i18n" @@ -17,7 +19,7 @@ import ( // Life-Circle: Before Hook → Compute Edit → Run Process → Compute View → After Hook // Execute Compute Edit On: Save // Execute Compute View On: Get -func processHandler(p *action.Process, process *gou.Process) (interface{}, error) { +func processHandler(p *action.Process, process *gouProcess.Process) (interface{}, error) { list, err := Get(process) if err != nil { @@ -55,7 +57,7 @@ func processHandler(p *action.Process, process *gou.Process) (interface{}, error } // Execute Process - act, err := gou.ProcessOf(name, args...) + act, err := gouProcess.Of(name, args...) if err != nil { log.Error("[list] %s %s -> %s %s", list.ID, p.Name, name, err.Error()) return nil, fmt.Errorf("[list] %s %s -> %s %s", list.ID, p.Name, name, err.Error()) @@ -95,7 +97,7 @@ func processHandler(p *action.Process, process *gou.Process) (interface{}, error } // translateSetting -func (dsl *DSL) translate(name string, process *gou.Process, data interface{}) (interface{}, error) { +func (dsl *DSL) translate(name string, process *gouProcess.Process, data interface{}) (interface{}, error) { if strings.ToLower(name) != "yao.list.setting" { return data, nil @@ -103,7 +105,7 @@ func (dsl *DSL) translate(name string, process *gou.Process, data interface{}) ( widgets := []string{} if dsl.Action.Bind.Model != "" { - m := gou.Select(dsl.Action.Bind.Model) + m := model.Select(dsl.Action.Bind.Model) widgets = append(widgets, fmt.Sprintf("model.%s", m.ID)) } @@ -112,7 +114,7 @@ func (dsl *DSL) translate(name string, process *gou.Process, data interface{}) ( } widgets = append(widgets, fmt.Sprintf("list.%s", dsl.ID)) - res, err := i18n.Trans(process.Lang(config.Conf.Lang), widgets, data) + res, err := i18n.Trans(session.Lang(process, config.Conf.Lang), widgets, data) if err != nil { return nil, err } diff --git a/widgets/list/layout.go b/widgets/list/layout.go index 012a9fee7f..fa94b965f9 100644 --- a/widgets/list/layout.go +++ b/widgets/list/layout.go @@ -2,14 +2,14 @@ package list import ( jsoniter "github.com/json-iterator/go" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/model" "github.com/yaoapp/yao/widgets/component" "github.com/yaoapp/yao/widgets/mapping" "github.com/yaoapp/yao/widgets/table" ) // BindModel bind model -func (layout *LayoutDSL) BindModel(m *gou.Model, listID string, fields *FieldsDSL, option map[string]interface{}) { +func (layout *LayoutDSL) BindModel(m *model.Model, listID string, fields *FieldsDSL, option map[string]interface{}) { // if layout.Primary == "" { // layout.Primary = m.PrimaryKey // } diff --git a/widgets/list/list.go b/widgets/list/list.go index 5f082eccff..02c34db2a7 100644 --- a/widgets/list/list.go +++ b/widgets/list/list.go @@ -6,7 +6,7 @@ import ( "strings" jsoniter "github.com/json-iterator/go" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" "github.com/yaoapp/kun/exception" "github.com/yaoapp/kun/log" "github.com/yaoapp/yao/config" @@ -165,8 +165,8 @@ func Get(list interface{}) (*DSL, error) { switch list.(type) { case string: id = list.(string) - case *gou.Process: - id = list.(*gou.Process).ArgsString(0) + case *process.Process: + id = list.(*process.Process).ArgsString(0) default: return nil, fmt.Errorf("%v type does not support", list) } diff --git a/widgets/list/list_test.go b/widgets/list/list_test.go index 5595ce43c5..1e8548a2cc 100644 --- a/widgets/list/list_test.go +++ b/widgets/list/list_test.go @@ -8,12 +8,11 @@ import ( "github.com/yaoapp/yao/fs" "github.com/yaoapp/yao/i18n" "github.com/yaoapp/yao/model" - "github.com/yaoapp/yao/runtime" "github.com/yaoapp/yao/script" "github.com/yaoapp/yao/share" - "github.com/yaoapp/yao/table" "github.com/yaoapp/yao/widgets/expression" "github.com/yaoapp/yao/widgets/field" + "github.com/yaoapp/yao/widgets/table" "github.com/yaoapp/yao/widgets/test" ) @@ -28,7 +27,7 @@ func TestLoad(t *testing.T) { func prepare(t *testing.T, language ...string) { - runtime.Load(config.Conf) + // runtime.Load(config.Conf) err := test.LoadEngine(language...) if err != nil { t.Fatal(err) diff --git a/widgets/list/process.go b/widgets/list/process.go index b30ae9b2be..705d02cbc7 100644 --- a/widgets/list/process.go +++ b/widgets/list/process.go @@ -5,8 +5,9 @@ import ( "net/url" "strings" - "github.com/yaoapp/gou" "github.com/yaoapp/gou/fs" + gouProcess "github.com/yaoapp/gou/process" + "github.com/yaoapp/gou/types" "github.com/yaoapp/kun/exception" "github.com/yaoapp/kun/log" "github.com/yaoapp/yao/helper" @@ -15,15 +16,15 @@ import ( // Export process func exportProcess() { - gou.RegisterProcessHandler("yao.list.setting", processSetting) - gou.RegisterProcessHandler("yao.list.xgen", processXgen) - gou.RegisterProcessHandler("yao.list.component", processComponent) - gou.RegisterProcessHandler("yao.list.upload", processUpload) - gou.RegisterProcessHandler("yao.list.download", processDownload) - gou.RegisterProcessHandler("yao.list.save", processSave) + gouProcess.Register("yao.list.setting", processSetting) + gouProcess.Register("yao.list.xgen", processXgen) + gouProcess.Register("yao.list.component", processComponent) + gouProcess.Register("yao.list.upload", processUpload) + gouProcess.Register("yao.list.download", processDownload) + gouProcess.Register("yao.list.save", processSave) } -func processXgen(process *gou.Process) interface{} { +func processXgen(process *gouProcess.Process) interface{} { list := MustGet(process) data := process.ArgsMap(1, map[string]interface{}{}) @@ -36,7 +37,7 @@ func processXgen(process *gou.Process) interface{} { return setting } -func processComponent(process *gou.Process) interface{} { +func processComponent(process *gouProcess.Process) interface{} { process.ValidateArgNums(3) list := MustGet(process) @@ -65,7 +66,7 @@ func processComponent(process *gou.Process) interface{} { return res } -func processDownload(process *gou.Process) interface{} { +func processDownload(process *gouProcess.Process) interface{} { process.ValidateArgNums(4) list := MustGet(process) @@ -93,7 +94,7 @@ func processDownload(process *gou.Process) interface{} { } // Create process - p, err := gou.ProcessOf(name, file) + p, err := gouProcess.Of(name, file) if err != nil { log.Error("[downalod] %s.%s %s", list.ID, field, err.Error()) exception.New("[downalod] %s.%s %s", 400, list.ID, field, err.Error()).Throw() @@ -109,7 +110,7 @@ func processDownload(process *gou.Process) interface{} { return res } -func processUpload(process *gou.Process) interface{} { +func processUpload(process *gouProcess.Process) interface{} { process.ValidateArgNums(4) list := MustGet(process) @@ -124,7 +125,7 @@ func processUpload(process *gou.Process) interface{} { } // $file.file - tmpfile, ok := process.Args[3].(gou.UploadFile) + tmpfile, ok := process.Args[3].(types.UploadFile) if !ok { exception.New("parameters error: %v", 400, process.Args[3]).Throw() } @@ -144,18 +145,18 @@ func processUpload(process *gou.Process) interface{} { return res } -func processSetting(process *gou.Process) interface{} { +func processSetting(process *gouProcess.Process) interface{} { list := MustGet(process) process.Args = append(process.Args, process.Args[0]) // list name return list.Action.Setting.MustExec(process) } -func processGet(process *gou.Process) interface{} { +func processGet(process *gouProcess.Process) interface{} { list := MustGet(process) return list.Action.Get.MustExec(process) } -func processSave(process *gou.Process) interface{} { +func processSave(process *gouProcess.Process) interface{} { list := MustGet(process) return list.Action.Save.MustExec(process) } diff --git a/widgets/list/process_test.go b/widgets/list/process_test.go index 9cb082400b..1c3a25c3a8 100644 --- a/widgets/list/process_test.go +++ b/widgets/list/process_test.go @@ -6,7 +6,8 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/model" + "github.com/yaoapp/gou/process" "github.com/yaoapp/gou/session" "github.com/yaoapp/kun/any" "github.com/yaoapp/yao/config" @@ -18,7 +19,7 @@ func TestProcessSetting(t *testing.T) { clear(t) testData(t) args := []interface{}{"category"} - res, err := gou.NewProcess("yao.list.Setting", args...).Exec() + res, err := process.New("yao.list.Setting", args...).Exec() if err != nil { t.Fatal(err) } @@ -33,7 +34,7 @@ func TestProcessXgen(t *testing.T) { clear(t) testData(t) args := []interface{}{"category"} - res, err := gou.NewProcess("yao.list.Xgen", args...).Exec() + res, err := process.New("yao.list.Xgen", args...).Exec() if err != nil { t.Fatal(err) } @@ -55,7 +56,7 @@ func TestProcessXgenWithPermissions(t *testing.T) { }) args := []interface{}{"category"} - res, err := gou.NewProcess("yao.list.Xgen", args...).Exec() + res, err := process.New("yao.list.Xgen", args...).Exec() if err != nil { t.Fatal(err) } @@ -66,7 +67,7 @@ func TestProcessXgenWithPermissions(t *testing.T) { assert.False(t, data.Has("fields.list.库存预警")) session.Global().Set("__permissions", nil) - res, err = gou.NewProcess("yao.list.Xgen", args...).Exec() + res, err = process.New("yao.list.Xgen", args...).Exec() if err != nil { t.Fatal(err) } @@ -88,7 +89,7 @@ func load(t *testing.T) { } func testData(t *testing.T) { - category := gou.Select("category") + category := model.Select("category") err := category.Insert( []string{"name", "stock", "status", "rank"}, [][]interface{}{ @@ -118,7 +119,7 @@ func tempFile(t *testing.T) string { } func clear(t *testing.T) { - for _, m := range gou.Models { + for _, m := range model.Models { err := m.DropTable() if err != nil { t.Fatal(err) diff --git a/widgets/login/login.go b/widgets/login/login.go index 660d28ac50..a526023c11 100644 --- a/widgets/login/login.go +++ b/widgets/login/login.go @@ -6,7 +6,7 @@ import ( "strings" jsoniter "github.com/json-iterator/go" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/api" "github.com/yaoapp/yao/config" "github.com/yaoapp/yao/share" ) @@ -72,25 +72,25 @@ func Export() error { // exportAPI export login api func exportAPI() error { - http := gou.HTTP{ + http := api.HTTP{ Name: "Widget Login API", Description: "Widget Login API", Version: share.VERSION, Guard: "bearer-jwt", Group: "__yao/login", - Paths: []gou.Path{}, + Paths: []api.Path{}, } for _, dsl := range Logins { // login action process := "yao.login.Admin" - args := []string{":payload"} + args := []interface{}{":payload"} if dsl.Action.Process != "" { process = dsl.Action.Process args = dsl.Action.Args } - path := gou.Path{ + path := api.Path{ Label: fmt.Sprintf("%s login", dsl.ID), Description: fmt.Sprintf("%s login", dsl.ID), Guard: "-", @@ -98,18 +98,18 @@ func exportAPI() error { Method: "POST", Process: process, In: args, - Out: gou.Out{Status: 200, Type: "application/json"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) // captcha process = "yao.utils.Captcha" - args = []string{":query"} + args = []interface{}{":query"} if dsl.Layout.Captcha != "" { process = dsl.Layout.Captcha } - path = gou.Path{ + path = api.Path{ Label: fmt.Sprintf("%s captcha", dsl.ID), Description: fmt.Sprintf("%s captcha", dsl.ID), Guard: "-", @@ -117,7 +117,7 @@ func exportAPI() error { Method: "GET", Process: process, In: args, - Out: gou.Out{Status: 200, Type: "application/json"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) @@ -130,6 +130,6 @@ func exportAPI() error { } // load apis - _, err = gou.LoadAPIReturn(string(source), "widgets.login") + _, err = api.Load(string(source), "widgets.login") return err } diff --git a/widgets/login/login_test.go b/widgets/login/login_test.go index 28596c2764..c719e08925 100644 --- a/widgets/login/login_test.go +++ b/widgets/login/login_test.go @@ -6,14 +6,13 @@ import ( "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/api" "github.com/yaoapp/yao/config" "github.com/yaoapp/yao/i18n" - "github.com/yaoapp/yao/runtime" ) func TestLoad(t *testing.T) { - runtime.Load(config.Conf) + // runtime.Load(config.Conf) i18n.Load(config.Conf) err := Load(config.Conf) if err != nil { @@ -44,7 +43,7 @@ func TestLoad(t *testing.T) { } func TestLoadHK(t *testing.T) { - runtime.Load(config.Conf) + // runtime.Load(config.Conf) i18n.Load(config.Conf) err := Load(config.Conf) if err != nil { @@ -147,7 +146,7 @@ func TestExport(t *testing.T) { t.Fatal(err) } - api, has := gou.APIs["widgets.login"] + api, has := api.APIs["widgets.login"] assert.True(t, has) assert.Equal(t, 4, len(api.HTTP.Paths)) } diff --git a/widgets/login/process.go b/widgets/login/process.go index 334c158c62..dec4bb4579 100644 --- a/widgets/login/process.go +++ b/widgets/login/process.go @@ -3,7 +3,8 @@ package login import ( "time" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/model" + "github.com/yaoapp/gou/process" "github.com/yaoapp/gou/session" "github.com/yaoapp/kun/any" "github.com/yaoapp/kun/exception" @@ -11,7 +12,6 @@ import ( "github.com/yaoapp/kun/maps" "github.com/yaoapp/yao/config" "github.com/yaoapp/yao/helper" - "github.com/yaoapp/yao/user" "golang.org/x/crypto/bcrypt" ) @@ -23,11 +23,11 @@ var loginTypes = map[string]string{ // Export process func exportProcess() { - gou.RegisterProcessHandler("yao.login.admin", processLoginAdmin) + process.Register("yao.login.admin", processLoginAdmin) } // processLoginAdmin yao.admin.login 用户登录 -func processLoginAdmin(process *gou.Process) interface{} { +func processLoginAdmin(process *process.Process) interface{} { process.ValidateArgNums(1) payload := process.ArgsMap(0).Dot() log.With(log.F{"payload": payload}).Debug("processLoginAdmin") @@ -40,7 +40,7 @@ func processLoginAdmin(process *gou.Process) interface{} { if value == "" { exception.New("请输入验证码", 400).Ctx(maps.Map{"id": id, "code": value}).Throw() } - if !user.ValidateCaptcha(id, value) { + if !helper.CaptchaValidate(id, value) { log.With(log.F{"id": id, "code": value}).Debug("ProcessLogin") exception.New("验证码不正确", 403).Ctx(maps.Map{"id": id, "code": value}).Throw() return nil @@ -70,11 +70,11 @@ func auth(field string, value string, password string, sid string) maps.Map { exception.New("登录方式(%s)尚未支持", 400, field).Throw() } - user := gou.Select("xiang.user") - rows, err := user.Get(gou.QueryParam{ + user := model.Select("xiang.user") + rows, err := user.Get(model.QueryParam{ Select: []interface{}{"id", "password", "name", "type", "email", "mobile", "extra", "status"}, Limit: 1, - Wheres: []gou.QueryWhere{ + Wheres: []model.QueryWhere{ {Column: column, Value: value}, {Column: "status", Value: "enabled"}, }, @@ -126,7 +126,7 @@ func auth(field string, value string, password string, sid string) maps.Map { } // 读取菜单 - menus := gou.NewProcess("yao.app.menu").WithSID(sid).Run() + menus := process.New("yao.app.menu").WithSID(sid).Run() return maps.Map{ "expires_at": token.ExpiresAt, "token": token.Token, diff --git a/widgets/login/types.go b/widgets/login/types.go index f3fb4d842f..df0ae9d22f 100644 --- a/widgets/login/types.go +++ b/widgets/login/types.go @@ -11,8 +11,8 @@ type DSL struct { // ActionDSL the login action DSL type ActionDSL struct { - Process string `json:"process,omitempty"` - Args []string `json:"args,omitempty"` + Process string `json:"process,omitempty"` + Args []interface{} `json:"args,omitempty"` } // LayoutDSL the login page layoutDSL diff --git a/widgets/models.go b/widgets/models.go index f547d9d1ac..634638031d 100644 --- a/widgets/models.go +++ b/widgets/models.go @@ -5,14 +5,14 @@ import ( "os" "strings" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/model" ) // Models return loaded models func Models() []Item { models := map[string]interface{}{} - for id, widget := range gou.Models { + for id, widget := range model.Models { if strings.HasPrefix(id, "xiang.") { continue diff --git a/widgets/process.go b/widgets/process.go index f65677e5c8..03d7685b76 100644 --- a/widgets/process.go +++ b/widgets/process.go @@ -1,11 +1,11 @@ package widgets import ( - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" ) // WidgetHandlers Processes -var WidgetHandlers = map[string]gou.ProcessHandler{ +var WidgetHandlers = map[string]process.Handler{ "apis": processApis, "actions": processActions, "models": processModels, @@ -14,31 +14,31 @@ var WidgetHandlers = map[string]gou.ProcessHandler{ } func init() { - gou.RegisterProcessGroup("widget", WidgetHandlers) + process.RegisterGroup("widget", WidgetHandlers) } // Get the loaded APIs -func processApis(process *gou.Process) interface{} { +func processApis(process *process.Process) interface{} { return Apis() } // Get the actions of each widget -func processActions(process *gou.Process) interface{} { +func processActions(process *process.Process) interface{} { return Actions() } // Get the loaded Models -func processModels(process *gou.Process) interface{} { +func processModels(process *process.Process) interface{} { return Models() } // Get the loaded Fields -func processFields(process *gou.Process) interface{} { +func processFields(process *process.Process) interface{} { return Fields() } // Get the loaded Filters -func processFilters(process *gou.Process) interface{} { +func processFilters(process *process.Process) interface{} { return Filters() } diff --git a/widgets/process_test.go b/widgets/process_test.go index 5ce3fd56da..2d5e583d9a 100644 --- a/widgets/process_test.go +++ b/widgets/process_test.go @@ -4,14 +4,14 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" "github.com/yaoapp/yao/config" ) func TestProcessApis(t *testing.T) { testData(t) args := []interface{}{} - res, err := gou.NewProcess("widget.apis", args...).Exec() + res, err := process.New("widget.apis", args...).Exec() if err != nil { t.Fatal(err) } @@ -21,7 +21,7 @@ func TestProcessApis(t *testing.T) { func TestProcessActions(t *testing.T) { testData(t) args := []interface{}{} - res, err := gou.NewProcess("widget.actions", args...).Exec() + res, err := process.New("widget.actions", args...).Exec() if err != nil { t.Fatal(err) } @@ -31,7 +31,7 @@ func TestProcessActions(t *testing.T) { func TestProcessModels(t *testing.T) { testData(t) args := []interface{}{} - res, err := gou.NewProcess("widget.models", args...).Exec() + res, err := process.New("widget.models", args...).Exec() if err != nil { t.Fatal(err) } @@ -41,7 +41,7 @@ func TestProcessModels(t *testing.T) { func TestProcessFields(t *testing.T) { testData(t) args := []interface{}{} - res, err := gou.NewProcess("widget.fields", args...).Exec() + res, err := process.New("widget.fields", args...).Exec() if err != nil { t.Fatal(err) } @@ -51,7 +51,7 @@ func TestProcessFields(t *testing.T) { func TestProcessFilters(t *testing.T) { testData(t) args := []interface{}{} - res, err := gou.NewProcess("widget.filters", args...).Exec() + res, err := process.New("widget.filters", args...).Exec() if err != nil { t.Fatal(err) } diff --git a/widgets/table/action.go b/widgets/table/action.go index ab5419dcd6..c36b37e54f 100644 --- a/widgets/table/action.go +++ b/widgets/table/action.go @@ -3,7 +3,7 @@ package table import ( "fmt" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/model" "github.com/yaoapp/yao/widgets/action" "github.com/yaoapp/yao/widgets/hook" ) @@ -188,7 +188,7 @@ func (act *ActionDSL) SetDefaultProcess() { } // BindModel bind model -func (act *ActionDSL) BindModel(m *gou.Model) error { +func (act *ActionDSL) BindModel(m *model.Model) error { name := m.ID act.Search.Bind(fmt.Sprintf("models.%s.Paginate", name)) diff --git a/widgets/table/api.go b/widgets/table/api.go index bc4e6439d3..b30a9c175d 100644 --- a/widgets/table/api.go +++ b/widgets/table/api.go @@ -5,7 +5,7 @@ import ( "github.com/gin-gonic/gin" jsoniter "github.com/json-iterator/go" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/api" "github.com/yaoapp/yao/share" "github.com/yaoapp/yao/widgets/action" ) @@ -87,96 +87,96 @@ func (table *DSL) getAction(path string) (*action.Process, error) { // export API func exportAPI() error { - http := gou.HTTP{ + http := api.HTTP{ Name: "Widget Table API", Description: "Widget Table API", Version: share.VERSION, Guard: "widget-table", Group: "__yao/table", - Paths: []gou.Path{}, + Paths: []api.Path{}, } // GET /api/__yao/table/:id/setting -> Default process: yao.table.Xgen - path := gou.Path{ + path := api.Path{ Label: "Setting", Description: "Setting", Path: "/:id/setting", Method: "GET", Process: "yao.table.Setting", - In: []string{"$param.id"}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{"$param.id"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) // GET /api/__yao/table/:id/search -> Default process: yao.table.Search $param.id :query $query.page $query.pagesize - path = gou.Path{ + path = api.Path{ Label: "Search", Description: "Search", Path: "/:id/search", Method: "GET", Process: "yao.table.Search", - In: []string{"$param.id", ":query-param", "$query.page", "$query.pagesize"}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{"$param.id", ":query-param", "$query.page", "$query.pagesize"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) // GET /api/__yao/table/:id/get -> Default process: yao.table.Get $param.id :query - path = gou.Path{ + path = api.Path{ Label: "Get", Description: "Get", Path: "/:id/get", Method: "GET", Process: "yao.table.Get", - In: []string{"$param.id", ":query-param"}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{"$param.id", ":query-param"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) // GET /api/__yao/table/:id/find/:primary -> Default process: yao.table.Find $param.id $param.primary :query - path = gou.Path{ + path = api.Path{ Label: "Find", Description: "Find", Path: "/:id/find/:primary", Method: "GET", Process: "yao.table.Find", - In: []string{"$param.id", "$param.primary", ":query-param"}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{"$param.id", "$param.primary", ":query-param"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) // GET /api/__yao/table/:id/component/:xpath/:method -> Default process: yao.table.Component $param.id $param.xpath $param.method :query - path = gou.Path{ + path = api.Path{ Label: "Component", Description: "Component", Path: "/:id/component/:xpath/:method", Method: "GET", Process: "yao.table.Component", - In: []string{"$param.id", "$param.xpath", "$param.method", ":query"}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{"$param.id", "$param.xpath", "$param.method", ":query"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) // POST /api/__yao/table/:id/upload/:xpath/:method -> Default process: yao.table.Upload $param.id $param.xpath $param.method $file.file - path = gou.Path{ + path = api.Path{ Label: "Upload", Description: "Upload", Path: "/:id/upload/:xpath/:method", Method: "POST", Process: "yao.table.Upload", - In: []string{"$param.id", "$param.xpath", "$param.method", "$file.file"}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{"$param.id", "$param.xpath", "$param.method", "$file.file"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) // GET /api/__yao/table/:id/download/:field -> Default process: yao.table.Download $param.id $param.xpath $param.field $query.name $query.token - path = gou.Path{ + path = api.Path{ Label: "Download", Description: "Download", Path: "/:id/download/:field", Method: "GET", Process: "yao.table.Download", - In: []string{"$param.id", "$param.field", "$query.name", "$query.token"}, - Out: gou.Out{ + In: []interface{}{"$param.id", "$param.field", "$query.name", "$query.token"}, + Out: api.Out{ Status: 200, Body: "{{content}}", Headers: map[string]string{"Content-Type": "{{type}}"}, @@ -185,110 +185,110 @@ func exportAPI() error { http.Paths = append(http.Paths, path) // POST /api/__yao/table/:id/save -> Default process: yao.table.Save $param.id :payload - path = gou.Path{ + path = api.Path{ Label: "Save", Description: "Save", Path: "/:id/save", Method: "POST", Process: "yao.table.Save", - In: []string{"$param.id", ":payload"}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{"$param.id", ":payload"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) // POST /api/__yao/table/:id/create -> Default process: yao.table.Create $param.id :payload - path = gou.Path{ + path = api.Path{ Label: "Create", Description: "Create", Path: "/:id/create", Method: "POST", Process: "yao.table.Create", - In: []string{"$param.id", ":payload"}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{"$param.id", ":payload"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) // POST /api/__yao/table/:id/insert -> Default process: yao.table.Insert :payload - path = gou.Path{ + path = api.Path{ Label: "Insert", Description: "Insert", Path: "/:id/insert", Method: "POST", Process: "yao.table.Insert", - In: []string{"$param.id", "$payload.columns", "$payload.values"}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{"$param.id", "$payload.columns", "$payload.values"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) // POST /api/__yao/table/:id/update/:primary -> Default process: yao.table.Update $param.id $param.primary :payload - path = gou.Path{ + path = api.Path{ Label: "Update", Description: "Update", Path: "/:id/update/:primary", Method: "POST", Process: "yao.table.Update", - In: []string{"$param.id", "$param.primary", ":payload"}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{"$param.id", "$param.primary", ":payload"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) // POST /api/__yao/table/:id/update/where -> Default process: yao.table.UpdateWhere $param.id :query :payload - path = gou.Path{ + path = api.Path{ Label: "Update Where", Description: "Update Where", Path: "/:id/update/where", Method: "POST", Process: "yao.table.UpdateWhere", - In: []string{"$param.id", ":query-param", ":payload"}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{"$param.id", ":query-param", ":payload"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) // POST /api/__yao/table/:id/update/in -> Default process: yao.table.UpdateIn $param.id $query.ids :payload - path = gou.Path{ + path = api.Path{ Label: "Update In", Description: "Update In", Path: "/:id/update/in", Method: "POST", Process: "yao.table.UpdateIn", - In: []string{"$param.id", "$query.ids", ":payload"}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{"$param.id", "$query.ids", ":payload"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) // POST /api/__yao/table/:id/delete/:primary -> Default process: yao.table.Delete $param.id $param.primary - path = gou.Path{ + path = api.Path{ Label: "Delete", Description: "Delete", Path: "/:id/delete/:primary", Method: "POST", Process: "yao.table.Delete", - In: []string{"$param.id", "$param.primary"}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{"$param.id", "$param.primary"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) // POST /api/__yao/table/:id/delete/where -> Default process: yao.table.DeleteWhere $param.id :query - path = gou.Path{ + path = api.Path{ Label: "Delete Where", Description: "Delete Where", Path: "/:id/delete/where", Method: "POST", Process: "yao.table.DeleteWhere", - In: []string{"$param.id", ":query-param"}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{"$param.id", ":query-param"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) // POST /api/__yao/table/:id/delete/in -> Default process: yao.table.DeleteIn $param.id $query.ids - path = gou.Path{ + path = api.Path{ Label: "Delete In", Description: "Delete In", Path: "/:id/delete/in", Method: "POST", Process: "yao.table.DeleteIn", - In: []string{"$param.id", "$query.ids"}, - Out: gou.Out{Status: 200, Type: "application/json"}, + In: []interface{}{"$param.id", "$query.ids"}, + Out: api.Out{Status: 200, Type: "application/json"}, } http.Paths = append(http.Paths, path) @@ -299,6 +299,6 @@ func exportAPI() error { } // load apis - _, err = gou.LoadAPIReturn(string(source), "widgets.table") + _, err = api.Load(string(source), "widgets.table") return err } diff --git a/widgets/table/api_test.go b/widgets/table/api_test.go index 19cbc86dc0..436c019f36 100644 --- a/widgets/table/api_test.go +++ b/widgets/table/api_test.go @@ -9,7 +9,6 @@ import ( "github.com/gin-gonic/gin" "github.com/stretchr/testify/assert" "github.com/yaoapp/kun/any" - "github.com/yaoapp/yao/network" "github.com/yaoapp/yao/widgets/test" ) @@ -182,7 +181,7 @@ func TestAPIGlobalCustomGuard(t *testing.T) { } func start(t *testing.T) int { - port := network.FreePort() + port := 0 load(t) clear(t) testData(t) diff --git a/widgets/table/bind.go b/widgets/table/bind.go index ed7c9fe205..52f7c4f781 100644 --- a/widgets/table/bind.go +++ b/widgets/table/bind.go @@ -3,7 +3,7 @@ package table import ( "fmt" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/model" ) // Bind model / store / table / ... @@ -31,7 +31,7 @@ func (dsl *DSL) Bind() error { func (dsl *DSL) bindModel() error { id := dsl.Action.Bind.Model - m, has := gou.Models[id] + m, has := model.Models[id] if !has { return fmt.Errorf("%s does not exist", id) } diff --git a/widgets/table/excel.go b/widgets/table/excel.go index aa83fbc31a..f305b055a4 100644 --- a/widgets/table/excel.go +++ b/widgets/table/excel.go @@ -10,7 +10,6 @@ import ( "github.com/yaoapp/kun/any" "github.com/yaoapp/kun/log" "github.com/yaoapp/kun/maps" - "github.com/yaoapp/yao/xfs" ) // Export Export query result to Excel @@ -43,7 +42,8 @@ func (dsl *DSL) Export(filename string, data interface{}, page int, chunkSize in return fmt.Errorf("the table does not support export") } - filename = filepath.Join(xfs.Stor.Root, filename) + // filename = filepath.Join(xfs.Stor.Root, filename) + filename = filepath.Join("/data", filename) if _, err := os.Stat(filename); errors.Is(err, os.ErrNotExist) { f := excelize.NewFile() index := f.GetActiveSheetIndex() diff --git a/widgets/table/fields.go b/widgets/table/fields.go index 959f651c11..a63665cfe4 100644 --- a/widgets/table/fields.go +++ b/widgets/table/fields.go @@ -4,7 +4,7 @@ import ( "fmt" "strings" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/model" "github.com/yaoapp/kun/log" "github.com/yaoapp/yao/widgets/component" "github.com/yaoapp/yao/widgets/field" @@ -16,7 +16,7 @@ func (fields *FieldsDSL) TableMap() map[string]field.ColumnDSL { } // BindModel cast model to fields -func (fields *FieldsDSL) BindModel(m *gou.Model) error { +func (fields *FieldsDSL) BindModel(m *model.Model) error { fields.filterMap = map[string]field.FilterDSL{} fields.tableMap = map[string]field.ColumnDSL{} diff --git a/widgets/table/fields_test.go b/widgets/table/fields_test.go index 16674f54ee..6632541b5d 100644 --- a/widgets/table/fields_test.go +++ b/widgets/table/fields_test.go @@ -4,14 +4,14 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/model" ) func TestFiledsBindModel(t *testing.T) { load(t) clear(t) testData(t) - m := gou.Select("pet") + m := model.Select("pet") tab := New("unit-test") err := tab.Fields.BindModel(m) if err != nil { diff --git a/widgets/table/handler.go b/widgets/table/handler.go index 9c0c3ddba7..7c567b63a2 100644 --- a/widgets/table/handler.go +++ b/widgets/table/handler.go @@ -4,7 +4,9 @@ import ( "fmt" "strings" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/model" + gouProcess "github.com/yaoapp/gou/process" + "github.com/yaoapp/gou/session" "github.com/yaoapp/kun/log" "github.com/yaoapp/yao/config" "github.com/yaoapp/yao/i18n" @@ -18,7 +20,7 @@ import ( // Execute Compute Filter On: Search, Get, Find // Execute Compute Edit On: Save, Create, Update, UpdateWhere, UpdateIn, Insert // Execute Compute View On: Search, Get, Find -func processHandler(p *action.Process, process *gou.Process) (interface{}, error) { +func processHandler(p *action.Process, process *gouProcess.Process) (interface{}, error) { tab, err := Get(process) if err != nil { @@ -62,7 +64,7 @@ func processHandler(p *action.Process, process *gou.Process) (interface{}, error } // Execute Process - act, err := gou.ProcessOf(name, args...) + act, err := gouProcess.Of(name, args...) if err != nil { log.Error("[table] %s %s -> %s %s %v", tab.ID, p.Name, name, err.Error(), args) return nil, fmt.Errorf("[table] %s %s -> %s %s", tab.ID, p.Name, name, err.Error()) @@ -102,7 +104,7 @@ func processHandler(p *action.Process, process *gou.Process) (interface{}, error } // translateSetting -func (dsl *DSL) translate(name string, process *gou.Process, data interface{}) (interface{}, error) { +func (dsl *DSL) translate(name string, process *gouProcess.Process, data interface{}) (interface{}, error) { if strings.ToLower(name) != "yao.table.setting" { return data, nil @@ -110,7 +112,7 @@ func (dsl *DSL) translate(name string, process *gou.Process, data interface{}) ( widgets := []string{} if dsl.Action.Bind.Model != "" { - m := gou.Select(dsl.Action.Bind.Model) + m := model.Select(dsl.Action.Bind.Model) widgets = append(widgets, fmt.Sprintf("model.%s", m.ID)) } @@ -119,7 +121,7 @@ func (dsl *DSL) translate(name string, process *gou.Process, data interface{}) ( } widgets = append(widgets, fmt.Sprintf("table.%s", dsl.ID)) - res, err := i18n.Trans(process.Lang(config.Conf.Lang), widgets, data) + res, err := i18n.Trans(session.Lang(process, config.Conf.Lang), widgets, data) if err != nil { return nil, err } diff --git a/widgets/table/layout.go b/widgets/table/layout.go index b50a4a042a..e5a07043bc 100644 --- a/widgets/table/layout.go +++ b/widgets/table/layout.go @@ -5,13 +5,13 @@ import ( "strings" jsoniter "github.com/json-iterator/go" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/model" "github.com/yaoapp/yao/widgets/component" "github.com/yaoapp/yao/widgets/mapping" ) // BindModel bind model -func (layout *LayoutDSL) BindModel(m *gou.Model, fields *FieldsDSL, option map[string]interface{}) error { +func (layout *LayoutDSL) BindModel(m *model.Model, fields *FieldsDSL, option map[string]interface{}) error { if option == nil { option = map[string]interface{}{} diff --git a/widgets/table/mapping_test.go b/widgets/table/mapping_test.go index 615a5ab613..502061825d 100644 --- a/widgets/table/mapping_test.go +++ b/widgets/table/mapping_test.go @@ -5,7 +5,7 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" "github.com/yaoapp/kun/any" ) @@ -34,7 +34,7 @@ func TestMappingFind(t *testing.T) { testData(t) args := []interface{}{"compute", 1} - res, err := gou.NewProcess("yao.table.find", args...).Exec() + res, err := process.New("yao.table.find", args...).Exec() if err != nil { t.Fatal(err) } @@ -51,7 +51,7 @@ func TestMappingGet(t *testing.T) { params := map[string]interface{}{"limit": 2} args := []interface{}{"compute", params} - res, err := gou.NewProcess("yao.table.get", args...).Exec() + res, err := process.New("yao.table.get", args...).Exec() if err != nil { t.Fatal(err) } @@ -69,7 +69,7 @@ func TestMappingSearch(t *testing.T) { params := map[string]interface{}{} args := []interface{}{"compute", params, 1, 5} - res, err := gou.NewProcess("yao.table.search", args...).Exec() + res, err := process.New("yao.table.search", args...).Exec() if err != nil { t.Fatal(err) } @@ -91,13 +91,13 @@ func TestMappingSave(t *testing.T) { "doctor_id": 1, }} - res, err := gou.NewProcess("yao.table.Save", args...).Exec() + res, err := process.New("yao.table.Save", args...).Exec() if err != nil { t.Fatal(err) } assert.Equal(t, "4", fmt.Sprintf("%v", res)) - res, err = gou.NewProcess("yao.table.find", "compute", res).Exec() + res, err = process.New("yao.table.find", "compute", res).Exec() if err != nil { t.Fatal(err) } @@ -120,12 +120,12 @@ func TestMappingUpdate(t *testing.T) { "doctor_id": 1, }} - _, err := gou.NewProcess("yao.table.Update", args...).Exec() + _, err := process.New("yao.table.Update", args...).Exec() if err != nil { t.Fatal(err) } - res, err := gou.NewProcess("yao.table.find", "compute", 1).Exec() + res, err := process.New("yao.table.find", "compute", 1).Exec() if err != nil { t.Fatal(err) } @@ -146,12 +146,12 @@ func TestMappingInsert(t *testing.T) { }, } - _, err := gou.NewProcess("yao.table.Insert", args...).Exec() + _, err := process.New("yao.table.Insert", args...).Exec() if err != nil { t.Fatal(err) } - res, err := gou.NewProcess("yao.table.find", "compute", 1).Exec() + res, err := process.New("yao.table.find", "compute", 1).Exec() if err != nil { t.Fatal(err) } diff --git a/widgets/table/process.go b/widgets/table/process.go index bcba7db658..c6b5d31d83 100644 --- a/widgets/table/process.go +++ b/widgets/table/process.go @@ -10,8 +10,10 @@ import ( "strings" "time" - "github.com/yaoapp/gou" "github.com/yaoapp/gou/fs" + "github.com/yaoapp/gou/model" + gouProcess "github.com/yaoapp/gou/process" + "github.com/yaoapp/gou/types" "github.com/yaoapp/kun/any" "github.com/yaoapp/kun/exception" "github.com/yaoapp/kun/log" @@ -23,27 +25,27 @@ import ( // Export process func exportProcess() { - gou.RegisterProcessHandler("yao.table.setting", processSetting) - gou.RegisterProcessHandler("yao.table.xgen", processXgen) - gou.RegisterProcessHandler("yao.table.component", processComponent) - gou.RegisterProcessHandler("yao.table.upload", processUpload) - gou.RegisterProcessHandler("yao.table.download", processDownload) - gou.RegisterProcessHandler("yao.table.search", processSearch) - gou.RegisterProcessHandler("yao.table.get", processGet) - gou.RegisterProcessHandler("yao.table.find", processFind) - gou.RegisterProcessHandler("yao.table.save", processSave) - gou.RegisterProcessHandler("yao.table.create", processCreate) - gou.RegisterProcessHandler("yao.table.insert", processInsert) - gou.RegisterProcessHandler("yao.table.update", processUpdate) - gou.RegisterProcessHandler("yao.table.updatewhere", processUpdateWhere) - gou.RegisterProcessHandler("yao.table.updatein", processUpdateIn) - gou.RegisterProcessHandler("yao.table.delete", processDelete) - gou.RegisterProcessHandler("yao.table.deletewhere", processDeleteWhere) - gou.RegisterProcessHandler("yao.table.deletein", processDeleteIn) - gou.RegisterProcessHandler("yao.table.export", processExport) + gouProcess.Register("yao.table.setting", processSetting) + gouProcess.Register("yao.table.xgen", processXgen) + gouProcess.Register("yao.table.component", processComponent) + gouProcess.Register("yao.table.upload", processUpload) + gouProcess.Register("yao.table.download", processDownload) + gouProcess.Register("yao.table.search", processSearch) + gouProcess.Register("yao.table.get", processGet) + gouProcess.Register("yao.table.find", processFind) + gouProcess.Register("yao.table.save", processSave) + gouProcess.Register("yao.table.create", processCreate) + gouProcess.Register("yao.table.insert", processInsert) + gouProcess.Register("yao.table.update", processUpdate) + gouProcess.Register("yao.table.updatewhere", processUpdateWhere) + gouProcess.Register("yao.table.updatein", processUpdateIn) + gouProcess.Register("yao.table.delete", processDelete) + gouProcess.Register("yao.table.deletewhere", processDeleteWhere) + gouProcess.Register("yao.table.deletein", processDeleteIn) + gouProcess.Register("yao.table.export", processExport) } -func processXgen(process *gou.Process) interface{} { +func processXgen(process *gouProcess.Process) interface{} { tab := MustGet(process) data := process.ArgsMap(1, map[string]interface{}{}) @@ -55,7 +57,7 @@ func processXgen(process *gou.Process) interface{} { return setting } -func processDownload(process *gou.Process) interface{} { +func processDownload(process *gouProcess.Process) interface{} { process.ValidateArgNums(4) tab := MustGet(process) @@ -83,7 +85,7 @@ func processDownload(process *gou.Process) interface{} { } // Create process - p, err := gou.ProcessOf(name, file) + p, err := gouProcess.Of(name, file) if err != nil { log.Error("[downalod] %s.%s %s", tab.ID, field, err.Error()) exception.New("[downalod] %s.%s %s", 400, tab.ID, field, err.Error()).Throw() @@ -99,7 +101,7 @@ func processDownload(process *gou.Process) interface{} { return res } -func processUpload(process *gou.Process) interface{} { +func processUpload(process *gouProcess.Process) interface{} { process.ValidateArgNums(4) tab := MustGet(process) @@ -114,7 +116,7 @@ func processUpload(process *gou.Process) interface{} { } // $file.file - tmpfile, ok := process.Args[3].(gou.UploadFile) + tmpfile, ok := process.Args[3].(types.UploadFile) if !ok { exception.New("parameters error: %v", 400, process.Args[3]).Throw() } @@ -134,7 +136,7 @@ func processUpload(process *gou.Process) interface{} { return res } -func processComponent(process *gou.Process) interface{} { +func processComponent(process *gouProcess.Process) interface{} { process.ValidateArgNums(3) tab := MustGet(process) @@ -163,80 +165,80 @@ func processComponent(process *gou.Process) interface{} { return res } -func processSetting(process *gou.Process) interface{} { +func processSetting(process *gouProcess.Process) interface{} { tab := MustGet(process) process.Args = append(process.Args, process.Args[0]) // table name return tab.Action.Setting.MustExec(process) } -func processSearch(process *gou.Process) interface{} { +func processSearch(process *gouProcess.Process) interface{} { tab := MustGet(process) return tab.Action.Search.MustExec(process) } -func processGet(process *gou.Process) interface{} { +func processGet(process *gouProcess.Process) interface{} { tab := MustGet(process) return tab.Action.Get.MustExec(process) } -func processSave(process *gou.Process) interface{} { +func processSave(process *gouProcess.Process) interface{} { tab := MustGet(process) return tab.Action.Save.MustExec(process) } -func processCreate(process *gou.Process) interface{} { +func processCreate(process *gouProcess.Process) interface{} { tab := MustGet(process) return tab.Action.Create.MustExec(process) } -func processFind(process *gou.Process) interface{} { +func processFind(process *gouProcess.Process) interface{} { tab := MustGet(process) return tab.Action.Find.MustExec(process) } -func processInsert(process *gou.Process) interface{} { +func processInsert(process *gouProcess.Process) interface{} { tab := MustGet(process) return tab.Action.Insert.MustExec(process) } -func processUpdate(process *gou.Process) interface{} { +func processUpdate(process *gouProcess.Process) interface{} { tab := MustGet(process) return tab.Action.Update.MustExec(process) } -func processUpdateWhere(process *gou.Process) interface{} { +func processUpdateWhere(process *gouProcess.Process) interface{} { tab := MustGet(process) return tab.Action.UpdateWhere.MustExec(process) } -func processUpdateIn(process *gou.Process) interface{} { +func processUpdateIn(process *gouProcess.Process) interface{} { process.ValidateArgNums(3) tab := MustGet(process) ids := strings.Split(process.ArgsString(1), ",") - process.Args[1] = gou.QueryParam{ - Wheres: []gou.QueryWhere{ + process.Args[1] = model.QueryParam{ + Wheres: []model.QueryWhere{ {Column: tab.Layout.Primary, OP: "in", Value: ids}, }, } return tab.Action.UpdateIn.MustExec(process) } -func processDelete(process *gou.Process) interface{} { +func processDelete(process *gouProcess.Process) interface{} { tab := MustGet(process) return tab.Action.Delete.MustExec(process) } -func processDeleteWhere(process *gou.Process) interface{} { +func processDeleteWhere(process *gouProcess.Process) interface{} { tab := MustGet(process) return tab.Action.DeleteWhere.MustExec(process) } -func processDeleteIn(process *gou.Process) interface{} { +func processDeleteIn(process *gouProcess.Process) interface{} { process.ValidateArgNums(2) tab := MustGet(process) ids := strings.Split(process.ArgsString(1), ",") - process.Args[1] = gou.QueryParam{ - Wheres: []gou.QueryWhere{ + process.Args[1] = model.QueryParam{ + Wheres: []model.QueryWhere{ {Column: tab.Layout.Primary, OP: "in", Value: ids}, }, } @@ -244,10 +246,10 @@ func processDeleteIn(process *gou.Process) interface{} { } // processExport yao.table.Export (:table, :queryParam, :chunkSize) -func processExport(process *gou.Process) interface{} { +func processExport(process *gouProcess.Process) interface{} { process.ValidateArgNums(1) tab := MustGet(process) // 0 - params := process.ArgsQueryParams(1, gou.QueryParam{}) + params := process.ArgsQueryParams(1, types.QueryParam{}) pagesize := process.ArgsInt(2, 50) // Filename diff --git a/widgets/table/process_test.go b/widgets/table/process_test.go index 4f2a0149cf..4b2ab5c8f5 100644 --- a/widgets/table/process_test.go +++ b/widgets/table/process_test.go @@ -7,9 +7,11 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/yaoapp/gou" "github.com/yaoapp/gou/fs" + "github.com/yaoapp/gou/model" + "github.com/yaoapp/gou/process" "github.com/yaoapp/gou/session" + "github.com/yaoapp/gou/types" "github.com/yaoapp/kun/any" "github.com/yaoapp/yao/config" "github.com/yaoapp/yao/helper" @@ -29,7 +31,7 @@ func TestProcessSearch(t *testing.T) { } args := []interface{}{"pet", params, 1, 5} - res, err := gou.NewProcess("yao.table.search", args...).Exec() + res, err := process.New("yao.table.search", args...).Exec() if err != nil { t.Fatal(err) } @@ -55,7 +57,7 @@ func TestProcessGet(t *testing.T) { } args := []interface{}{"pet", params} - res, err := gou.NewProcess("yao.table.get", args...).Exec() + res, err := process.New("yao.table.get", args...).Exec() if err != nil { t.Fatal(err) } @@ -75,7 +77,7 @@ func TestProcessFind(t *testing.T) { testData(t) args := []interface{}{"pet", 1} - res, err := gou.NewProcess("yao.table.find", args...).Exec() + res, err := process.New("yao.table.find", args...).Exec() if err != nil { t.Fatal(err) } @@ -98,13 +100,13 @@ func TestProcessSave(t *testing.T) { "doctor_id": 1, }} - res, err := gou.NewProcess("yao.table.Save", args...).Exec() + res, err := process.New("yao.table.Save", args...).Exec() if err != nil { t.Fatal(err) } assert.Equal(t, "4", fmt.Sprintf("%v", res)) - res, err = gou.NewProcess("yao.table.find", "pet", res).Exec() + res, err = process.New("yao.table.find", "pet", res).Exec() if err != nil { t.Fatal(err) } @@ -128,13 +130,13 @@ func TestProcessCreate(t *testing.T) { "doctor_id": 1, }} - res, err := gou.NewProcess("yao.table.Create", args...).Exec() + res, err := process.New("yao.table.Create", args...).Exec() if err != nil { t.Fatal(err) } assert.Equal(t, "6", fmt.Sprintf("%v", res)) - res, err = gou.NewProcess("yao.table.find", "pet", res).Exec() + res, err = process.New("yao.table.find", "pet", res).Exec() if err != nil { t.Fatal(err) } @@ -157,12 +159,12 @@ func TestProcessUpdate(t *testing.T) { "doctor_id": 1, }} - _, err := gou.NewProcess("yao.table.Update", args...).Exec() + _, err := process.New("yao.table.Update", args...).Exec() if err != nil { t.Fatal(err) } - res, err := gou.NewProcess("yao.table.find", "pet", 1).Exec() + res, err := process.New("yao.table.find", "pet", 1).Exec() if err != nil { t.Fatal(err) } @@ -187,12 +189,12 @@ func TestProcessUpdateWhere(t *testing.T) { "doctor_id": 1, }} - _, err := gou.NewProcess("yao.table.UpdateWhere", args...).Exec() + _, err := process.New("yao.table.UpdateWhere", args...).Exec() if err != nil { t.Fatal(err) } - res, err := gou.NewProcess("yao.table.find", "pet", 1).Exec() + res, err := process.New("yao.table.find", "pet", 1).Exec() if err != nil { t.Fatal(err) } @@ -216,12 +218,12 @@ func TestProcessUpdateIn(t *testing.T) { "doctor_id": 1, }} - _, err := gou.NewProcess("yao.table.UpdateIn", args...).Exec() + _, err := process.New("yao.table.UpdateIn", args...).Exec() if err != nil { t.Fatal(err) } - res, err := gou.NewProcess("yao.table.find", "pet", 1).Exec() + res, err := process.New("yao.table.find", "pet", 1).Exec() if err != nil { t.Fatal(err) } @@ -242,12 +244,12 @@ func TestProcessInsert(t *testing.T) { }, } - _, err := gou.NewProcess("yao.table.Insert", args...).Exec() + _, err := process.New("yao.table.Insert", args...).Exec() if err != nil { t.Fatal(err) } - res, err := gou.NewProcess("yao.table.find", "pet", 1).Exec() + res, err := process.New("yao.table.find", "pet", 1).Exec() if err != nil { t.Fatal(err) } @@ -262,12 +264,12 @@ func TestProcessDelete(t *testing.T) { testData(t) args := []interface{}{"pet", 1} - _, err := gou.NewProcess("yao.table.Delete", args...).Exec() + _, err := process.New("yao.table.Delete", args...).Exec() if err != nil { t.Fatal(err) } - _, err = gou.NewProcess("yao.table.find", "pet", 1).Exec() + _, err = process.New("yao.table.find", "pet", 1).Exec() assert.Contains(t, err.Error(), "ID=1") } @@ -280,12 +282,12 @@ func TestProcessDeleteWhere(t *testing.T) { map[string]interface{}{"wheres": []map[string]interface{}{{"column": "id", "value": 1}}}, } - _, err := gou.NewProcess("yao.table.DeleteWhere", args...).Exec() + _, err := process.New("yao.table.DeleteWhere", args...).Exec() if err != nil { t.Fatal(err) } - _, err = gou.NewProcess("yao.table.find", "pet", 1).Exec() + _, err = process.New("yao.table.find", "pet", 1).Exec() assert.Contains(t, err.Error(), "ID=1") } @@ -295,12 +297,12 @@ func TestProcessDeleteIn(t *testing.T) { testData(t) args := []interface{}{"pet", "1"} - _, err := gou.NewProcess("yao.table.DeleteIn", args...).Exec() + _, err := process.New("yao.table.DeleteIn", args...).Exec() if err != nil { t.Fatal(err) } - _, err = gou.NewProcess("yao.table.find", "pet", 1).Exec() + _, err = process.New("yao.table.find", "pet", 1).Exec() assert.Contains(t, err.Error(), "ID=1") } @@ -321,7 +323,7 @@ func TestProcessComponent(t *testing.T) { }, } - res, err := gou.NewProcess("yao.table.Component", args...).Exec() + res, err := process.New("yao.table.Component", args...).Exec() if err != nil { t.Fatal(err) } @@ -345,7 +347,7 @@ func TestProcessComponentError(t *testing.T) { "remote", map[string]interface{}{"select": []string{"name", "status"}, "limit": 2}, } - _, err := gou.NewProcess("yao.table.Component", args...).Exec() + _, err := process.New("yao.table.Component", args...).Exec() assert.Contains(t, err.Error(), "fields.filter.edit.props.状态.::not-exist") } @@ -357,10 +359,10 @@ func TestProcessUpload(t *testing.T) { "pet", "fields.table.相关图片.edit.props", "api", - gou.UploadFile{TempFile: tempFile(t)}, + types.UploadFile{TempFile: tempFile(t)}, } - res, err := gou.NewProcess("yao.table.Upload", args...).Exec() + res, err := process.New("yao.table.Upload", args...).Exec() if err != nil { t.Fatal(err) } @@ -383,7 +385,7 @@ func TestProcessDownload(t *testing.T) { } args := []interface{}{"pet", "images", "/text.txt", jwt.Token} - res, err := gou.NewProcess("yao.table.Download", args...).Exec() + res, err := process.New("yao.table.Download", args...).Exec() if err != nil { t.Fatal(err) } @@ -399,7 +401,7 @@ func TestProcessSetting(t *testing.T) { clear(t) testData(t) args := []interface{}{"pet"} - res, err := gou.NewProcess("yao.table.Setting", args...).Exec() + res, err := process.New("yao.table.Setting", args...).Exec() if err != nil { t.Fatal(err) } @@ -418,7 +420,7 @@ func TestProcessXgen(t *testing.T) { clear(t) testData(t) args := []interface{}{"pet"} - res, err := gou.NewProcess("yao.table.Xgen", args...).Exec() + res, err := process.New("yao.table.Xgen", args...).Exec() if err != nil { t.Fatal(err) } @@ -448,7 +450,7 @@ func TestProcessXgenWithPermissions(t *testing.T) { }) args := []interface{}{"pet"} - res, err := gou.NewProcess("yao.table.Xgen", args...).Exec() + res, err := process.New("yao.table.Xgen", args...).Exec() if err != nil { t.Fatal(err) } @@ -464,7 +466,7 @@ func TestProcessXgenWithPermissions(t *testing.T) { assert.Len(t, data.Get("table.operation.actions"), 4) session.Global().Set("__permissions", nil) - res, err = gou.NewProcess("yao.table.Xgen", args...).Exec() + res, err = process.New("yao.table.Xgen", args...).Exec() if err != nil { t.Fatal(err) } @@ -485,8 +487,8 @@ func TestProcessExport(t *testing.T) { load(t) clear(t) testData(t) - args := []interface{}{"pet", gou.QueryParam{Wheres: []gou.QueryWhere{{Column: "mode", Value: "enabled"}}}, 2} - response := gou.NewProcess("yao.table.Export", args...).Run() + args := []interface{}{"pet", model.QueryParam{Wheres: []model.QueryWhere{{Column: "mode", Value: "enabled"}}}, 2} + response := process.New("yao.table.Export", args...).Run() assert.NotNil(t, response) fs := fs.MustGet("system") size, _ := fs.Size(response.(string)) @@ -503,7 +505,7 @@ func load(t *testing.T) { } func testData(t *testing.T) { - pet := gou.Select("pet") + pet := model.Select("pet") err := pet.Insert( []string{"name", "type", "status", "mode", "stay", "cost", "doctor_id"}, [][]interface{}{ @@ -533,7 +535,7 @@ func tempFile(t *testing.T) string { } func clear(t *testing.T) { - for _, m := range gou.Models { + for _, m := range model.Models { err := m.DropTable() if err != nil { t.Fatal(err) diff --git a/widgets/table/table.go b/widgets/table/table.go index 750fcd0c76..379dcec062 100644 --- a/widgets/table/table.go +++ b/widgets/table/table.go @@ -6,7 +6,7 @@ import ( "strings" jsoniter "github.com/json-iterator/go" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/process" "github.com/yaoapp/kun/exception" "github.com/yaoapp/kun/log" "github.com/yaoapp/yao/config" @@ -208,8 +208,8 @@ func Get(table interface{}) (*DSL, error) { switch table.(type) { case string: id = table.(string) - case *gou.Process: - id = table.(*gou.Process).ArgsString(0) + case *process.Process: + id = table.(*process.Process).ArgsString(0) default: return nil, fmt.Errorf("%v type does not support", table) } diff --git a/widgets/table/table_test.go b/widgets/table/table_test.go index b50a5f6fed..38d86eefb2 100644 --- a/widgets/table/table_test.go +++ b/widgets/table/table_test.go @@ -9,7 +9,6 @@ import ( "github.com/yaoapp/yao/flow" "github.com/yaoapp/yao/fs" "github.com/yaoapp/yao/model" - "github.com/yaoapp/yao/runtime" "github.com/yaoapp/yao/script" _ "github.com/yaoapp/yao/utils" "github.com/yaoapp/yao/widgets/app" @@ -37,7 +36,7 @@ func TestLoadID(t *testing.T) { } func prepare(t *testing.T, language ...string) { - runtime.Load(config.Conf) + // runtime.Load(config.Conf) err := test.LoadEngine(language...) if err != nil { t.Fatal(err) diff --git a/widgets/test/engine.go b/widgets/test/engine.go index 9b9ca8ccfb..05d2c3680c 100644 --- a/widgets/test/engine.go +++ b/widgets/test/engine.go @@ -2,24 +2,21 @@ package test import ( "os" - "path/filepath" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/model" "github.com/yaoapp/yao/config" "github.com/yaoapp/yao/i18n" - "github.com/yaoapp/yao/model" - "github.com/yaoapp/yao/runtime" "github.com/yaoapp/yao/share" ) // LoadEngine load engine func LoadEngine(language ...string) error { - runtime.Load(config.Conf) + // runtime.Load(config.Conf) i18n.Load(config.Conf) share.DBConnect(config.Conf.DB) // removed later - gou.LoadCrypt(`{}`, "PASSWORD") - gou.LoadCrypt(`{}`, "AES") + model.WithCrypt([]byte(`{}`), "PASSWORD") + model.WithCrypt([]byte(`{}`), "AES") // Session server err := share.SessionStart() @@ -30,10 +27,10 @@ func LoadEngine(language ...string) error { // load engine models dev := os.Getenv("YAO_DEV") if dev != "" { - err := model.LoadFrom(filepath.Join(dev, "yao", "models"), "xiang.") - if err != nil { - return err - } + // err := model.LoadFrom(filepath.Join(dev, "yao", "models"), "xiang.") + // if err != nil { + // return err + // } } return nil diff --git a/widgets/test/request.go b/widgets/test/request.go index fe4133581c..2bd3eb7e78 100644 --- a/widgets/test/request.go +++ b/widgets/test/request.go @@ -9,7 +9,8 @@ import ( "time" jsoniter "github.com/json-iterator/go" - "github.com/yaoapp/gou" + "github.com/yaoapp/gou/model" + "github.com/yaoapp/gou/process" "github.com/yaoapp/gou/session" "github.com/yaoapp/yao/helper" ) @@ -189,8 +190,8 @@ func (p *Response) To(v interface{}) error { // AutoLogin auto login func AutoLogin(id int) (map[string]interface{}, error) { - user := gou.Select("xiang.user") - row, err := user.Find(id, gou.QueryParam{Select: []interface{}{"id", "name", "type", "email", "mobile", "extra", "status"}}) + user := model.Select("xiang.user") + row, err := user.Find(id, model.QueryParam(model.QueryParam{Select: []interface{}{"id", "name", "type", "email", "mobile", "extra", "status"}})) if err != nil { return nil, err } @@ -205,7 +206,7 @@ func AutoLogin(id int) (map[string]interface{}, error) { session.Global().ID(sid).Set("user", row) session.Global().ID(sid).Set("issuer", "xiang") - p, err := gou.ProcessOf("yao.app.menu") + p, err := process.Of("yao.app.menu") if err != nil { return nil, err } diff --git a/widgets/test/server.go b/widgets/test/server.go index e517ec8fc1..9a7c8beda1 100644 --- a/widgets/test/server.go +++ b/widgets/test/server.go @@ -5,8 +5,6 @@ import ( "testing" "github.com/gin-gonic/gin" - "github.com/yaoapp/gou" - "github.com/yaoapp/yao/config" "github.com/yaoapp/yao/helper" "github.com/yaoapp/yao/share" ) @@ -22,19 +20,19 @@ func Start(t *testing.T, guards map[string]gin.HandlerFunc, port int) error { return err } - gin.SetMode(gin.ReleaseMode) - gou.SetHTTPGuards(guards) - gou.ServeHTTP( - gou.Server{ - Host: "127.0.0.1", - Port: port, - Root: "/api", - Allows: config.Conf.AllowFrom, - }, - shutdown, func(s gou.Server) { - shutdownComplete <- true - }, - ) + // gin.SetMode(gin.ReleaseMode) + // gou.SetHTTPGuards(guards) + // gou.ServeHTTP( + // gou.Server{ + // Host: "127.0.0.1", + // Port: port, + // Root: "/api", + // Allows: config.Conf.AllowFrom, + // }, + // shutdown, func(s gou.Server) { + // shutdownComplete <- true + // }, + // ) return nil } diff --git a/widgets/widgets_test.go b/widgets/widgets_test.go index 71e17d6c9f..6b3ea6dc71 100644 --- a/widgets/widgets_test.go +++ b/widgets/widgets_test.go @@ -8,7 +8,6 @@ import ( "github.com/yaoapp/yao/config" "github.com/yaoapp/yao/i18n" "github.com/yaoapp/yao/model" - "github.com/yaoapp/yao/runtime" "github.com/yaoapp/yao/script" "github.com/yaoapp/yao/share" "github.com/yaoapp/yao/widgets/test" @@ -27,7 +26,7 @@ func prepare(t *testing.T, language ...string) { t.Fatal(err) } - runtime.Load(config.Conf) + // runtime.Load(config.Conf) i18n.Load(config.Conf) share.DBConnect(config.Conf.DB) // removed later diff --git a/xfs/process.go b/xfs/process.go deleted file mode 100644 index a2baf54f2d..0000000000 --- a/xfs/process.go +++ /dev/null @@ -1,166 +0,0 @@ -package xfs - -import ( - "crypto/md5" - "encoding/hex" - "fmt" - "os" - "path/filepath" - "strings" - "time" - - "github.com/aliyun/alibaba-cloud-sdk-go/services/sts" - "github.com/yaoapp/gou" - "github.com/yaoapp/gou/session" - "github.com/yaoapp/kun/any" - "github.com/yaoapp/kun/exception" - "github.com/yaoapp/kun/maps" - "github.com/yaoapp/xun" - "github.com/yaoapp/yao/data" - "github.com/yaoapp/yao/helper" - "github.com/yaoapp/yao/share" -) - -// DEPRECATED -func init() { - // 注册处理器 - gou.RegisterProcessHandler("xiang.fs.Upload", processUpload) - gou.RegisterProcessHandler("xiang.fs.GetToken", processGetToken) - gou.RegisterProcessHandler("xiang.fs.GetURL", processGetURL) - gou.RegisterProcessHandler("xiang.fs.ReadFile", processReadFile) -} - -// processUpload 上传文件到本地服务器 -func processUpload(process *gou.Process) interface{} { - process.ValidateArgNums(1) - tmpfile, ok := process.Args[0].(xun.UploadFile) - if !ok { - exception.New("上传文件参数错误", 400, process.Args[0]).Throw() - } - - hash := md5.Sum([]byte(time.Now().Format("20060102-15:04:05"))) - fingerprint := string(hex.EncodeToString(hash[:])) - fingerprint = strings.ToUpper(fingerprint) - - dir := time.Now().Format("20060102") - ext := filepath.Ext(tmpfile.Name) - filename := filepath.Join(dir, fmt.Sprintf("%s%s", fingerprint, ext)) - Stor.MustMkdirAll(dir, os.ModePerm) - - content, err := New("/").ReadFile(tmpfile.TempFile) - if err != nil { - exception.New("不能读取上传文件 %s", 500, err.Error()).Throw() - } - - Stor.MustWriteFile(filename, content, os.ModePerm) - return filename -} - -// processGetContent 返回文件正文 -func processReadFile(process *gou.Process) interface{} { - process.ValidateArgNums(1) - filename := process.ArgsString(0) - encode := process.ArgsBool(1, true) - - stats, err := Stor.Stat(filename) - if err != nil { - exception.New("读取文件信息失败 %s", 500, err.Error()).Throw() - } - - var content string - body := Stor.MustReadFile(filename) - if encode { - content = Encode(body) - } else { - content = string(body) - } - - return maps.Map{ - "size": stats.Size(), - "content": content, - } -} - -// processGetToken 上传文件到腾讯云对象存储 COS -func processGetToken(process *gou.Process) interface{} { - process.ValidateArgNums(1) - name := process.ArgsString(0, "oss") - // bucket := process.ArgsString(1) - if name != "oss" { - exception.New("暂时支持 oss 存储", 400).Throw() - } - - if share.App.Storage.OSS == nil { - exception.New("未配置 OSS 存储", 400).Throw() - } - - app := share.App.Storage.OSS - id := strings.Split(app.Endpoint, ".")[0] - client, err := sts.NewClientWithAccessKey(id, app.ID, app.Secret) - if err != nil { - exception.New("配置错误 %s", 400, err.Error()).Throw() - } - - //构建请求对象。 - request := sts.CreateAssumeRoleRequest() - request.Scheme = "https" - request.Domain = "sts.aliyuncs.com" - - //设置参数。关于参数含义和设置方法,请参见API参考。 - request.RoleArn = app.RoleArn - request.RoleSessionName = app.SessionName - - //发起请求,并得到响应。 - response, err := client.AssumeRole(request) - if err != nil { - exception.New("配置错误 %s", 400, err.Error()).Throw() - } - - res := any.Of(response.Credentials).Map() - res.Set("Endpoint", app.Endpoint) - return res.MapStrAny -} - -// 临时 -const svg404 = ` - - - - Created with Fabric.js 4.2.0 - - - - - - - - - 404 - - -` - -// processGetURL 返回文件CDN地址 -func processGetURL(process *gou.Process) interface{} { - if len(process.Args) < 1 { - return string(data.MustAsset("yao/data/icons/404.png")) - } - - token := process.ArgsString(2) - if token == "" { - exception.New("token is null", 403).Throw() - } - - claims := helper.JwtValidate(token) - userID, err := session.Global().ID(claims.SID).Get("user_id") - if err != nil || userID == nil { - exception.New("session expired", 403).Throw() - } - - filename := process.ArgsString(0) - body, err := Stor.ReadFile(filename) - if err != nil { - return string(data.MustAsset("yao/data/icons/404.png")) - } - return string(body) -} diff --git a/xfs/process_test.go b/xfs/process_test.go deleted file mode 100644 index 415c6cd1ef..0000000000 --- a/xfs/process_test.go +++ /dev/null @@ -1,57 +0,0 @@ -package xfs - -import ( - "os" - "testing" - - "github.com/yaoapp/yao/share" -) - -// DEPRECATED - -func init() { - share.App = share.AppInfo{ - Storage: share.AppStorage{ - Default: "oss", - OSS: &share.AppStorageOSS{ - Endpoint: "oss-cn-hangzhou.aliyuncs.com", - ID: os.Getenv("OSS_TEST_ID"), - Secret: os.Getenv("OSS_TEST_SECRET"), - RoleArn: "acs:ram::31524094:role/ramosstest", - SessionName: "SessionTest", - }, - }, - } -} -func TestProcessGetToken(t *testing.T) { - - // the oss support will be using new process - - // args := []interface{}{"oss"} - // process := gou.NewProcess("xiang.fs.GetToken", args...) - // response := processGetToken(process) - // assert.NotNil(t, response) - // res := any.Of(response).Map() - // assert.True(t, res.Has("AccessKeyId")) - // assert.True(t, res.Has("AccessKeySecret")) - // assert.True(t, res.Has("Expiration")) - // assert.True(t, res.Has("SecurityToken")) - // assert.True(t, res.Has("Endpoint")) - - // // 使用token - // client, err := oss.New( - // res.Get("Endpoint").(string), - // res.Get("AccessKeyId").(string), - // res.Get("AccessKeySecret").(string), - // oss.SecurityToken(res.Get("SecurityToken").(string)), - // ) - // assert.Nil(t, err) - - // bucket, err := client.Bucket("image-appcook") - // assert.Nil(t, err) - - // // 上传字符串。 - // now := fmt.Sprintf("%d", time.Now().UnixNano()) - // err = bucket.PutObject("xiang/unit-test."+now+".txt", strings.NewReader(now)) - // assert.Nil(t, err) -} diff --git a/xfs/xfs.go b/xfs/xfs.go deleted file mode 100644 index 6dbea5b329..0000000000 --- a/xfs/xfs.go +++ /dev/null @@ -1,263 +0,0 @@ -package xfs - -import ( - "archive/tar" - "archive/zip" - "bytes" - "encoding/base64" - "fmt" - "io" - "io/fs" - "os" - "path/filepath" - "strings" - - "github.com/spf13/afero" - "github.com/spf13/afero/tarfs" - "github.com/spf13/afero/zipfs" - "github.com/yaoapp/kun/exception" - "github.com/yaoapp/yao/config" -) - -// DEPRECATED - -// Stor 文件系统实例 -var Stor Xfs - -// Xfs 文件系统 -type Xfs struct { - Root string // Root - afero.Afero -} - -// Fs 文件系统 Interface -type Fs interface { - afero.Fs -} - -// File file fs -type File interface { - afero.File -} - -func init() { - Stor = New(filepath.Join(config.Conf.Root, "data")) -} - -// New 创建文件系统 -func New(path string) Xfs { - pinfo := strings.Split(path, "://") - fs := "fs" - root := path - if len(pinfo) == 2 { - fs = pinfo[0] - root = strings.TrimPrefix(path, fmt.Sprintf("%s://", fs)) - } - - xfs := Xfs{ - Root: root, - } - switch fs { - case "fs", "file": - xfs.Fs = afero.NewBasePathFs(afero.NewOsFs(), root) - break - case "mem", "memory": - xfs.Fs = afero.NewMemMapFs() - break - default: - exception.New("尚未支持 %s 文件系统", 500, fs).Throw() - } - - // exists := xfs.MustDirExists("/") - // if !exists && root != "/" { - // xfs.MustMkdirAll("/", os.ModePerm) - // } - - return xfs -} - -// NewZip 创建Zip文件系统 -func NewZip(zipfile string) Xfs { - r, err := zip.OpenReader(zipfile) - if err != nil { - exception.New("ZIP文件打开失败 %s ", 500, err).Throw() - } - return Xfs{ - Root: "/", - Afero: afero.Afero{ - Fs: zipfs.New(&r.Reader), - }, - } -} - -// NewTar tar文件系统 -func NewTar(tarfile string) Xfs { - var buf bytes.Buffer - r := tar.NewReader(&buf) - return Xfs{ - Root: "/", - Afero: afero.Afero{ - Fs: tarfs.New(r), - }, - } -} - -// Encode Base64编码 -func Encode(content []byte) string { - return base64.StdEncoding.EncodeToString(content) -} - -// Decode Base64编码 -func Decode(content []byte) []byte { - var data []byte - _, err := base64.StdEncoding.Decode(data, content) - if err != nil { - exception.New("文件解码失败 %s ", 500, err).Throw() - } - return data -} - -// DecodeString Base64编码 -func DecodeString(content string) string { - dst, err := base64.StdEncoding.DecodeString(content) - if err != nil { - exception.New("文件解码失败 %s ", 500, err).Throw() - } - return string(dst) -} - -// MustOpen 打开文件 -func (xfs *Xfs) MustOpen(filename string) File { - file, err := xfs.Open(filename) - if err != nil { - exception.New("打开文件失败 %s 失败 ", 500, filename).Throw() - } - return file -} - -// MustReadFile 阅读文件内容 -func (xfs *Xfs) MustReadFile(filename string) []byte { - bytes, err := xfs.ReadFile(filename) - if err != nil { - exception.New("阅读文件内容失败 %s 失败 %s ", 500, filename, err).Throw() - } - return bytes -} - -// MustReadDir 阅读文件夹内容 -func (xfs *Xfs) MustReadDir(dirname string) []os.FileInfo { - fileinfos, err := xfs.ReadDir(dirname) - if err != nil { - exception.New("阅读文件夹失败 %s 失败 ", 500, dirname).Throw() - } - return fileinfos -} - -// MustExists 检查文件是否存在 -func (xfs *Xfs) MustExists(filename string) bool { - has, err := xfs.Exists(filename) - if err != nil { - exception.New("检查文件失败 %s 失败 ", 500, filename).Throw() - } - return has -} - -// MustDirExists 检查文件夹是否存在 -func (xfs *Xfs) MustDirExists(dirname string) bool { - res, err := xfs.DirExists(dirname) - if err != nil { - exception.New("检查文件夹 %s 失败 ", 500, dirname).Throw() - } - return res -} - -// MustMkdirAll 创建文件夹及子文件夹 -func (xfs *Xfs) MustMkdirAll(dirname string, pterm fs.FileMode) { - err := xfs.MkdirAll(dirname, pterm) - if err != nil { - exception.New("创建文件夹及子文件 %s 失败 ", 500, dirname).Throw() - } -} - -// MustMkdir 创建文件夹 -func (xfs *Xfs) MustMkdir(dirname string, pterm fs.FileMode) { - err := xfs.Mkdir(dirname, pterm) - if err != nil { - exception.New("创建文件夹 %s 失败 ", 500, dirname).Throw() - } -} - -// MustIsDir 是否为文件夹 -func (xfs *Xfs) MustIsDir(dirname string) bool { - isdir, err := xfs.IsDir(dirname) - if err != nil { - exception.New("创建文件夹 %s 失败 ", 500, dirname).Throw() - } - return isdir -} - -// MustIsEmpty 文件是否为空 -func (xfs *Xfs) MustIsEmpty(filename string) bool { - isEmpty, err := xfs.IsEmpty(filename) - if err != nil { - exception.New("检查文件是否为空 %s 失败 ", 500, filename).Throw() - } - return isEmpty - -} - -// GetTempDir 临时目录 -func (xfs *Xfs) GetTempDir(subPath string) string { - return afero.GetTempDir(xfs.Fs, subPath) -} - -// MustTempDir 创建临时文件夹 -func (xfs *Xfs) MustTempDir(dirname string, prefix string) string { - name, err := xfs.TempDir(dirname, prefix) - if err != nil { - exception.New("创建文件夹 %s %s 失败 ", 500, dirname, prefix).Throw() - } - return name -} - -// MustTempFile 临时文件 -func (xfs *Xfs) MustTempFile(dirname, prefix string) File { - f, err := xfs.TempFile(dirname, prefix) - if err != nil { - exception.New("创建临时文件 %s %s 失败 ", 500, dirname, prefix).Throw() - } - return f -} - -// MustWalk 文件夹遍历 -func (xfs *Xfs) MustWalk(root string, walkFn filepath.WalkFunc) { - err := xfs.Walk(root, walkFn) - if err != nil { - exception.New("遍历文件夹 %s 失败 ", 500, root).Throw() - } -} - -// MustWriteFile 写入文件 -func (xfs *Xfs) MustWriteFile(filename string, data []byte, perm os.FileMode) { - err := xfs.WriteFile(filename, data, perm) - if err != nil { - exception.New("写入文件 %s 失败 ", 500, filename).Throw() - } -} - -// MustFileContainsBytes 文件是否包含内容 -func (xfs *Xfs) MustFileContainsBytes(filename string, subslice []byte) bool { - has, err := xfs.FileContainsBytes(filename, subslice) - if err != nil { - exception.New("检查文件是否包含内容 %s 失败 ", 500, filename).Throw() - } - return has -} - -// MustSafeWriteReader 检查文件能否写入 -func (xfs *Xfs) MustSafeWriteReader(filename string, r io.Reader) { - err := xfs.SafeWriteReader(filename, r) - if err != nil { - exception.New("检查文件是否可以写入 Reader %s 失败 ", 500, filename).Throw() - } -} diff --git a/xfs/xfs_test.go b/xfs/xfs_test.go deleted file mode 100644 index c21a279ab1..0000000000 --- a/xfs/xfs_test.go +++ /dev/null @@ -1,18 +0,0 @@ -package xfs - -import ( - "os" - "testing" - - "github.com/stretchr/testify/assert" -) - -// DEPRECATED - -func TestOSFsMustMkdirAll(t *testing.T) { - // fs := New(config.Conf.Source) - fs := New(os.Getenv("YAO_DEV")) - assert.NotPanics(t, func() { - fs.MustMkdirAll("/.tmp/unit-test/dir", os.ModePerm) - }) -}