Skip to content

Commit

Permalink
refactoring downloadFile to appropriately handle write streams
Browse files Browse the repository at this point in the history
  • Loading branch information
pellicceama committed Aug 19, 2022
1 parent 2be89f5 commit da16a31
Showing 1 changed file with 30 additions and 32 deletions.
62 changes: 30 additions & 32 deletions src/utils/images.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,36 +9,34 @@ function getP2PUrl(hash) {
}

export async function downloadFile (fileUrl: string, fileDestination: string, fileName: string): Promise<void> {

return new Promise(async (resolve, reject) => {
if(!fileUrl || !fileDestination || !fileName) {
reject(new Error(`Cannot download empty file Url, dest or name. Dest: ${fileDestination} ${fileName}`));
}
const localFilePath = path.resolve(fileDestination, fileName);

const isP2P = fileUrl.includes('ipfs://') || fileUrl.includes('ipns://');

// TODO: resolve ENS entries alongside IPFS
const url = isP2P ? getP2PUrl(fileUrl.split('//')[1]): fileUrl;

try {
const response = await axios({
method: 'GET',
url: url,
responseType: 'stream',
});

const w = response.data.pipe(fs.createWriteStream(localFilePath));
w.on('finish', () => {
resolve();
});

w.on('error', (err) => {
reject(err);
});

} catch (err) {
reject(`${fileUrl} fetch error: ${err?.response?.status}`);
}
});
if(!fileUrl || !fileDestination || !fileName) {
throw new Error(`Cannot download empty file Url, dest or name. Dest: ${fileDestination} ${fileName}`);
}

const localFilePath = path.resolve(fileDestination, fileName);
const writer = fs.createWriteStream(localFilePath);

const isP2P = fileUrl.includes('ipfs://') || fileUrl.includes('ipns://');

// TODO: resolve ENS entries alongside IPFS
const url = isP2P ? getP2PUrl(fileUrl.split('//')[1]): fileUrl;

return axios({
method: 'GET',
url: url,
responseType: 'stream',
}).then(response => {
return new Promise(async (resolve, reject) => {

response.data.pipe(writer);

writer.on('finish', () => {
resolve();
});

writer.on('error', (err) => {
reject(err);
});
})
})
};

0 comments on commit da16a31

Please sign in to comment.