在 `fetch` 作用域之外使用 Cloudflare Worker 的环境变量

huangapple go评论46阅读模式
英文:

Use cloudflare worker env outside fetch scope

问题

我正在使用Cloudflare Workers创建一个缓存代理。我正在使用自制的类实例来抽象Airtable查询,这需要一些机密信息才能实例化。

现在,我必须在每次fetch中实例化它,因为这是我知道的访问Cloudflare环境变量的唯一方法。有没有一种方法可以全局访问它们,这样我就可以在fetch范围之外实例化这个类?

import { useAirtable } from 'painless-airtable';
import router from './router';
import type { Env } from './types';

export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext) {

    // 我想把这部分移到fetch之外
    const { AIRTABLE_BASE: base, AIRTABLE_TOKEN: token } = env;
    const airtable = useAirtable({ base, token });

    return router.handle(request, { airtable, env, ctx });
  },
};
英文:

I'm creating a cache-proxy with Cloudflare Workers. I'm using a self made class instance to abstract Airtable queries, that require couple of secrets to be instantiated.

Now I must instantiate it inside fetch every time, as it's the only way I know to access Cloudflare env variables. Is there a way to globally access them so I can instantiate the class outside the fetch scope?

import { useAirtable } from 'painless-airtable';
import router from './router';
import type { Env } from './types';

export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext) {

    // I'd like to extract this out of fetch
    const { AIRTABLE_BASE: base, AIRTABLE_TOKEN: token } = env;
    const airtable = useAirtable({ base, token });

    return router.handle(request, { airtable, env, ctx });
  },
};

答案1

得分: 2

我能想到的最简单方法是使用 https://hono.dev 并在中间件中初始化你的 Airtable,这样你就可以访问执行上下文。

import { Hono } from 'hono'

const app: Hono<{ Bindings: ExecutionContext }> = new Hono<{ Bindings: ExecutionContext }>()

app.use('/*', (ctx: HonoContext, next: any) => {
  // 你可以使用 ctx.env 访问你的环境
  // 你可以使用 ctx.set 在你的上下文中设置对象
})

app.get('<your-endpoint>', (ctx: HonoContext): Promise<Response> => {
  // 在这里初始化了你的 Airtable
  // 你可以使用 ctx.get 获取它
})
英文:

The simplest way I can think of is to use https://hono.dev and have your Airtable initialized in a middleware, there you get access to the execution context.

import { Hono } from &#39;hono&#39;
    
const app: Hono&lt;{ Bindings: ExecutionContext }&gt; = new Hono&lt;{ Bindings: ExecutionContext }&gt;()
    
app.use(&#39;/*&#39;, (ctx: HonoContext, next: any) =&gt; {
  // you can access your env with ctx.env
  // you can use ctx.set to set objects in your context
})
    
    
app.get(&#39;&lt;your-endpoint&gt;&#39;, (ctx: HonoContext): Promise&lt;Response&gt; =&gt; {
  // your airtable is initialized here
  // you can get it with ctx.get
})

huangapple
  • 本文由 发表于 2023年2月24日 17:27:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/75554786.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定