Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Workspace]Add workspace id in basePath #212

Merged
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

32 changes: 32 additions & 0 deletions src/core/public/http/base_path.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,4 +110,36 @@ describe('BasePath', () => {
expect(new BasePath('/foo/bar', '/foo').serverBasePath).toEqual('/foo');
});
});

describe('workspaceBasePath', () => {
it('get path with workspace', () => {
expect(new BasePath('/foo/bar', '/foo/bar', '/workspace').get()).toEqual(
'/foo/bar/workspace'
);
});

it('getBasePath with workspace provided', () => {
expect(new BasePath('/foo/bar', '/foo/bar', '/workspace').getBasePath()).toEqual('/foo/bar');
});

it('prepend with workspace provided', () => {
expect(new BasePath('/foo/bar', '/foo/bar', '/workspace').prepend('/prepend')).toEqual(
'/foo/bar/workspace/prepend'
);
});

it('prepend with workspace provided but calls without workspace', () => {
expect(
new BasePath('/foo/bar', '/foo/bar', '/workspace').prepend('/prepend', {
withoutWorkspace: true,
})
).toEqual('/foo/bar/prepend');
});

it('remove with workspace provided', () => {
expect(
new BasePath('/foo/bar', '/foo/bar', '/workspace').remove('/foo/bar/workspace/remove')
).toEqual('/remove');
});
});
});
28 changes: 19 additions & 9 deletions src/core/public/http/base_path.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,37 +29,47 @@
*/

import { modifyUrl } from '@osd/std';
import type { PrependOptions } from './types';

export class BasePath {
constructor(
private readonly basePath: string = '',
public readonly serverBasePath: string = basePath
public readonly serverBasePath: string = basePath,
private readonly workspaceBasePath: string = ''
) {}

public get = () => {
return `${this.basePath}${this.workspaceBasePath}`;
};

public getBasePath = () => {
return this.basePath;
};

public prepend = (path: string): string => {
if (!this.basePath) return path;
public prepend = (path: string, prependOptions?: PrependOptions): string => {
const { withoutWorkspace } = prependOptions || {};
const basePath = withoutWorkspace ? this.basePath : this.get();
if (!basePath) return path;
return modifyUrl(path, (parts) => {
if (!parts.hostname && parts.pathname && parts.pathname.startsWith('/')) {
parts.pathname = `${this.basePath}${parts.pathname}`;
parts.pathname = `${basePath}${parts.pathname}`;
}
});
};

public remove = (path: string): string => {
if (!this.basePath) {
public remove = (path: string, prependOptions?: PrependOptions): string => {
const { withoutWorkspace } = prependOptions || {};
const basePath = withoutWorkspace ? this.basePath : this.get();
if (!basePath) {
return path;
}

if (path === this.basePath) {
if (path === basePath) {
return '/';
}

if (path.startsWith(`${this.basePath}/`)) {
return path.slice(this.basePath.length);
if (path.startsWith(`${basePath}/`)) {
return path.slice(basePath.length);
}

return path;
Expand Down
10 changes: 5 additions & 5 deletions src/core/public/http/http_service.mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export type HttpSetupMock = jest.Mocked<HttpSetup> & {
anonymousPaths: jest.Mocked<HttpSetup['anonymousPaths']>;
};

const createServiceMock = ({ basePath = '' } = {}): HttpSetupMock => ({
const createServiceMock = ({ basePath = '', workspaceBasePath = '' } = {}): HttpSetupMock => ({
fetch: jest.fn(),
get: jest.fn(),
head: jest.fn(),
Expand All @@ -48,7 +48,7 @@ const createServiceMock = ({ basePath = '' } = {}): HttpSetupMock => ({
patch: jest.fn(),
delete: jest.fn(),
options: jest.fn(),
basePath: new BasePath(basePath),
basePath: new BasePath(basePath, undefined, workspaceBasePath),
anonymousPaths: {
register: jest.fn(),
isAnonymous: jest.fn(),
Expand All @@ -58,14 +58,14 @@ const createServiceMock = ({ basePath = '' } = {}): HttpSetupMock => ({
intercept: jest.fn(),
});

const createMock = ({ basePath = '' } = {}) => {
const createMock = ({ basePath = '', workspaceBasePath = '' } = {}) => {
const mocked: jest.Mocked<PublicMethodsOf<HttpService>> = {
setup: jest.fn(),
start: jest.fn(),
stop: jest.fn(),
};
mocked.setup.mockReturnValue(createServiceMock({ basePath }));
mocked.start.mockReturnValue(createServiceMock({ basePath }));
mocked.setup.mockReturnValue(createServiceMock({ basePath, workspaceBasePath }));
mocked.start.mockReturnValue(createServiceMock({ basePath, workspaceBasePath }));
return mocked;
};

Expand Down
26 changes: 26 additions & 0 deletions src/core/public/http/http_service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,32 @@ describe('#setup()', () => {
// We don't verify that this Observable comes from Fetch#getLoadingCount$() to avoid complex mocking
expect(loadingServiceSetup.addLoadingCountSource).toHaveBeenCalledWith(expect.any(Observable));
});

it('setup basePath without workspaceId provided in window.location.href', () => {
const injectedMetadata = injectedMetadataServiceMock.createSetupContract();
const fatalErrors = fatalErrorsServiceMock.createSetupContract();
const httpService = new HttpService();
const setupResult = httpService.setup({ fatalErrors, injectedMetadata });
expect(setupResult.basePath.get()).toEqual('');
});

it('setup basePath with workspaceId provided in window.location.href', () => {
const windowSpy = jest.spyOn(window, 'window', 'get');
windowSpy.mockImplementation(
() =>
({
location: {
href: 'http://localhost/w/workspaceId/app',
},
} as any)
);
const injectedMetadata = injectedMetadataServiceMock.createSetupContract();
const fatalErrors = fatalErrorsServiceMock.createSetupContract();
const httpService = new HttpService();
const setupResult = httpService.setup({ fatalErrors, injectedMetadata });
expect(setupResult.basePath.get()).toEqual('/w/workspaceId');
windowSpy.mockRestore();
});
});

describe('#stop()', () => {
Expand Down
10 changes: 9 additions & 1 deletion src/core/public/http/http_service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ import { AnonymousPathsService } from './anonymous_paths_service';
import { LoadingCountService } from './loading_count_service';
import { Fetch } from './fetch';
import { CoreService } from '../../types';
import { getWorkspaceIdFromUrl } from '../utils';
import { WORKSPACE_PATH_PREFIX } from '../../utils/constants';

interface HttpDeps {
injectedMetadata: InjectedMetadataSetup;
Expand All @@ -50,9 +52,15 @@ export class HttpService implements CoreService<HttpSetup, HttpStart> {

public setup({ injectedMetadata, fatalErrors }: HttpDeps): HttpSetup {
const opensearchDashboardsVersion = injectedMetadata.getOpenSearchDashboardsVersion();
let workspaceBasePath = '';
const workspaceId = getWorkspaceIdFromUrl(window.location.href);
if (workspaceId) {
workspaceBasePath = `${WORKSPACE_PATH_PREFIX}/${workspaceId}`;
}
const basePath = new BasePath(
injectedMetadata.getBasePath(),
injectedMetadata.getServerBasePath()
injectedMetadata.getServerBasePath(),
workspaceBasePath
);
const fetchService = new Fetch({ basePath, opensearchDashboardsVersion });
const loadingCount = this.loadingCount.setup({ fatalErrors });
Expand Down
25 changes: 20 additions & 5 deletions src/core/public/http/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,25 +87,40 @@ export interface HttpSetup {
*/
export type HttpStart = HttpSetup;

/**
* prepend options
*
* withoutWorkspace option will prepend a relative url with only basePath
* workspaceId will rewrite the /w/{workspaceId} part, if workspace id is an empty string, prepend will remove the workspaceId part
*/
export interface PrependOptions {
withoutWorkspace?: boolean;
}

/**
* APIs for manipulating the basePath on URL segments.
* @public
*/
export interface IBasePath {
/**
* Gets the `basePath` string.
* Gets the `basePath + workspace` string.
*/
get: () => string;

/**
* Prepends `path` with the basePath.
* Gets the `basePath
*/
getBasePath: () => string;

/**
* Prepends `path` with the basePath + workspace.
*/
prepend: (url: string) => string;
prepend: (url: string, prependOptions?: PrependOptions) => string;

/**
* Removes the prepended basePath from the `path`.
* Removes the prepended basePath + workspace from the `path`.
*/
remove: (url: string) => string;
remove: (url: string, prependOptions?: PrependOptions) => string;

/**
* Returns the server's root basePath as configured, without any namespace prefix.
Expand Down
4 changes: 4 additions & 0 deletions src/core/public/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -349,3 +349,7 @@ export {
export { __osdBootstrap__ } from './osd_bootstrap';

export { WorkspacesStart, WorkspacesSetup, WorkspacesService } from './workspace';

export { WORKSPACE_TYPE } from '../utils';

export { getWorkspaceIdFromUrl, formatUrlWithWorkspaceId } from './utils';
2 changes: 2 additions & 0 deletions src/core/public/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,5 @@
export { shareWeakReplay } from './share_weak_replay';
export { Sha256 } from './crypto';
export { MountWrapper, mountReactNode } from './mount';
export { getWorkspaceIdFromUrl, formatUrlWithWorkspaceId } from './workspace';
export { WORKSPACE_PATH_PREFIX, WORKSPACE_TYPE } from '../../utils';
Loading
Loading