Skip to content

Allow clients to use the already used port on a standalone server #21

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

Closed
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion src/client/mockttp-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ export default class MockttpClient extends AbstractMockttp implements Mockttp {
}

async start(port?: number): Promise<void> {
if (this.mockServerConfig) throw new Error('Server is already started');
if (this.mockServerConfig && !this.mockServerOptions.allowMultiClientsOnPort) throw new Error('Server is already started');

const path = port ? `/start?port=${port}` : '/start';
let mockServerConfig = await this.requestFromStandalone<MockServerConfig>(path, {
Expand Down
1 change: 1 addition & 0 deletions src/mockttp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ export interface Mockttp {
}

export interface MockttpOptions {
allowMultiClientsOnPort?: boolean;
cors?: boolean;
debug?: boolean;
https?: CAOptions;
Expand Down
27 changes: 24 additions & 3 deletions src/standalone/mockttp-standalone.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import { MockttpOptions } from '../mockttp';
import { Duplex, PassThrough } from 'stream';

export interface StandaloneServerOptions {
allowMultiClientsOnPort?: boolean;
debug?: boolean;
serverDefaults?: MockttpOptions;
}
Expand Down Expand Up @@ -60,9 +61,14 @@ export class MockttpStandalone {
);

if (port != null && this.routers[port] != null) {
res.status(409).json({
error: `Cannot start: mock server is already running on port ${port}`
});
if(options.allowMultiClientsOnPort) {
res.status(200).json(this.getMockServerConfigForPort(port));
} else {
res.status(409).json({
error: `Cannot start: mock server is already running on port ${port}`
});
}

return;
}

Expand Down Expand Up @@ -133,6 +139,21 @@ export class MockttpStandalone {
});
}

private getMockServerConfigForPort(port: number) {
const mockServerOnPort = this.mockServers.find(server => server.port === port);

if(mockServerOnPort) {
return {
mockRoot: mockServerOnPort.url,
port,
}
}

return {
port,
}
}

private routers: { [port: number]: express.Router } = { };
private subscriptionServers: { [port: number]: SubscriptionServer } = { };
private streamServers: { [port: number]: ws.Server } = { };
Expand Down