61 lines
1.7 KiB
JavaScript
Raw Normal View History

2025-05-26 11:22:29 +02:00
import { Codex } from "@codex-storage/sdk-js";
import { NodeUploadStategy } from "@codex-storage/sdk-js/node";
import path from "path";
import fs from "fs";
export class DataService {
constructor(configService) {
this.configService = configService;
}
upload = async (filePath) => {
const data = this.getCodexData();
2025-05-26 11:39:57 +02:00
// We can use mime util to determine the content type of the file. But Codex will reject some
// mimetypes. So we set it to octet-stream always.
const contentType = "application/octet-stream";
2025-05-26 11:22:29 +02:00
const filename = path.basename(filePath);
const fileData = fs.readFileSync(filePath);
2025-05-26 11:39:57 +02:00
const metadata = { filename: filename, mimetype: contentType };
2025-05-26 12:51:16 +02:00
const strategy = new NodeUploadStategy(fileData, metadata);
2025-05-26 11:22:29 +02:00
const uploadResponse = data.upload(strategy);
const res = await uploadResponse.result;
if (res.error) {
2025-05-26 11:39:57 +02:00
throw new Error(res.data);
2025-05-26 11:22:29 +02:00
}
return res.data;
};
download = async (cid) => {
2025-05-26 12:51:16 +02:00
throw new Error("Waiting for fix of codex-js sdk");
2025-05-26 11:22:29 +02:00
const data = this.getCodexData();
const manifest = await data.fetchManifest(cid);
const filename = this.getFilename(manifest);
const response = await data.networkDownloadStream(cid);
const fileData = response.data;
fs.writeFileSync(filename, fileData);
};
getCodexData = () => {
const config = this.configService.get();
const url = `http://localhost:${config.ports.apiPort}`;
const codex = new Codex(url);
return codex.data;
};
getFilename = (manifest) => {
const defaultFilename = "unknown_" + Math.random();
const filename = manifest?.data?.manifest?.filename;
if (filename == undefined || filename.length < 1) return defaultFilename;
return filename;
};
}