45 lines
1.3 KiB
TypeScript
45 lines
1.3 KiB
TypeScript
import { Injectable } from "@angular/core";
|
|
import { Observable } from "rxjs";
|
|
import { DocumentData } from "../symbols/DocumentData";
|
|
import { HttpClient, Request, Response } from "selenium-webdriver/http";
|
|
import { encodeUriSegment } from "@angular/router/src/url_tree";
|
|
|
|
@Injectable({
|
|
providedIn: "root"
|
|
})
|
|
export class DocumentFetchService {
|
|
|
|
constructor(private http: HttpClient) {}
|
|
|
|
public async fetch(unsafeId: string): Promise<DocumentData> {
|
|
const encodedId = this.encodeId(unsafeId);
|
|
const response: Response = await this.http.send(new Request("GET", "/documents/" + encodedId + ".md"));
|
|
if (response.status === 200) {
|
|
return {
|
|
found: true,
|
|
id: encodedId,
|
|
content: await response.body
|
|
};
|
|
}
|
|
return {
|
|
found: false,
|
|
id: encodedId,
|
|
content: await this.fetchErrorContent(404)
|
|
};
|
|
}
|
|
|
|
public async fetchErrorContent(errorCode: number): Promise<string> {
|
|
if (errorCode > 0 && errorCode <= 700) {
|
|
const response: Response = await this.http.send(new Request("GET", "/documents/" + errorCode + ".md"));
|
|
if (response.status === 200) {
|
|
return await response.body;
|
|
}
|
|
}
|
|
return "Error " + errorCode + ".";
|
|
}
|
|
|
|
private encodeId(id: string): string {
|
|
return id.split("/").map(encodeUriSegment).filter((part) => part !== "." && part !== "..").join("/");
|
|
}
|
|
}
|