Refactor code structure for improved readability and maintainability
This commit is contained in:
@@ -27,3 +27,63 @@ export const DB_CONFIG = {
|
||||
|
||||
export const JWT_SECRET = process.env.JWT_SECRET || "change-me-in-production";
|
||||
export const JWT_EXPIRES_IN = process.env.JWT_EXPIRES_IN || "7d";
|
||||
|
||||
function normalizeHostKey(value) {
|
||||
if (!value) return null;
|
||||
try {
|
||||
const url = new URL(value);
|
||||
return url.host.toLowerCase();
|
||||
} catch {
|
||||
return value.replace(/^[a-z]+:\/\//i, "").replace(/\/.*$/, "").trim().toLowerCase() || null;
|
||||
}
|
||||
}
|
||||
|
||||
function parseGiteaTokenMap(rawValue) {
|
||||
if (!rawValue) return {};
|
||||
const map = {};
|
||||
try {
|
||||
const parsed = typeof rawValue === "string" ? JSON.parse(rawValue) : rawValue;
|
||||
if (parsed && typeof parsed === "object") {
|
||||
for (const [key, token] of Object.entries(parsed)) {
|
||||
const host = normalizeHostKey(key);
|
||||
if (host && typeof token === "string" && token.trim()) {
|
||||
map[host] = token.trim();
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
} catch {
|
||||
// Fall through to comma-separated parsing.
|
||||
}
|
||||
|
||||
const segments = String(rawValue)
|
||||
.split(",")
|
||||
.map((segment) => segment.trim())
|
||||
.filter(Boolean);
|
||||
for (const segment of segments) {
|
||||
const [key, token] = segment.split("=").map((part) => part.trim());
|
||||
const host = normalizeHostKey(key);
|
||||
if (host && token) {
|
||||
map[host] = token;
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
const DEFAULT_GITEA_TOKEN = process.env.GITEA_TOKEN?.trim() || null;
|
||||
const GITEA_TOKENS = parseGiteaTokenMap(process.env.GITEA_TOKENS);
|
||||
|
||||
function getEnvTokenForHost(host) {
|
||||
if (!host) return null;
|
||||
const envKey = `GITEA_TOKEN_${host.replace(/[^A-Z0-9]/gi, "_").toUpperCase()}`;
|
||||
return process.env[envKey]?.trim() || null;
|
||||
}
|
||||
|
||||
export function getGiteaToken(baseUrl) {
|
||||
const host = normalizeHostKey(baseUrl);
|
||||
return (
|
||||
(host && (GITEA_TOKENS[host] || getEnvTokenForHost(host))) ||
|
||||
DEFAULT_GITEA_TOKEN ||
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user