-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.ts
93 lines (85 loc) · 2.49 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import type { Cache, CacheStorage } from '@cloudflare/workers-types';
import { createBindingProxy } from './proxy';
/**
* Whether the bindings proxy is enabled and currently active.
*
* The proxy is enabled by default in development mode, but can be disabled by setting
* `DISABLE_BINDINGS_PROXY` to `true`.
*
* Alternatively, it can be enabled in other environments by setting `ENABLE_BINDINGS_PROXY` to
* `true`.
* */
export const isProxyEnabled = () =>
process?.env?.ENABLE_BINDINGS_PROXY ||
(!process?.env?.DISABLE_BINDINGS_PROXY && process?.env?.NODE_ENV === 'development');
/**
* Interfaces with a binding from the environment.
*
* @example
* ```ts
* const value = await binding<KVNamespace>('MY_KV').get('key');
* ```
*
* @example
* By default, `process.env` is used in production, however, a custom fallback can be provided.
* ```ts
* const MY_KV = binding<KVNamespace>('MY_KV', { fallback: platform.env });
* ```
*
* @param id Binding ID.
* @param opts Binding options, such as a custom fallback.
* @returns Binding value.
*/
export const binding = <T>(id: string, opts?: BindingOpts): T => {
if (isProxyEnabled()) {
return new Proxy(
{},
{
get: (_, prop) => createBindingProxy<T>(id, { proxyType: 'binding' })[prop as keyof T],
},
) as T;
}
return (opts?.fallback ?? process?.env)?.[id] as T;
};
type DeriveCacheReturnType<T> = T extends 'default' | undefined ? Cache : Promise<Cache>;
/**
* Interfaces with the Cloudflare Cache API.
*
* By default, the `default` cache is used, however, a custom cache can be provided by passing a
* cache name as the first argument.
*
* @example
* ```ts
* const value = await cacheApi().put(..., ...);
* ```
*
* @example
* ```ts
* const value = await cacheApi('custom').put(..., ...);
* ```
*
* @param cacheName Name of the cache to open, or `undefined` to open the default cache.
* @returns Cache instance.
*/
export const cacheApi = <T extends string | undefined = undefined>(
cacheName?: T,
): DeriveCacheReturnType<T> => {
if (isProxyEnabled()) {
return new Proxy(
{},
{
get: (_, prop: keyof Cache) =>
createBindingProxy<Cache>(cacheName ?? 'default', { proxyType: 'caches' })[prop],
},
) as DeriveCacheReturnType<T>;
}
const cachesInstance = caches as unknown as CacheStorage;
return (
cacheName === 'default' || cacheName === undefined
? cachesInstance.default
: cachesInstance.open(cacheName)
) as DeriveCacheReturnType<T>;
};
type BindingOpts = {
fallback: Record<string, unknown>;
};