|
| 1 | +import type { Job } from "./jobs/load"; |
| 2 | + |
| 3 | +export interface ClientOptions { |
| 4 | + url: string; |
| 5 | + apiKey: string; |
| 6 | +} |
| 7 | + |
| 8 | +export class Client { |
| 9 | + url: string; |
| 10 | + apiKey: string; |
| 11 | + |
| 12 | + constructor(options: ClientOptions) { |
| 13 | + this.url = options.url; |
| 14 | + this.apiKey = options.apiKey; |
| 15 | + } |
| 16 | + |
| 17 | + async createJob(job: Job) { |
| 18 | + // TODO: reuse fetch error handling |
| 19 | + const response = await fetch(`${this.url}/api/jobs`, { |
| 20 | + method: "POST", |
| 21 | + headers: { |
| 22 | + "Content-Type": "application/json", |
| 23 | + Authorization: `Bearer ${this.apiKey}`, |
| 24 | + }, |
| 25 | + body: JSON.stringify(job), |
| 26 | + }); |
| 27 | + |
| 28 | + const data = await response.json(); |
| 29 | + return data; |
| 30 | + } |
| 31 | + |
| 32 | + async streamJob(jobId: string) { |
| 33 | + const response = await fetch(`${this.url}/api/jobs/${jobId}/stream`, { |
| 34 | + headers: { |
| 35 | + Authorization: `Bearer ${this.apiKey}`, |
| 36 | + }, |
| 37 | + }); |
| 38 | + |
| 39 | + const reader = response.body!.getReader(); |
| 40 | + const decoder = new TextDecoder(); |
| 41 | + |
| 42 | + async function* streamGenerator() { |
| 43 | + while (true) { |
| 44 | + const { done, value } = await reader.read(); |
| 45 | + if (done) break; |
| 46 | + |
| 47 | + const chunk = decoder.decode(value, { stream: true }); |
| 48 | + const lines = chunk.split("\n").filter((line) => line.trim()); |
| 49 | + |
| 50 | + for (const line of lines) { |
| 51 | + if (line.startsWith("data: ")) { |
| 52 | + const jsonStr = line.slice(6); |
| 53 | + try { |
| 54 | + const data = JSON.parse(jsonStr); |
| 55 | + yield data; |
| 56 | + } catch (e) { |
| 57 | + console.error("Error parsing SSE data:", e); |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + return streamGenerator(); |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +export function createClient(options: ClientOptions): Client { |
| 69 | + return new Client(options); |
| 70 | +} |
0 commit comments