ionian/src/client/accessor/document.ts
2023-06-01 14:18:53 +09:00

99 lines
3.5 KiB
TypeScript

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<Document[]>;
addList: (content_list: DocumentBody[]) => Promise<number[]>;
async findByPath(basepath: string, filename?: string): Promise<Document[]> {
throw new Error("not allowed");
}
async findDeleted(content_type: string): Promise<Document[]> {
throw new Error("not allowed");
}
async findList(option?: QueryListOption | undefined): Promise<Document[]> {
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<Document | undefined> {
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<Document[]> {
throw new Error("not implement");
return [];
}
async update(c: Partial<Document> & { id: number }): Promise<boolean> {
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<number> {
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<boolean> {
const res = await fetch(`${baseurl}/${id}`, {
method: "DELETE",
});
const ret = await res.json();
return ret;
}
async addTag(c: Document, tag_name: string): Promise<boolean> {
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<boolean> {
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;