This repository has been archived on 2022-10-07. You can view files and clone it, but cannot push or open issues or pull requests.
skynet-webportal/packages/ipfs-api/src/utils.ts

72 lines
2.3 KiB
TypeScript
Raw Normal View History

2021-09-17 14:10:54 +00:00
import { SkynetClient } from "@skynetlabs/skynet-nodejs";
import { createReadStream, createWriteStream } from "fs";
import got from "got";
import { extract } from "tar-fs";
import { IPFS_GATEWAY, IPFS_INFURA_API, SKYNET_PORTAL } from "./consts";
const client = new SkynetClient(SKYNET_PORTAL);
export async function contentType(cid: string): Promise<string> {
const url = `${IPFS_GATEWAY}/${cid}`;
const response = await got.head(url);
return response.headers["content-type"];
}
export async function isDirectory(cid: string): Promise<boolean> {
const url = `${IPFS_INFURA_API}/api/v0/object/get?arg=${cid}&encoding=json`;
const json = await got.get(url).json();
return Boolean(json["Links"].length);
}
2021-10-01 12:35:54 +00:00
export async function download(cid: string, destination: string, directory: boolean): Promise<boolean> {
const url = directory ? `${IPFS_INFURA_API}/api/v0/get?arg=${cid}&archive=true` : `${IPFS_GATEWAY}/${cid}`;
2021-09-17 14:10:54 +00:00
return new Promise((resolve, reject) => {
const downloadStream = got.stream(url);
downloadStream.on("error", (error) => {
2021-09-29 17:57:36 +00:00
console.error(`Download fail ${url}: ${error.message}`);
2021-09-17 14:10:54 +00:00
});
const fileWriterStream = createWriteStream(destination);
fileWriterStream
.on("error", (error) => {
console.error(`Could not write file to system: ${error.message}`);
reject(error);
})
.on("finish", () => {
console.log(`File downloaded to ${destination}`);
resolve(true);
});
downloadStream.pipe(fileWriterStream);
});
}
export async function extractArchive(src: string, dst: string) {
return new Promise((resolve, reject) => {
2021-10-01 12:35:54 +00:00
createReadStream(src).pipe(extract(dst)).on("finish", resolve).on("error", reject);
2021-09-17 14:10:54 +00:00
});
}
export async function sleep(ms: number) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
export async function uploadFile(filePath: string): Promise<string> {
const response = await client.uploadFile(filePath);
if (response.startsWith("sia://")) {
return response.slice("sia://".length);
}
throw new Error("upload failed, skylink not found");
}
export async function uploadDirectory(dirPath: string): Promise<string> {
const response = await client.uploadDirectory(dirPath);
if (response.startsWith("sia://")) {
return response.slice("sia://".length);
}
throw new Error("upload failed, skylink not found");
}