kernel-ipfs-client/src/index.ts

86 lines
2.2 KiB
TypeScript
Raw Normal View History

import { Client, factory, NetworkClient } from "@lumeweb/libkernel/module";
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
}
2023-07-14 08:58:45 +00:00
export const MODULE =
2023-07-30 00:44:12 +00:00
"zduPX8bUwHAY1C69w5sqxG9WoTRsdWrdk9Mci3sfajHnB4YHUWBkehd29D";
2023-07-14 08:58:45 +00:00
export class IPFSClient extends NetworkClient {
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
pipe = defer();
update("next");
2023-04-09 20:19:41 +00:00
return {
value: chunk,
done: false,
2023-04-09 20:19:41 +00:00
};
},
};
},
};
},
};
2022-08-05 13:34:50 +00:00
}
}
2023-07-14 08:58:45 +00:00
export const createClient = factory<IPFSClient>(IPFSClient, MODULE);