-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
spaces_url_parser.ts
47 lines (39 loc) · 1.43 KB
/
spaces_url_parser.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import { DEFAULT_SPACE_ID } from '../../common/constants';
export function getSpaceIdFromPath(
requestBasePath: string = '/',
serverBasePath: string = '/'
): string {
let pathToCheck: string = requestBasePath;
if (serverBasePath && serverBasePath !== '/' && requestBasePath.startsWith(serverBasePath)) {
pathToCheck = requestBasePath.substr(serverBasePath.length);
}
// Look for `/s/space-url-context` in the base path
const matchResult = pathToCheck.match(/^\/s\/([a-z0-9_\-]+)/);
if (!matchResult || matchResult.length === 0) {
return DEFAULT_SPACE_ID;
}
// Ignoring first result, we only want the capture group result at index 1
const [, spaceId] = matchResult;
if (!spaceId) {
throw new Error(`Unable to determine Space ID from request path: ${requestBasePath}`);
}
return spaceId;
}
export function addSpaceIdToPath(
basePath: string = '/',
spaceId: string = '',
requestedPath: string = ''
): string {
if (requestedPath && !requestedPath.startsWith('/')) {
throw new Error(`path must start with a /`);
}
if (spaceId && spaceId !== DEFAULT_SPACE_ID) {
return `${basePath}/s/${spaceId}${requestedPath}`;
}
return `${basePath}${requestedPath}`;
}