wx-filemanager-data-provider
Version:
122 lines • 4.32 kB
JavaScript
import { Rest } from "@wx/lib-data-provider";
export default class RestDataProvider extends Rest {
constructor(url) {
super(url);
}
getHandlers() {
return {
"create-file": {
handler: (ev) => {
if (ev.file.file) {
const multipartFormData = new FormData();
multipartFormData.append("file", ev.file.file);
multipartFormData.append("name", ev.file.name);
return this.send(`upload?id=${encodeURIComponent(ev.parent)}`, "POST", multipartFormData);
}
else {
return this.send(`files/${encodeURIComponent(ev.parent)}`, "POST", this.getParams({
name: `${ev.file.name}`,
type: ev.file.type,
})).then((res) => {
this.handleNonUniqueNames([res.result.id], [ev.newId]);
return res;
});
}
},
},
"rename-file": {
handler: (ev) => {
return this.send(`files/${encodeURIComponent(ev.id)}`, "PUT", this.getParams({
operation: "rename",
name: ev.name,
})).then((res) => {
this.handleNonUniqueNames([res.result.id], [ev.newId]);
return res;
});
},
},
"move-files": {
handler: async (ev) => {
return this.send("files", "PUT", this.getParams({
operation: "move",
ids: ev.ids,
target: ev.target,
})).then((res) => {
this.handleNonUniqueNames(res.result.map((i) => i.id), ev.newIds);
return res;
});
},
},
"copy-files": {
handler: async (ev) => {
return this.send("files", "PUT", this.getParams({
operation: "copy",
ids: ev.ids,
target: ev.target,
})).then((res) => {
this.handleNonUniqueNames(res.result.map((i) => i.id), ev.newIds);
return res;
});
},
},
"delete-files": {
handler: async (ev) => {
return this.send("files", "DELETE", this.getParams({
ids: ev.ids,
}));
},
},
};
}
async loadFiles(id) {
const data = await this.send(id ? `files/${encodeURIComponent(id)}` : "files", "GET");
return this.parseDates(data);
}
loadInfo(id) {
return this.send(id ? `info/${encodeURIComponent(id)}` : "info", "GET");
}
parseDates(data) {
data.forEach(item => {
if (item.date)
item.date = new Date(item.date);
});
return data;
}
async send(url, method, data, customHeaders) {
const headers = {
...customHeaders,
};
const req = {
method,
headers,
};
if (data) {
req.body = data;
}
return fetch(`${this._url}/${url}`, req).then(res => {
return res
.json()
.then(response => {
if (!res.ok)
throw new Error(`Network error: ${response.error}`);
return response;
})
.catch(error => {
console.error(error);
});
});
}
getParams(obj) {
return typeof obj === "object" ? JSON.stringify(obj) : obj;
}
handleNonUniqueNames(serverIds, localIds) {
localIds.forEach((id, i) => {
if (id !== serverIds[i])
this.exec("file-renamed", {
id,
newId: serverIds[i],
});
});
}
}
//# sourceMappingURL=RestDataProvider.js.map