33 lines
1.3 KiB
TypeScript
33 lines
1.3 KiB
TypeScript
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
|
|
import type { GatewayAutoService } from '../../features/routing/index.js';
|
|
import { HarborError } from '../../../shared/errors.js';
|
|
import { sendJson } from '../response.js';
|
|
|
|
interface GatewayAutoRouteDependencies {
|
|
appMode: string;
|
|
gatewayAuto: Pick<GatewayAutoService, 'setEnabled'>;
|
|
readBody(req: IncomingMessage): Promise<Record<string, unknown>>;
|
|
withOperation<T>(kind: string, operation: () => Promise<T>): Promise<T>;
|
|
readStatePayload(): Promise<Record<string, unknown> & { gatewayAuto?: unknown }>;
|
|
}
|
|
|
|
export function createGatewayAutoRoute(dependencies: GatewayAutoRouteDependencies) {
|
|
return {
|
|
async handle(req: IncomingMessage, res: ServerResponse) {
|
|
if (req.method !== 'POST' || req.url !== '/api/gateway-auto') return false;
|
|
if (dependencies.appMode !== 'client') throw new HarborError('REQUEST_INVALID');
|
|
const { enabled } = await dependencies.readBody(req);
|
|
if (typeof enabled !== 'boolean') throw new HarborError('REQUEST_INVALID');
|
|
|
|
await dependencies.withOperation(
|
|
'gateway-auto',
|
|
() => dependencies.gatewayAuto.setEnabled(enabled),
|
|
);
|
|
const state = await dependencies.readStatePayload();
|
|
sendJson(res, 200, { success: true, gatewayAuto: state.gatewayAuto, state });
|
|
return true;
|
|
},
|
|
};
|
|
}
|