Info
#

2025/06/23 (Mon) 07:50:27 GMT+0000 (UTC)
Type: PC | System: Unknown | Browser: Unknown ... More

Menu
.
+
#
  • @ /note/deno_fresh/post-GetClient
Content
.
+
#

Post: Nekoformi
Date: 2024/04/26

Get Client

本ウェブサイトはとあるブログ記事を参考に開発したのですが、その中で「Deno Deployにアップロードするとデータベースのクライアントの取得に失敗する」というエラーが発生したので、とあるプログラマーの神に解決してもらいました。

client.ts
+
#
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
import 'dotenv/load.ts'; import { Client } from 'postgress'; export const client = new Client({ user: Deno.env.get('DB_USER'), database: Deno.env.get('DB_NAME'), hostname: Deno.env.get('DB_HOST'), port: Deno.env.get('DB_PORT'), password: Deno.env.get('DB_PASSWORD'), }); await client.connect();
someDatabaseFunction.ts
+
#
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
import { client } from '.../client.ts'; export const someDatabaseFunction = async () => { try { await client.queryObject<someDatabaseType>(...); ... } catch (e) { console.error(e); ... } };

このコードではセキュリティーが云々と言われたので

client.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:
import 'dotenv/load.ts'; import { Client } from 'postgress'; async function createClient() { const client = new Client({ user: Deno.env.get('DB_USER'), database: Deno.env.get('DB_NAME'), hostname: Deno.env.get('DB_HOST'), port: Deno.env.get('DB_PORT'), password: Deno.env.get('DB_PASSWORD'), }); await client.connect(); return client; } let client: Client | undefined; export default async function getClient() { if (!client) client = await createClient(); return client; }
someDatabaseFunction.ts
+
#
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
import getClient from '.../client.ts'; export const someDatabaseFunction = async () => { try { const client = await getClient(); await client.queryObject<someDatabaseType>(...); ... } catch (e) { console.error(e); ... } };

こうすることで、全てが解決しました。