arcstrum-sdk
Version:
Arcstrum SDK for authentication and database management
67 lines (66 loc) • 2.41 kB
JavaScript
// src/sdk/media.ts
const API_BASE = "https://api.arcstrum.com";
export class ArcstrumMediaClient {
constructor({ userId, token, apiBase }) {
this.userId = userId;
this.token = token;
this.apiBase = apiBase || API_BASE;
}
headers(isJson = true) {
const headers = {};
if (isJson)
headers["Content-Type"] = "application/json";
if (this.token)
headers["Authorization"] = `Bearer ${this.token}`;
return headers;
}
async post(path, body, isJson = true) {
const res = await fetch(`${this.apiBase}${path}`, {
method: "POST",
headers: this.headers(isJson),
body: isJson ? JSON.stringify({ user_id: this.userId, ...body }) : body,
});
if (!res.ok)
throw new Error(await res.text());
return res.json();
}
async get(path, params) {
let url = `${this.apiBase}${path}`;
const search = new URLSearchParams({ user_id: this.userId, ...params }).toString();
url += `?${search}`;
const res = await fetch(url, { headers: this.headers() });
if (!res.ok)
throw new Error(await res.text());
return res.json();
}
// Upload a media file, returns filename string (only filename, not file content)
async uploadFile(file) {
const formData = new FormData();
formData.append("file", file);
// We do not set content-type header to let browser set multipart boundary
const res = await fetch(`${this.apiBase}/upload`, {
method: "POST",
headers: this.token ? { Authorization: `Bearer ${this.token}` } : undefined,
body: formData,
});
if (!res.ok)
throw new Error(await res.text());
const data = await res.json();
if (!data.filename)
throw new Error("Media upload did not return filename");
return data.filename;
}
// List all media filenames (or metadata if supported)
async listFiles() {
const data = await this.get("/list");
return data.files;
}
// Get URL to access a media file
getFileUrl(filename) {
return `${this.apiBase}/files/${encodeURIComponent(filename)}`;
}
// Delete a media file by filename
async deleteFile(filename) {
await this.post("/delete", { filename });
}
}