kernel-ipfs-client/src/index.ts

90 lines
2.2 KiB
TypeScript
Raw Normal View History

import { Client, factory } from "@lumeweb/libkernel-universal";
import defer from "p-defer";
2023-04-01 17:39:22 +00:00
import { CatOptions, LsOptions, StatOptions } from "@helia/unixfs";
2022-08-05 13:34:50 +00:00
interface AbortableGenerator {
abort: () => void;
2023-04-09 20:19:41 +00:00
iterable: () => AsyncIterable<Uint8Array>;
2022-08-05 13:34:50 +00:00
}
export class IPFSClient extends Client {
public async ready() {
return this.callModuleReturn("ready");
2022-08-05 13:34:50 +00:00
}
2023-04-01 17:39:22 +00:00
public async stat(cid: string, options?: Partial<StatOptions>) {
return this.callModuleReturn("stat", { cid, options });
2022-08-05 13:34:50 +00:00
}
2023-04-01 17:39:22 +00:00
public ls(cid: string, options?: Partial<LsOptions>): AbortableGenerator {
return this.connectModuleGenerator("ls", { cid, options });
2022-08-05 13:34:50 +00:00
}
2023-04-01 17:39:22 +00:00
public cat(cid: string, options?: Partial<CatOptions>): AbortableGenerator {
return this.connectModuleGenerator("cat", { cid, options });
2022-08-05 13:34:50 +00:00
}
public async ipns(cid: string): Promise<string> {
return this.callModuleReturn("ipnsResolve", { cid });
2022-08-05 13:34:50 +00:00
}
public async activePeers(): Promise<number> {
return this.callModuleReturn("getActivePeers");
2022-08-05 13:34:50 +00:00
}
private connectModuleGenerator(
method: string,
data: any
): AbortableGenerator {
2023-04-09 20:19:41 +00:00
let pipe = defer<Uint8Array>();
const [update, result] = this.connectModule(method, data, (item: any) => {
pipe.resolve(item);
});
(async () => {
const ret = await result;
this.handleError(ret);
pipe.resolve(undefined);
})();
return {
abort() {
2023-04-09 20:19:41 +00:00
update("abort");
},
2023-04-09 20:19:41 +00:00
iterable(): AsyncIterable<Uint8Array> {
return {
[Symbol.asyncIterator]() {
return {
async next(): Promise<IteratorResult<Uint8Array>> {
const chunk = await pipe.promise;
if (chunk === undefined) {
2023-04-17 00:55:34 +00:00
return {
value: new Uint8Array(),
done: true,
2023-04-17 00:55:34 +00:00
};
}
2023-04-09 20:19:41 +00:00
update("next");
pipe = defer();
return {
value: chunk,
done: false,
2023-04-09 20:19:41 +00:00
};
},
};
},
};
},
};
2022-08-05 13:34:50 +00:00
}
}
export const createClient = factory<IPFSClient>(
IPFSClient,
2023-04-17 02:45:45 +00:00
"AAA0F0m8xP2YVcP0YZ-1QT8nLqYPZjgANotOQO3nGST1Bg"
);