Use cloudflare worker env outside fetch scope
Asked Answered
O

1

6

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 });
  },
};

Olympian answered 24/2, 2023 at 9:27 Comment(0)
C
2

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
})
Countersign answered 16/5, 2023 at 3:52 Comment(4)
This will be the same issue you will need to pass ctx to children. Looks weird and not reliable. Should not rely on the library for accessing Env globally.Weikert
can you elaborate what you find weird and unreliable about passing an argument around to other functions?Countersign
To me this breaks the abstraction. Controllers/Routers should not be in charge of configuring the Services they call. When I call TodoRepository.save() from the controller, the controller should not care if it is backed by an AirTable, Supabase, AzureSQL etc..Tights
You could also have a static class to store the airtable instance and use a middleware to intialize it and set it to the class. Then you can import that in any file you want without the need to pass the context around. @Tights if the purpose of your abstraction is to decouple dependencies for easier unit testing, you can always implement your middleware in a separate file and import it in. What do you think is otherwise a viable solution that does respect the abstraction principle you are referring to?Countersign

© 2022 - 2024 — McMap. All rights reserved.