no log: Auto detect backend port and base_url during development

This commit is contained in:
LASER-Yi 2022-03-17 12:01:22 +08:00
parent 75100d8aca
commit 44c851eb31
No known key found for this signature in database
GPG key ID: BB28903D50A1D408
5 changed files with 83 additions and 76 deletions

View file

@ -5,20 +5,12 @@
# VITE_API_KEY="YOUR_SERVER_API_KEY" # VITE_API_KEY="YOUR_SERVER_API_KEY"
# Address of your backend # Address of your backend
VITE_PROXY_URL=http://127.0.0.1:6767 # VITE_PROXY_URL=http://127.0.0.1:6767
# Bazarr configuration path, must be absolute path # Bazarr configuration path, must be absolute path
# Vite will use this variable to find your bazarr API key # Vite will use this variable to find your bazarr's configuration file
VITE_BAZARR_CONFIG_FILE="../data/config/config.ini" VITE_BAZARR_CONFIG_FILE="../data/config/config.ini"
# Proxy Settings
# Allow Unsecured connection to your backend
VITE_PROXY_SECURE=true
# Allow websocket connection in Socket.IO
VITE_ALLOW_WEBSOCKET=true
# Display update section in settings # Display update section in settings
VITE_CAN_UPDATE=true VITE_CAN_UPDATE=true
@ -27,3 +19,11 @@ VITE_HAS_UPDATE=false
# Display React-Query devtools # Display React-Query devtools
VITE_QUERY_DEV=false VITE_QUERY_DEV=false
# Proxy Settings
# Allow Unsecured connection to your backend
VITE_PROXY_SECURE=true
# Allow websocket connection in Socket.IO
VITE_ALLOW_WEBSOCKET=true

View file

@ -35,8 +35,6 @@
5. (Optional) Change the address of your backend server 5. (Optional) Change the address of your backend server
> http://127.0.0.1:6767 will be used by default
``` ```
# Address of your backend # Address of your backend
VITE_PROXY_URL=http://localhost:6767 VITE_PROXY_URL=http://localhost:6767
@ -66,12 +64,6 @@ Open `http://localhost:3000` to view it in the browser.
The page will reload if you make edits. The page will reload if you make edits.
You will also see any lint errors in the console. You will also see any lint errors in the console.
### `npm test`
Run the Unit Test to validate app state.
Please ensure all tests are passed before uploading the code
### `npm run build` ### `npm run build`
Builds the app in production mode and save to the `build` folder. Builds the app in production mode and save to the `build` folder.

View file

@ -1,50 +0,0 @@
import { readFile } from "fs/promises";
async function parseConfig(path: string) {
const config = await readFile(path, "utf8");
const targetSection = config
.split("\n\n")
.filter((section) => section.includes("[auth]"));
if (targetSection.length === 0) {
throw new Error("Cannot find [auth] section in config");
}
const section = targetSection[0];
for (const line of section.split("\n")) {
const matched = line.startsWith("apikey");
if (matched) {
const results = line.split("=");
if (results.length === 2) {
const key = results[1].trim();
return key;
}
}
}
throw new Error("Cannot find apikey in config");
}
export async function findApiKey(
env: Record<string, string>
): Promise<string | undefined> {
if (env["VITE_API_KEY"] !== undefined) {
return undefined;
}
if (env["VITE_BAZARR_CONFIG_FILE"] !== undefined) {
const path = env["VITE_BAZARR_CONFIG_FILE"];
try {
const apiKey = await parseConfig(path);
return apiKey;
} catch (err) {
console.warn(err.message);
}
}
return undefined;
}

View file

@ -0,0 +1,65 @@
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");
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://localhost:${port}${baseUrl}`;
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})`
);
}
}
}

View file

@ -2,20 +2,20 @@ import react from "@vitejs/plugin-react";
import path from "path"; import path from "path";
import { defineConfig, loadEnv } from "vite"; import { defineConfig, loadEnv } from "vite";
import checker from "vite-plugin-checker"; import checker from "vite-plugin-checker";
import { findApiKey } from "./config/api-key";
import chunks from "./config/chunks"; import chunks from "./config/chunks";
import overrideEnv from "./config/configReader";
export default defineConfig(async ({ mode, command }) => { export default defineConfig(async ({ mode, command }) => {
const env = loadEnv(mode, process.cwd()); const env = loadEnv(mode, process.cwd());
const target = env.VITE_PROXY_URL;
const allowWs = env.VITE_ALLOW_WEBSOCKET === "true";
const secure = env.VITE_PROXY_SECURE === "true";
if (command === "serve" && env["VITE_API_KEY"] === undefined) { if (command === "serve") {
const apiKey = await findApiKey(env); await overrideEnv(env);
process.env["VITE_API_KEY"] = apiKey ?? "UNKNOWN_API_KEY";
} }
const target = env.VITE_PROXY_URL;
const ws = env.VITE_ALLOW_WEBSOCKET === "true";
const secure = env.VITE_PROXY_SECURE === "true";
return { return {
plugins: [ plugins: [
react(), react(),
@ -50,7 +50,7 @@ export default defineConfig(async ({ mode, command }) => {
target, target,
changeOrigin: true, changeOrigin: true,
secure, secure,
ws: allowWs, ws,
}, },
}, },
}, },