summaryrefslogtreecommitdiffhomepage
path: root/frontend/config/configReader.ts
blob: d0a90daa09e9c7c0ff808d5c8cf2cdb4b74540a3 (plain)
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
62
63
64
65
66
67
68
69
70
71
72
/* eslint-disable no-console */
/// <reference types="node" />

import { readFile } from "fs/promises";

async function read(path: string, sectionName: string, fieldName: string) {
  const config = await readFile(path, "utf8");

  const targetSection = config
    .split("\n\n")
    .filter((section) => section.includes(`[${sectionName}]`));

  if (targetSection.length === 0) {
    throw new Error(`Cannot find [${sectionName}] section in config`);
  }

  const section = targetSection[0];

  for (const line of section.split("\n")) {
    const matched = line.startsWith(fieldName);
    if (matched) {
      const results = line.split("=");
      if (results.length === 2) {
        const key = results[1].trim();
        return key;
      }
    }
  }

  throw new Error(`Cannot find ${fieldName} in config`);
}

export default async function overrideEnv(env: Record<string, string>) {
  const configPath = env["VITE_BAZARR_CONFIG_FILE"];

  if (configPath === undefined) {
    return;
  }

  if (env["VITE_API_KEY"] === undefined) {
    try {
      const apiKey = await read(configPath, "auth", "apikey");

      console.log(`Using API key: ${apiKey}`);

      env["VITE_API_KEY"] = apiKey;
      process.env["VITE_API_KEY"] = apiKey;
    } catch (err) {
      throw new Error(
        `No API key found, please run the backend first, (error: ${err.message})`
      );
    }
  }

  if (env["VITE_PROXY_URL"] === undefined) {
    try {
      const port = await read(configPath, "general", "port");
      const baseUrl = await read(configPath, "general", "base_url");

      const url = `http://127.0.0.1:${port}${baseUrl}`;

      console.log(`Using backend url: ${url}`);

      env["VITE_PROXY_URL"] = url;
      process.env["VITE_PROXY_URL"] = url;
    } catch (err) {
      throw new Error(
        `No proxy url found, please run the backend first, (error: ${err.message})`
      );
    }
  }
}