kernel-ipfs-client/src/index.ts

73 lines
1.8 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;
iterable: AsyncGenerator<object>;
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", { 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");
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 {
const pipe = defer();
let done = false;
const [update, result] = this.connectModule(method, data, (item: any) => {
pipe.resolve(item);
});
(async () => {
const ret = await result;
done = true;
this.handleError(ret);
})();
return {
abort() {
update();
},
// @ts-ignore
iterable: async function* (): AsyncGenerator<object> {
// @ts-ignore
const iterator = (await pipe.promise)[Symbol.asyncIterator]();
for await (const value of iterator) {
yield value as object;
}
},
};
2022-08-05 13:34:50 +00:00
}
}
export const createClient = factory<IPFSClient>(
IPFSClient,
2023-04-04 15:35:19 +00:00
"AAChdANbL0wYGNUJsH7zfa6tCSnhGQItgCeGf-KJlw2Pew"
);