R: refactor with bind func

This commit is contained in:
aki-0421 2023-04-11 21:04:19 +09:00
parent 7926558e38
commit 9e97a4a812
No known key found for this signature in database
GPG Key ID: 64A8CF6D437D166A
2 changed files with 33 additions and 22 deletions

33
cloudflare/fetch/bind.go Normal file
View File

@ -0,0 +1,33 @@
package fetch
import (
"errors"
"net/http"
"syscall/js"
"github.com/syumai/workers/internal/jshttp"
"github.com/syumai/workers/internal/jsutil"
)
// fetch is a function that reproduces cloudflare fetch.
// Docs: https://developers.cloudflare.com/workers/runtime-apis/fetch/
func fetch(namespace js.Value, req *http.Request /* TO DO: options here */) (*http.Response, error) {
if namespace.IsUndefined() {
return nil, errors.New("fetch function not found")
}
promise := namespace.Call("fetch",
// The Request object to fetch.
// Docs: https://developers.cloudflare.com/workers/runtime-apis/request
jshttp.ToJSRequest(req),
// The content of the request.
// Docs: https://developers.cloudflare.com/workers/runtime-apis/request#requestinit
jsutil.NewObject(),
)
jsRes, err := jsutil.AwaitPromise(promise)
if err != nil {
return nil, err
}
return jshttp.ToResponse(jsRes)
}

View File

@ -1,22 +0,0 @@
package fetch
import (
"net/http"
"github.com/syumai/workers/internal/jshttp"
"github.com/syumai/workers/internal/jsutil"
)
// Do sends an HTTP request and returns an HTTP response
func (c *Client) Do(req *Request) (*http.Response, error) {
jsReq := jshttp.ToJSRequest(req.Request)
init := jsutil.NewObject()
promise := c.namespace.Call("fetch", jsReq, init)
jsRes, err := jsutil.AwaitPromise(promise)
if err != nil {
return nil, err
}
return jshttp.ToResponse(jsRes)
}