89 lines
2.6 KiB
TypeScript
Raw Normal View History

2023-04-27 23:18:48 +02:00
import _ from 'lodash';
import { getCommonPath } from './string-formatting';
import type { Config } from './types';
2023-04-27 23:18:48 +02:00
interface ServerConfig {
url: string;
}
2023-04-27 23:18:48 +02:00
export const getConfigUrls = (config: Config, forAdminBuild = false) => {
const serverConfig = config.get<ServerConfig>('server');
2021-10-26 12:07:57 +02:00
const adminConfig = config.get('admin');
// Defines serverUrl value
let serverUrl = _.get(serverConfig, 'url', '');
serverUrl = _.trim(serverUrl, '/ ');
if (typeof serverUrl !== 'string') {
throw new Error('Invalid server url config. Make sure the url is a string.');
}
if (serverUrl.startsWith('http')) {
try {
serverUrl = _.trim(new URL(serverConfig.url).toString(), '/');
} catch (e) {
throw new Error(
'Invalid server url config. Make sure the url defined in server.js is valid.'
);
}
} else if (serverUrl !== '') {
serverUrl = `/${serverUrl}`;
}
// Defines adminUrl value
2021-10-26 12:07:57 +02:00
let adminUrl = _.get(adminConfig, 'url', '/admin');
adminUrl = _.trim(adminUrl, '/ ');
if (typeof adminUrl !== 'string') {
throw new Error('Invalid admin url config. Make sure the url is a non-empty string.');
}
if (adminUrl.startsWith('http')) {
try {
adminUrl = _.trim(new URL(adminUrl).toString(), '/');
} catch (e) {
throw new Error('Invalid admin url config. Make sure the url defined in server.js is valid.');
}
} else {
adminUrl = `${serverUrl}/${adminUrl}`;
}
// Defines adminPath value
let adminPath = adminUrl;
if (
serverUrl.startsWith('http') &&
adminUrl.startsWith('http') &&
new URL(adminUrl).origin === new URL(serverUrl).origin &&
!forAdminBuild
) {
adminPath = adminUrl.replace(getCommonPath(serverUrl, adminUrl), '');
adminPath = `/${_.trim(adminPath, '/')}`;
} else if (adminUrl.startsWith('http')) {
adminPath = new URL(adminUrl).pathname;
}
return {
serverUrl,
adminUrl,
adminPath,
};
};
2022-08-08 23:33:39 +02:00
const getAbsoluteUrl =
2023-04-27 23:18:48 +02:00
(adminOrServer: 'admin' | 'server') =>
(config: Config, forAdminBuild = false) => {
2022-08-08 23:33:39 +02:00
const { serverUrl, adminUrl } = getConfigUrls(config, forAdminBuild);
const url = adminOrServer === 'server' ? serverUrl : adminUrl;
2022-08-08 23:33:39 +02:00
if (url.startsWith('http')) {
return url;
}
2022-08-08 23:33:39 +02:00
const hostname =
config.get('environment') === 'development' &&
['127.0.0.1', '0.0.0.0'].includes(config.get('server.host'))
? 'localhost'
: config.get('server.host');
2022-08-08 23:33:39 +02:00
return `http://${hostname}:${config.get('server.port')}${url}`;
};
2023-04-27 23:18:48 +02:00
export const getAbsoluteAdminUrl = getAbsoluteUrl('admin');
export const getAbsoluteServerUrl = getAbsoluteUrl('server');