浏览代码

feat: add gateway

Thomas Zhang 2 月之前
父节点
当前提交
63c0f120f0
共有 2 个文件被更改,包括 44 次插入0 次删除
  1. 29 0
      src/lib/server/gateway.ts
  2. 15 0
      src/lib/server/server.ts

+ 29 - 0
src/lib/server/gateway.ts

@@ -0,0 +1,29 @@
+interface GatewayConfig {
+	endpoint: string;
+	apiKey: string;
+}
+
+class Gateway {
+	#cfg: GatewayConfig;
+
+	constructor(cfg: GatewayConfig) {
+		this.#cfg = cfg;
+	}
+
+	get endpoint(): string {
+		return this.#cfg.endpoint;
+	}
+
+	async fetch(path: string, options?: RequestInit): Promise<Response> {
+		const url = new URL(path, this.#cfg.endpoint);
+		const headers = new Headers(options?.headers);
+		headers.set('Authorization', `Bearer ${this.#cfg.apiKey}`);
+		const response = await fetch(url.toString(), {
+			...options,
+			headers,
+		});
+		return response;
+	}
+}
+
+export { Gateway };

+ 15 - 0
src/lib/server/server.ts

@@ -9,6 +9,7 @@ import { env } from '$env/dynamic/private';
 
 import { Auth } from './auth';
 import { Catalog } from './catalog';
+import { Gateway } from './gateway';
 import { Resources } from './resources';
 import { WorkspaceManager } from './workspace';
 
@@ -21,6 +22,7 @@ class Server {
 	#auth: Auth | undefined;
 	#catalog!: Catalog;
 	#resources!: Resources;
+	#gateway!: Gateway;
 
 	async init(): Promise<void> {
 		if (this.#initialized) return;
@@ -30,6 +32,7 @@ class Server {
 		await Promise.all([this.#createWorkspaceManager(), this.#createAuth()]);
 		const workspaces = this.#ws.list();
 		await Promise.all([this.#createCatalog(workspaces), this.#createResources(workspaces)]);
+		await Promise.all([this.#createGateway()]);
 
 		log.info('Server ready');
 	}
@@ -68,6 +71,14 @@ class Server {
 		this.#resources = resources;
 	}
 
+	async #createGateway(): Promise<void> {
+		const gateway = new Gateway({
+			endpoint: env.GATEWAY_ENDPOINT || 'http://gateway-default:4000',
+			apiKey: env.GATEWAY_KEY,
+		});
+		this.#gateway = gateway;
+	}
+
 	get ws(): WorkspaceManager {
 		return this.#ws;
 	}
@@ -84,6 +95,10 @@ class Server {
 		return this.#resources;
 	}
 
+	get gateway(): Gateway {
+		return this.#gateway;
+	}
+
 	async #saveFile(fileName: string, file: File): Promise<string> {
 		await fs.mkdir(path.dirname(fileName), { recursive: true });
 		let usedFileName = fileName;