dataService.js
1 import { Codex } from "@codex-storage/sdk-js"; 2 import { NodeUploadStategy } from "@codex-storage/sdk-js/node"; 3 import path from "path"; 4 import fs from "fs"; 5 6 export class DataService { 7 constructor(configService) { 8 this.configService = configService; 9 } 10 11 upload = async (filePath) => { 12 const data = this.getCodexData(); 13 14 // We can use mime util to determine the content type of the file. But Codex will reject some 15 // mimetypes. So we set it to octet-stream always. 16 const contentType = "application/octet-stream"; 17 18 const filename = path.basename(filePath); 19 const fileData = fs.readFileSync(filePath); 20 21 const metadata = { filename: filename, mimetype: contentType }; 22 23 const strategy = new NodeUploadStategy(fileData, metadata); 24 const uploadResponse = data.upload(strategy); 25 const res = await uploadResponse.result; 26 27 if (res.error) { 28 throw new Error(res.data); 29 } 30 return res.data; 31 }; 32 33 download = async (cid) => { 34 const data = this.getCodexData(); 35 const manifest = await data.fetchManifest(cid); 36 const filename = this.getFilename(manifest); 37 38 const response = await data.networkDownloadStream(cid); 39 const fileData = await response.data.text(); 40 41 fs.writeFileSync(filename, fileData); 42 return filename; 43 }; 44 45 debugInfo = async () => { 46 const debug = this.getCodexDebug(); 47 const res = await debug.info(); 48 if (res.error) { 49 throw new Error(res.data); 50 } 51 return res.data; 52 }; 53 54 localData = async () => { 55 const data = this.getCodexData(); 56 const res = await data.cids(); 57 if (res.error) { 58 throw new Error(res.data); 59 } 60 return res.data; 61 }; 62 63 getCodex = () => { 64 const config = this.configService.get(); 65 const url = `http://localhost:${config.ports.apiPort}`; 66 const codex = new Codex(url); 67 return codex; 68 }; 69 70 getCodexData = () => { 71 return this.getCodex().data; 72 }; 73 74 getCodexDebug = () => { 75 return this.getCodex().debug; 76 }; 77 78 getFilename = (manifest) => { 79 const defaultFilename = "unknown_" + Math.random(); 80 const filename = manifest?.data?.manifest?.filename; 81 82 if (filename == undefined || filename.length < 1) return defaultFilename; 83 return filename; 84 }; 85 }