import { Document, DocumentAccessor, DocumentBody, QueryListOption } from "../../model/doc"; import { toQueryString } from "./util"; const baseurl = "/api/doc"; export * from "../../model/doc"; export class FetchFailError extends Error {} export class ClientDocumentAccessor implements DocumentAccessor { search: (search_word: string) => Promise; addList: (content_list: DocumentBody[]) => Promise; async findByPath(basepath: string, filename?: string): Promise { throw new Error("not allowed"); } async findDeleted(content_type: string): Promise { throw new Error("not allowed"); } async findList(option?: QueryListOption | undefined): Promise { let res = await fetch(`${baseurl}/search?${option !== undefined ? toQueryString(option) : ""}`); if (res.status == 401) throw new FetchFailError("Unauthorized"); if (res.status !== 200) throw new FetchFailError("findList Failed"); let ret = await res.json(); return ret; } async findById(id: number, tagload?: boolean | undefined): Promise { let res = await fetch(`${baseurl}/${id}`); if (res.status !== 200) throw new FetchFailError("findById Failed"); let ret = await res.json(); return ret; } /** * not implement */ async findListByBasePath(basepath: string): Promise { throw new Error("not implement"); return []; } async update(c: Partial & { id: number }): Promise { const { id, ...rest } = c; const res = await fetch(`${baseurl}/${id}`, { method: "POST", body: JSON.stringify(rest), headers: { "content-type": "application/json", }, }); const ret = await res.json(); return ret; } async add(c: DocumentBody): Promise { throw new Error("not allow"); const res = await fetch(`${baseurl}`, { method: "POST", body: JSON.stringify(c), headers: { "content-type": "application/json", }, }); const ret = await res.json(); return ret; } async del(id: number): Promise { const res = await fetch(`${baseurl}/${id}`, { method: "DELETE", }); const ret = await res.json(); return ret; } async addTag(c: Document, tag_name: string): Promise { const { id, ...rest } = c; const res = await fetch(`${baseurl}/${id}/tags/${tag_name}`, { method: "POST", body: JSON.stringify(rest), headers: { "content-type": "application/json", }, }); const ret = await res.json(); return ret; } async delTag(c: Document, tag_name: string): Promise { const { id, ...rest } = c; const res = await fetch(`${baseurl}/${id}/tags/${tag_name}`, { method: "DELETE", body: JSON.stringify(rest), headers: { "content-type": "application/json", }, }); const ret = await res.json(); return ret; } } export const CDocumentAccessor = new ClientDocumentAccessor(); export const makeThumbnailUrl = (x: Document) => { return `${baseurl}/${x.id}/${x.content_type}/thumbnail`; }; export default CDocumentAccessor;