Skip to content

Commit 23d93ae

Browse files
committed
Improve api config validation and initialization
1 parent 872fb68 commit 23d93ae

1 file changed

Lines changed: 19 additions & 17 deletions

File tree

src/lib/api/index.ts

Lines changed: 19 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -21,36 +21,38 @@ import {
2121
ShockersApi as ShockersV2Api,
2222
} from './internal/v2';
2323

24-
function GetBasePath() {
24+
function GetBasePath(): string {
2525
if (!PUBLIC_BACKEND_API_URL) {
2626
throw new Error('PUBLIC_BACKEND_API_URL is not set in the environment');
2727
}
2828

2929
try {
30-
const parsedUrl = new URL(PUBLIC_BACKEND_API_URL);
31-
// Remove trailing slash unless the path is just "/"
32-
let basePath = parsedUrl.toString();
30+
const url = new URL(PUBLIC_BACKEND_API_URL);
3331

34-
// Remove trailing slash if present
35-
if (basePath.endsWith('/')) {
36-
basePath = basePath.slice(0, -1);
32+
if (url.protocol !== 'https:') {
33+
throw new Error('PUBLIC_BACKEND_API_URL must be a HTTPS url');
3734
}
3835

39-
return basePath;
40-
} catch (error: any) {
36+
if (url.search || url.hash) {
37+
throw new Error('PUBLIC_BACKEND_API_URL must not contain query parameters or hash');
38+
}
39+
40+
// Normalize pathname
41+
let pathname = url.pathname === '/' ? '' : url.pathname.replace(/\/+$/, '');
42+
43+
return `${url.origin}${pathname}`;
44+
} catch (error) {
4145
throw new Error('PUBLIC_BACKEND_API_URL is not a valid URL', { cause: error });
4246
}
4347
}
4448

45-
function GetConfig(): ConfigurationParameters {
46-
return {
47-
basePath: GetBasePath(),
48-
credentials: 'include',
49-
};
50-
}
49+
const API_CONFIG: ConfigurationParameters = {
50+
basePath: GetBasePath(),
51+
credentials: 'include',
52+
};
5153

52-
const DefaultApiV1Configuration = new ConfigurationV1(GetConfig());
53-
const DefaultApiV2Configuration = new ConfigurationV2(GetConfig());
54+
const DefaultApiV1Configuration = new ConfigurationV1(API_CONFIG);
55+
const DefaultApiV2Configuration = new ConfigurationV2(API_CONFIG);
5456

5557
export const accountV1Api = new AccountV1Api(DefaultApiV1Configuration);
5658
export const accountV2Api = new AccountV2Api(DefaultApiV2Configuration);

0 commit comments

Comments
 (0)