0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Cloudflare,Hono環境のRepositoryで環境変数を扱う

Posted at

Honoではprocess.envが使えない

Honoでの開発中、SupabaseのAPIキーを.dev.varsに記載して、以下のようにリポジトリで使おうと思ったところ、

xxxRepository.ts
import { createClient } from "@supabase/supabase-js";


const supabaseUrl = process.env.SUPABASE_URL;
const supabaseKey = process.env.SUPABASE_ANON_KEY;

const supabase = createClient(supabaseUrl,supabaseKey);

terminal
[ERROR]service core:Uncaught Error: supabaseUrl is required.

supabaseUrl,keyをログに出力してみると

"supabaseUrl" undefined
"supabaseKey" undefined

はい、取り出せてません。

公式ドキュメントによると、

コードの中で c.env.* から環境変数にアクセスします。
Cloudflare Workers では、環境変数には c からアクセスします。 process.env ではありません。
https://hono-ja.pages.dev/docs/getting-started/cloudflare-workers

ということでした。

ただ... context扱うのはcontroller

ということで、DIによるバケツリレーで解決

xxxController.ts
import { Hono } from "hono";

// 環境変数の型定義
type Bindings = {
  SUPABASE_URL: string;
  SUPABASE_ANON_KEY: string;
};

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

app.get("/", async (c) => {
  try {
    const repository = new xxxRepository(c.env.SUPABASE_URL, c.env.SUPABASE_ANON_KEY);
    const service = new xxxService(repository);

    const xxx = await service.getAll();
    return c.json(xxx, 200);
  } catch (error: unknown) {
    const { message, statusCode } = handleError(error);
    return c.json({ message }, statusCode);
  }
});
xxxService.ts
export class xxxService {
  private repository: xxxRepository;

  constructor(repository: xxxRepository) {
    this.repository = repository;
  }

  async getAll(): Promise<xxx[]> {
    return await this.repository.findAll();
  }
  
}
xxxRepository.ts
export class xxxRepository {
  private supabase;
  constructor(supabaseUrl: string, supabaseKey: string) {
    this.supabase = createClient(supabaseUrl, supabaseKey);
  }

  async findAll(): Promise<xxx[]> {
  
    const { data, error } = await this.supabase.from....

    return data as xxx[];
  }

}

値を渡してインスタンスを作ることで、あくまで依存性の方向は保ったまま、環境変数を扱いました。

ただ、このバケツリレーが正解なのかどうかも分からない笑
また公式ドキュメントと睨めっこしたり、いろんなコードを見ながら最適解を見つけます笑

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?