@fairdatasociety/fairdrive-opfs
Version:
Fairdrive OPFS - integrate data sources from Web 2.0 or Web 3.0
106 lines (105 loc) • 2.9 kB
JavaScript
import { FdpConnectProvider } from '../core/provider';
import { create } from 'ipfs-http-client';
/**
* IpfsMfsProviderDriver is the driver for the IPFS MFS provider.
*/
export class IpfsMfsProviderDriver {
constructor(options) {
this.host = options.host;
this.client = create({ url: options.host });
}
/**
* Verify if a file exists
* @param path - path to the file
* @param mount - mount to check
* @returns Returns true if the file exists, else false
*/
async exists(path, mount) {
const stat = await this.client.files.stat(path);
return stat.cid.byteLength > 0;
}
/**
* Creates a directory
* @param name - directory name
* @param mount - mount to check
* @returns Returns true if the directory created, else false
*/
async createDir(name, mount) {
try {
await this.client.files.mkdir(name);
return true;
}
catch (e) {
return false;
}
}
async delete(filePath, mount) {
try {
await this.client.files.rm(filePath);
return true;
}
catch (e) {
// eslint-disable-next-line no-console
console.error(e);
return false;
}
}
async read(mount) {
const entries = {
dirs: [],
files: [],
mount,
};
for await (const i of this.client.files.ls(`${mount.path}`)) {
if (i.type === 'directory') {
entries.dirs.push(i.name);
}
else {
entries.files.push(i.name);
}
}
return entries;
}
/**
* Download a file
* @param id - id of the file
* @param mount - mount to download the file from
* @param options - options
* @returns
*/
async download(id, mount, options = {}) {
let bs;
for await (const res of this.client.files.read(`${mount.path}${id}`, options)) {
bs = res;
}
return bs;
}
/**
* Upload a file
* @param file - file to upload
* @param mount - mount to upload to
* @param options - options
*/
async upload(file, mount, options = {}) {
const res = this.client.files.write(`${mount.path}${file.name}`, file, { create: true });
return res;
}
}
/**
* IPFSMfsProvider is the provider for IPFS MFS.
*/
export class IPFSMfsProvider extends FdpConnectProvider {
constructor(host = 'http://localhost:5001/api/v0/') {
super({
name: 'IPFSMfsProvider',
});
this.host = host;
}
initialize(options) {
super.initialize(options);
this.filesystemDriver = new IpfsMfsProviderDriver(options);
}
async listMounts() {
return [{ name: 'root', path: '/' }];
}
}