2023-04-11 21:04:19 +09:00
|
|
|
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/
|
2023-05-28 13:04:35 +09:00
|
|
|
func fetch(namespace js.Value, req *http.Request, init *RequestInit) (*http.Response, error) {
|
2023-04-11 21:04:19 +09:00
|
|
|
if namespace.IsUndefined() {
|
|
|
|
return nil, errors.New("fetch function not found")
|
|
|
|
}
|
2024-01-25 08:56:34 +09:00
|
|
|
fetchFunc := namespace.Get("fetch")
|
|
|
|
promise := fetchFunc.Invoke(
|
2023-04-11 21:04:19 +09:00
|
|
|
// 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
|
2023-05-28 13:04:35 +09:00
|
|
|
init.ToJS(),
|
2023-04-11 21:04:19 +09:00
|
|
|
)
|
2024-01-23 12:53:32 +09:00
|
|
|
|
2023-04-11 21:04:19 +09:00
|
|
|
jsRes, err := jsutil.AwaitPromise(promise)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2024-01-23 12:53:32 +09:00
|
|
|
|
2024-08-11 22:07:10 +09:00
|
|
|
return jshttp.ToResponse(jsRes)
|
2023-04-11 21:04:19 +09:00
|
|
|
}
|