39 lines
1.3 KiB
Go
Raw Normal View History

2023-03-29 18:10:05 +09:00
package cloudflare
import (
"syscall/js"
"github.com/syumai/workers/cloudflare/internal/cfruntimecontext"
"github.com/syumai/workers/internal/jsutil"
)
2023-03-29 21:11:01 +09:00
// WaitUntil extends the lifetime of the "fetch" event.
// It accepts an asynchronous task which the Workers runtime will execute before the handler terminates but without blocking the response.
// see: https://developers.cloudflare.com/workers/runtime-apis/fetch-event/#waituntil
func WaitUntil(task func()) {
exCtx := cfruntimecontext.MustGetExecutionContext()
2023-04-20 07:57:04 +09:00
exCtx.Call("waitUntil", jsutil.NewPromise(js.FuncOf(func(this js.Value, pArgs []js.Value) any {
2023-03-29 21:08:22 +09:00
resolve := pArgs[0]
go func() {
task()
resolve.Invoke(js.Undefined())
}()
return js.Undefined()
2023-03-29 18:10:05 +09:00
})))
}
2023-04-20 07:57:04 +09:00
// PassThroughOnException prevents a runtime error response when the Worker script throws an unhandled exception.
// Instead, the request forwards to the origin server as if it had not gone through the worker.
// see: https://developers.cloudflare.com/workers/runtime-apis/fetch-event/#passthroughonexception
func PassThroughOnException() {
exCtx := cfruntimecontext.MustGetExecutionContext()
2023-04-20 21:29:18 +09:00
jsutil.AwaitPromise(jsutil.NewPromise(js.FuncOf(func(this js.Value, pArgs []js.Value) any {
resolve := pArgs[0]
go func() {
exCtx.Call("passThroughOnException")
resolve.Invoke(js.Undefined())
}()
return js.Undefined()
})))
2023-04-20 07:57:04 +09:00
}