58 lines
1.8 KiB
Go
Raw Normal View History

package cfruntimecontext
2023-02-11 10:30:51 +09:00
import (
2023-06-25 18:22:59 +09:00
"errors"
2023-02-11 10:30:51 +09:00
"syscall/js"
2024-01-17 17:21:34 +09:00
"github.com/syumai/workers/internal/jsutil"
2023-02-11 10:30:51 +09:00
)
/**
* The type definition of RuntimeContext for Cloudflare Worker expects:
* ```ts
* type RuntimeContext {
* env: Env;
* ctx: ExecutionContext;
2023-06-25 18:22:59 +09:00
* ...
2023-02-11 10:30:51 +09:00
* }
* ```
* This type is based on the type definition of ExportedHandlerFetchHandler.
* - see: https://github.com/cloudflare/workers-types/blob/c8d9533caa4415c2156d2cf1daca75289d01ae70/index.d.ts#LL564
*/
// MustGetRuntimeContextEnv gets object which holds environment variables bound to Cloudflare worker.
2023-02-11 10:30:51 +09:00
// - see: https://github.com/cloudflare/workers-types/blob/c8d9533caa4415c2156d2cf1daca75289d01ae70/index.d.ts#L566
func MustGetRuntimeContextEnv() js.Value {
return MustGetRuntimeContextValue("env")
2023-02-11 10:30:51 +09:00
}
// MustGetExecutionContext gets ExecutionContext object from context.
2023-02-11 10:30:51 +09:00
// - see: https://github.com/cloudflare/workers-types/blob/c8d9533caa4415c2156d2cf1daca75289d01ae70/index.d.ts#L567
// - see also: https://github.com/cloudflare/workers-types/blob/c8d9533caa4415c2156d2cf1daca75289d01ae70/index.d.ts#L554
func MustGetExecutionContext() js.Value {
return MustGetRuntimeContextValue("ctx")
}
// MustGetRuntimeContextValue gets value for specified key from RuntimeContext.
// - if the value is undefined, this function panics.
func MustGetRuntimeContextValue(key string) js.Value {
val, err := GetRuntimeContextValue(key)
if err != nil {
panic(err)
}
return val
2023-02-11 10:30:51 +09:00
}
2023-06-25 18:22:59 +09:00
var ErrValueNotFound = errors.New("execution context value for specified key not found")
// GetRuntimeContextValue gets value for specified key from RuntimeContext.
// - if the value is undefined, return error.
func GetRuntimeContextValue(key string) (js.Value, error) {
runtimeObj := jsutil.RuntimeContext
2024-01-22 21:29:39 +09:00
v := runtimeObj.Get(key)
2023-06-25 18:22:59 +09:00
if v.IsUndefined() {
return js.Value{}, ErrValueNotFound
}
return v, nil
}