Skip to content

Commit 9668551

Browse files
committed
fix: refactor database client initialization and improve error handling
1 parent 94865c1 commit 9668551

File tree

2 files changed

+25
-11
lines changed

2 files changed

+25
-11
lines changed

.gitignore

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,4 +22,6 @@ Thumbs.db
2222
# Vite
2323
vite.config.js.timestamp-*
2424
vite.config.ts.timestamp-*
25-
replica.db*
25+
# Database files
26+
local-dev-replica.db*
27+
local-dev-replica.db-*

src/lib/server/client.ts

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,36 @@
1+
import { dev } from '$app/environment';
12
import { env } from '$env/dynamic/private';
23
import { createClient, type Client } from '@libsql/client';
34

4-
const { TURSO_DB_URL, TURSO_DB_AUTH_TOKEN, TURSO_SYNC_URL } = env;
5+
const { TURSO_DB_URL, TURSO_DB_AUTH_TOKEN } = env;
6+
7+
const LOCAL_DB_PATH = dev
8+
? './local-dev-replica.db'
9+
: '/app/data/turso-replica.db';
10+
11+
let client_instance: Client | null = null;
512

613
export const turso_client = (): Client => {
7-
const url = TURSO_DB_URL?.trim();
8-
if (url === undefined) {
14+
if (client_instance) {
15+
return client_instance;
16+
}
17+
18+
const remote_url = TURSO_DB_URL?.trim();
19+
if (remote_url === undefined) {
920
throw new Error('TURSO_DB_URL is not defined');
1021
}
1122

1223
const auth_token = TURSO_DB_AUTH_TOKEN?.trim();
1324
if (auth_token === undefined) {
14-
if (!url.includes('file:')) {
15-
throw new Error('TURSO_DB_AUTH_TOKEN is not defined');
16-
}
25+
throw new Error('TURSO_DB_AUTH_TOKEN is not defined');
1726
}
1827

19-
return createClient({
20-
url: TURSO_DB_URL as string,
21-
syncUrl: TURSO_SYNC_URL as string,
22-
authToken: TURSO_DB_AUTH_TOKEN as string,
28+
client_instance = createClient({
29+
url: `file:${LOCAL_DB_PATH}`,
30+
syncUrl: remote_url,
31+
authToken: auth_token,
32+
syncInterval: dev ? 60 : 300,
2333
});
34+
35+
return client_instance;
2436
};

0 commit comments

Comments
 (0)