You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
sandkasten-web/src/app/services/backendService.service.ts

57 lines
1.4 KiB

import { Injectable } from '@angular/core';
import { SSE } from 'sse.js';
import { Observable, Subject } from 'rxjs';
export type ExecutionMessage = {
type: 'stdout' | 'stderr' | 'exit';
text: string;
};
@Injectable({
providedIn: 'root',
})
export class BackendService {
private apiUrl = 'http://localhost:3000';
private resultSubject = new Subject<ExecutionMessage>();
constructor() {}
async createRoom(code: string) {
const reponse = await fetch(`${this.apiUrl}/live`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ code }),
});
return reponse.text();
}
executeCode(code: string, language: string) {
const sse = new SSE(`${this.apiUrl}/run`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'text/event-stream',
},
payload: JSON.stringify({ code, language }),
});
sse.addEventListener('message', (event: MessageEvent<string>) => {
const result = event.data;
// @ts-expect-error The type is not declared although present
const type = event.id;
const text = decodeURIComponent(result.replace(/%00/g, ''));
if (type === 'end') {
sse.close();
}
this.resultSubject.next({ type, text });
});
}
getResult(): Observable<ExecutionMessage> {
return this.resultSubject.asObservable();
}
}