英文:
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 'hono'
const app: Hono<{ Bindings: ExecutionContext }> = new Hono<{ Bindings: ExecutionContext }>()
app.use('/*', (ctx: HonoContext, next: any) => {
// you can access your env with ctx.env
// you can use ctx.set to set objects in your context
})
app.get('<your-endpoint>', (ctx: HonoContext): Promise<Response> => {
// your airtable is initialized here
// you can get it with ctx.get
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论