|
| 1 | +import { dev } from '$app/environment'; |
1 | 2 | import { env } from '$env/dynamic/private'; |
2 | 3 | import { createClient, type Client } from '@libsql/client'; |
3 | 4 |
|
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; |
5 | 12 |
|
6 | 13 | 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) { |
9 | 20 | throw new Error('TURSO_DB_URL is not defined'); |
10 | 21 | } |
11 | 22 |
|
12 | 23 | const auth_token = TURSO_DB_AUTH_TOKEN?.trim(); |
13 | 24 | 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'); |
17 | 26 | } |
18 | 27 |
|
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, |
23 | 33 | }); |
| 34 | + |
| 35 | + return client_instance; |
24 | 36 | }; |
0 commit comments