65 lines
1.8 KiB
TypeScript
65 lines
1.8 KiB
TypeScript
import { Injectable } from "@angular/core";
|
|
import { DocumentData } from "../symbols/DocumentData";
|
|
import { HttpClient } from "@angular/common/http";
|
|
import { take } from "rxjs/operators";
|
|
|
|
@Injectable({
|
|
providedIn: "root"
|
|
})
|
|
export class DocumentFetchService {
|
|
private language: string;
|
|
|
|
constructor(private http: HttpClient) {
|
|
this.language = document.body.parentElement.lang;
|
|
}
|
|
|
|
public async fetch(unsafeId: string): Promise<DocumentData> {
|
|
const encodedId = this.encodeId(unsafeId);
|
|
try {
|
|
return await this.fetchWithLanguage(encodedId, this.language);
|
|
} catch (e) {
|
|
try {
|
|
return await this.fetchWithLanguage(encodedId, "en");
|
|
} catch (e) {
|
|
return {
|
|
found: false,
|
|
id: encodedId,
|
|
content: await this.fetchErrorContent(404)
|
|
};
|
|
}
|
|
}
|
|
}
|
|
|
|
private async fetchWithLanguage(unsafeId: string, language: string): Promise<DocumentData> {
|
|
const encodedId = this.encodeId(unsafeId);
|
|
const response: string = await this.http.get("/documents/" + encodedId + "." + language + ".md", { responseType: "text" })
|
|
.pipe(take(1)).toPromise();
|
|
return {
|
|
found: true,
|
|
id: encodedId,
|
|
content: await response
|
|
};
|
|
}
|
|
|
|
public async fetchErrorContent(errorCode: number): Promise<string> {
|
|
if (errorCode > 0 && errorCode <= 700) {
|
|
try {
|
|
const response: string = await this.http.get("/documents/" + errorCode + "." + this.language + ".md", { responseType: "text" })
|
|
.pipe(take(1)).toPromise();
|
|
return response;
|
|
} catch (e) {
|
|
}
|
|
}
|
|
return "Error " + errorCode + ".";
|
|
}
|
|
|
|
private encodeId(id: string): string {
|
|
const encoded = id.split("/").map(encodeURIComponent).filter((part) => part.length > 0 && !/[^a-zA-Z0-9_-àùéèì]/.test(part)).join("/");
|
|
if (encoded.length > 0) {
|
|
return encoded;
|
|
} else {
|
|
return "index";
|
|
}
|
|
}
|
|
}
|