Favor typed unions over class hierarchy

This commit is contained in:
oleksandr-shysh
2025-06-16 12:39:29 +03:00
parent d9e49f3438
commit d87be5fb25
3 changed files with 35 additions and 30 deletions
+33 -28
View File
@@ -11,46 +11,53 @@ import {
UserMeResponseSchema,
} from "../core/ApiSchemas";
interface Platform {
getRedirectUri(): string;
setLocation(url: string): Promise<void> | void;
getApiBaseForLocalhost(): string;
initializeAuthListener(): void;
}
type Platform =
| {
kind: "browser";
getRedirectUri(): string;
setLocation(url: string): void;
getApiBaseForLocalhost(): string;
initializeAuthListener(): void;
}
| {
kind: "capacitor";
getRedirectUri(): string;
setLocation(url: string): Promise<void>;
getApiBaseForLocalhost(): string;
initializeAuthListener(): void;
};
class BrowserPlatform implements Platform {
const browserPlatform: Platform = {
kind: "browser",
getRedirectUri(): string {
return window.location.href.split("#")[0];
}
},
setLocation(url: string): void {
window.location.href = url;
}
},
getApiBaseForLocalhost(): string {
return (
localStorage.getItem("apiHost") ?? (process.env.LOCAL_API_BASE_URL || "")
);
}
},
initializeAuthListener(): void {
// No-op for web
}
}
},
};
class CapacitorPlatform implements Platform {
const capacitorPlatform: Platform = {
kind: "capacitor",
getRedirectUri(): string {
return `${process.env.APP_BASE_URL || ""}/discord-redirect.html`;
}
},
async setLocation(url: string): Promise<void> {
await Browser.open({ url });
}
},
getApiBaseForLocalhost(): string {
return process.env.LOCAL_API_BASE_URL || "";
}
return process.env.APP_BASE_URL
? process.env.APP_BASE_URL!.replace("9000", "8787")
: "http://localhost:8787";
},
initializeAuthListener(): void {
App.addListener("appUrlOpen", async (data) => {
try {
@@ -72,13 +79,11 @@ class CapacitorPlatform implements Platform {
await Browser.close();
}
});
}
}
},
};
const platform: Platform =
Capacitor.getPlatform() !== "web"
? new CapacitorPlatform()
: new BrowserPlatform();
Capacitor.getPlatform() !== "web" ? capacitorPlatform : browserPlatform;
function getAudience() {
const hostname =
+1 -1
View File
@@ -33,7 +33,7 @@ const corsOptions = {
) => {
// allow requests with no origin (like mobile apps or curl requests)
if (!origin) return callback(null, true);
if (allowedOrigins.indexOf(origin) !== -1) {
if (allowedOrigins.some((o) => origin.startsWith(o))) {
callback(null, true);
} else {
callback(new Error("Not allowed by CORS"));
+1 -1
View File
@@ -159,7 +159,7 @@ export default async (env, argv) => {
}),
new webpack.DefinePlugin({
"process.env.WEBSOCKET_URL": JSON.stringify(
appBaseUrl.split("://")[1], // remove protocol
appBaseUrl ? appBaseUrl.split("://")[1] : "", // remove protocol
),
"process.env.GAME_ENV": JSON.stringify(isProduction ? "prod" : "dev"),
"process.env.GIT_COMMIT": JSON.stringify(gitCommit),