Skip to content

Commit

Permalink
Merge pull request YaoApp#728 from trheyi/main
Browse files Browse the repository at this point in the history
Optimize $backend function call
  • Loading branch information
trheyi authored Aug 4, 2024
2 parents 346a310 + d170ab6 commit 19ff6c7
Show file tree
Hide file tree
Showing 9 changed files with 140 additions and 79 deletions.
122 changes: 61 additions & 61 deletions data/bindata.go

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion sui/api/build_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ func TestCompile(t *testing.T) {
defer clean()

page := testPage(t)
html, warnings, err := page.Compile(nil, &core.BuildOption{KeepPageTag: false})
html, _, warnings, err := page.Compile(nil, &core.BuildOption{KeepPageTag: false})
if err != nil {
t.Fatalf("Compile error: %v", err)
}
Expand Down
31 changes: 26 additions & 5 deletions sui/api/run.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package api

import (
"path/filepath"

"github.com/gin-gonic/gin"
"github.com/yaoapp/gou/process"
"github.com/yaoapp/kun/exception"
Expand Down Expand Up @@ -36,6 +38,17 @@ func Run(process *process.Process) interface{} {
return nil
}

if payload["page"] == nil {
exception.New("The page is required", 400).Throw()
return nil
}

page, ok := payload["page"].(string)
if !ok {
exception.New("The page must be a string", 400).Throw()
return nil
}

args := []interface{}{}
if payload["args"] != nil {
args, ok = payload["args"].([]interface{})
Expand All @@ -45,7 +58,7 @@ func Run(process *process.Process) interface{} {
}
}

ctx.Request.URL.Path = route
ctx.Request.URL.Path = page
r, _, err := NewRequestContext(ctx)
if err != nil {
exception.Err(err, 500).Throw()
Expand All @@ -61,7 +74,7 @@ func Run(process *process.Process) interface{} {
c, _, err = r.MakeCache()
if err != nil {
log.Error("[SUI] Can't make cache, %s %s error: %s", route, method, err.Error())
exception.New("Can't make cache, please the route and method is correct, get more information from the log.", 500).Throw()
exception.New("Can't make cache, the route and method is correct, get more information from the log.", 500).Throw()
return nil
}
}
Expand All @@ -78,12 +91,20 @@ func Run(process *process.Process) interface{} {
return nil
}

if c.Script == nil {
exception.New("Script not found", 500).Throw()
// Load the script
file := filepath.Join("/public", route)
script, err := core.LoadScript(file, r.Request.DisableCache())
if err != nil {
exception.New("Can't load the script (%s), get more information from the log.", 500, route).Throw()
return nil
}

if script == nil {
exception.New("Script not found (%s)", 404, route)
return nil
}

scriptCtx, err := c.Script.NewContext(process.Sid, nil)
scriptCtx, err := script.NewContext(process.Sid, nil)
if err != nil {
exception.Err(err, 500).Throw()
return nil
Expand Down
6 changes: 6 additions & 0 deletions sui/core/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ func (page *Page) Build(ctx *BuildContext, option *BuildOption) (*goquery.Docume

body := doc.Find("body")
body.SetAttr("s:ns", namespace)
body.SetAttr("s:public", option.PublicRoot) // Save public root
body.SetAttr("s:assets", option.AssetRoot)

// Bind the Page events
if !option.JitMode {
page.BindEvent(ctx, doc.Selection, "__page", true)
Expand Down Expand Up @@ -218,6 +221,9 @@ func (page *Page) BuildAsComponent(sel *goquery.Selection, ctx *BuildContext, op

// Pass the component props
first := body.Children().First()
first.SetAttr("s:public", option.PublicRoot) // Save public root
first.SetAttr("s:assets", option.AssetRoot)

// page.copyProps(ctx, sel, first, attrs...)
page.parseProps(sel, first, attrs...)
page.copySlots(sel, first)
Expand Down
12 changes: 7 additions & 5 deletions sui/core/compile.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,11 @@ var importAssetsRe = regexp.MustCompile(`import\s*\t*\n*\s*['"]@assets\/([^'"]+)
var AssetsRe = regexp.MustCompile(`[` + quoteRe + `]@assets\/([^` + quoteRe + `]+)[` + quoteRe + `]`) // '@assets/foo.js' or "@assets/foo.js" or `@assets/foo`

// Compile the page
func (page *Page) Compile(ctx *BuildContext, option *BuildOption) (string, []string, error) {
func (page *Page) Compile(ctx *BuildContext, option *BuildOption) (string, string, []string, error) {

doc, warnings, err := page.Build(ctx, option)
if err != nil {
return "", warnings, fmt.Errorf("Page build error: %s", err.Error())
return "", "", warnings, fmt.Errorf("Page build error: %s", err.Error())
}

if warnings != nil && len(warnings) > 0 {
Expand Down Expand Up @@ -62,9 +62,11 @@ func (page *Page) Compile(ctx *BuildContext, option *BuildOption) (string, []str
page.Config = page.GetConfig()

// Config Data
config := ""
if page.Config != nil {
config = page.ExportConfig()
body.AppendHtml("\n\n" + `<script name="config" type="json">` + "\n" +
page.ExportConfig() +
config +
"\n</script>\n\n",
)
}
Expand Down Expand Up @@ -94,11 +96,11 @@ func (page *Page) Compile(ctx *BuildContext, option *BuildOption) (string, []str
page.ReplaceDocument(doc)
html, err := doc.Html()
if err != nil {
return "", warnings, fmt.Errorf("Generate html error: %s", err.Error())
return "", "", warnings, fmt.Errorf("Generate html error: %s", err.Error())
}

// @todo: Minify the html
return html, warnings, nil
return html, config, warnings, nil
}

// CompileAsComponent compile the page as component
Expand Down
4 changes: 4 additions & 0 deletions sui/core/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ var allowUsePropAttrs = map[string]bool{
"s:event": true,
"s:event-cn": true,
"s:render": true,
"s:public": true,
"s:assets": true,
}

var keepAttrs = map[string]bool{
Expand All @@ -83,6 +85,8 @@ var keepAttrs = map[string]bool{
"s:event": true,
"s:event-cn": true,
"s:render": true,
"s:public": true,
"s:assets": true,
}

// NewTemplateParser create a new template parser
Expand Down
3 changes: 2 additions & 1 deletion sui/libsui/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,7 @@ function __sui_store(elm) {

async function __sui_backend_call(
route: string,
page: string,
method: string,
...args: any
): Promise<any> {
Expand All @@ -229,7 +230,7 @@ async function __sui_backend_call(
"Content-Type": "application/json",
Cookie: document.cookie,
};
const payload = { method, args };
const payload = { method, args, page };
try {
const body = JSON.stringify(payload);
const response = await fetch(url, { method: "POST", headers, body: body });
Expand Down
14 changes: 10 additions & 4 deletions sui/libsui/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,18 +177,24 @@ class __Render {
}

function $Backend(route?: string) {
route = route || window.location.pathname;
return new __Backend(route);
const page = window.location.pathname;
const root = document.body.getAttribute("s:public") || "/";
route = route || page;
const re = new RegExp("^" + root);
route = root + route.replace(re, "");
return new __Backend(route, page);
}

class __Backend {
route = "";
constructor(route) {
page = "";
constructor(route: string, page: string) {
this.route = route;
this.page = page;
}

async Call(method: string, ...args: any): Promise<any> {
// @ts-ignore
return await __sui_backend_call(this.route, method, ...args);
return await __sui_backend_call(this.route, this.page, method, ...args);
}
}
25 changes: 23 additions & 2 deletions sui/storages/local/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -398,7 +398,7 @@ func (page *Page) Build(globalCtx *core.GlobalBuildContext, option *core.BuildOp
}
page.Root = root

html, warnings, err := page.Page.Compile(ctx, option)
html, config, warnings, err := page.Page.Compile(ctx, option)
if err != nil {
return warnings, fmt.Errorf("Compile the page %s error: %s", page.Route, err.Error())
}
Expand All @@ -421,6 +421,12 @@ func (page *Page) Build(globalCtx *core.GlobalBuildContext, option *core.BuildOp
return warnings, err
}

// Save the config file
err = page.writeConfig([]byte(config), option.Data)
if err != nil {
return warnings, err
}

// Jit Components
if globalCtx == nil {
jitComponents, err := page.tmpl.GlobRoutes(ctx.GetJitComponents(), true)
Expand Down Expand Up @@ -528,7 +534,7 @@ func (page *Page) Trans(globalCtx *core.GlobalBuildContext, option *core.BuildOp
warnings := []string{}
ctx := core.NewBuildContext(globalCtx)

_, messages, err := page.Page.Compile(ctx, option)
_, _, messages, err := page.Page.Compile(ctx, option)
if err != nil {
return warnings, err
}
Expand Down Expand Up @@ -768,6 +774,21 @@ func (page *Page) writeHTML(html []byte, data map[string]interface{}) error {
return nil
}

// writeHTMLTo write the html to file
func (page *Page) writeConfig(config []byte, data map[string]interface{}) error {
configFile := fmt.Sprintf("%s.cfg", page.publicFile(data))
configFileAbs := filepath.Join(application.App.Root(), configFile)
dir := filepath.Dir(configFileAbs)
if exist, _ := os.Stat(dir); exist == nil {
os.MkdirAll(dir, os.ModePerm)
}
err := os.WriteFile(configFileAbs, config, 0644)
if err != nil {
return err
}
return nil
}

// writeHTMLTo write the html to file
func (page *Page) writeJitHTML(html []byte, data map[string]interface{}) error {
htmlFile := fmt.Sprintf("%s.jit", page.publicFile(data))
Expand Down

0 comments on commit 19ff6c7

Please sign in to comment.