mirror of
https://github.com/shishantbiswas/bknd.git
synced 2026-03-16 04:27:21 +00:00
updated media api and added tests, fixed body limit
This commit is contained in:
@@ -14,8 +14,28 @@ export class MediaApi extends ModuleApi<MediaApiOptions> {
|
||||
return this.get(["files"]);
|
||||
}
|
||||
|
||||
getFile(filename: string) {
|
||||
return this.get(["file", filename]);
|
||||
getFileResponse(filename: string) {
|
||||
return this.get(["file", filename], undefined, {
|
||||
headers: {
|
||||
Accept: "*/*"
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async getFile(filename: string): Promise<Blob> {
|
||||
const { res } = await this.getFileResponse(filename);
|
||||
if (!res.ok || !res.body) {
|
||||
throw new Error("Failed to fetch file");
|
||||
}
|
||||
return await res.blob();
|
||||
}
|
||||
|
||||
async getFileStream(filename: string): Promise<ReadableStream<Uint8Array>> {
|
||||
const { res } = await this.getFileResponse(filename);
|
||||
if (!res.ok || !res.body) {
|
||||
throw new Error("Failed to fetch file");
|
||||
}
|
||||
return res.body;
|
||||
}
|
||||
|
||||
getFileUploadUrl(file: FileWithPath): string {
|
||||
@@ -32,10 +52,46 @@ export class MediaApi extends ModuleApi<MediaApiOptions> {
|
||||
});
|
||||
}
|
||||
|
||||
uploadFile(file: File) {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
return this.post(["upload"], formData);
|
||||
uploadFile(body: File | ReadableStream, filename?: string) {
|
||||
let type: string = "application/octet-stream";
|
||||
let name: string = filename || "";
|
||||
try {
|
||||
type = (body as File).type;
|
||||
if (!filename) {
|
||||
name = (body as File).name;
|
||||
}
|
||||
} catch (e) {}
|
||||
|
||||
if (name && name.length > 0 && name.includes("/")) {
|
||||
name = name.split("/").pop() || "";
|
||||
}
|
||||
|
||||
if (!name || name.length === 0) {
|
||||
throw new Error("Invalid filename");
|
||||
}
|
||||
|
||||
return this.post(["upload", name], body, {
|
||||
headers: {
|
||||
"Content-Type": type
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async upload(item: Request | Response | string | File | ReadableStream, filename?: string) {
|
||||
if (item instanceof Request || typeof item === "string") {
|
||||
const res = await this.fetcher(item);
|
||||
if (!res.ok || !res.body) {
|
||||
throw new Error("Failed to fetch file");
|
||||
}
|
||||
return this.uploadFile(res.body, filename);
|
||||
} else if (item instanceof Response) {
|
||||
if (!item.body) {
|
||||
throw new Error("Invalid response");
|
||||
}
|
||||
return this.uploadFile(item.body, filename);
|
||||
}
|
||||
|
||||
return this.uploadFile(item, filename);
|
||||
}
|
||||
|
||||
deleteFile(filename: string) {
|
||||
|
||||
Reference in New Issue
Block a user