aboutsummaryrefslogtreecommitdiff
path: root/packages/db/src/core/utils.ts
blob: cf3e375354cc3c907f82774a842f2557a7ef780a (plain) (blame)
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import { getAstroStudioEnv } from '@astrojs/studio';
import type { AstroConfig, AstroIntegration } from 'astro';
import { loadEnv } from 'vite';
import './types.js';

export type VitePlugin = Required<AstroConfig['vite']>['plugins'][number];

export function getAstroEnv(envMode = ''): Record<`ASTRO_${string}`, string> {
	const env = loadEnv(envMode, process.cwd(), 'ASTRO_');
	return env;
}

export type RemoteDatabaseInfo = {
	type: 'libsql' | 'studio';
	url: string;
};

export function getRemoteDatabaseInfo(): RemoteDatabaseInfo {
	const astroEnv = getAstroEnv();
	const studioEnv = getAstroStudioEnv();

	if (studioEnv.ASTRO_STUDIO_REMOTE_DB_URL)
		return {
			type: 'studio',
			url: studioEnv.ASTRO_STUDIO_REMOTE_DB_URL,
		};

	if (astroEnv.ASTRO_DB_REMOTE_URL)
		return {
			type: 'libsql',
			url: astroEnv.ASTRO_DB_REMOTE_URL,
		};

	return {
		type: 'studio',
		url: 'https://db.services.astro.build',
	};
}

export function getDbDirectoryUrl(root: URL | string) {
	return new URL('db/', root);
}

export function defineDbIntegration(integration: AstroIntegration): AstroIntegration {
	return integration;
}

export type Result<T> = { success: true; data: T } | { success: false; data: unknown };

/**
 * Map an object's values to a new set of values
 * while preserving types.
 */
export function mapObject<T, U = T>(
	item: Record<string, T>,
	callback: (key: string, value: T) => U,
): Record<string, U> {
	return Object.fromEntries(
		Object.entries(item).map(([key, value]) => [key, callback(key, value)]),
	);
}