|
| 1 | +/* eslint-disable no-console */ |
| 2 | +'use strict' |
| 3 | + |
| 4 | +const ipfsClient = require('ipfs-client') |
| 5 | +let ipfs |
| 6 | + |
| 7 | +const COLORS = { |
| 8 | + active: 'blue', |
| 9 | + success: 'green', |
| 10 | + error: 'red' |
| 11 | +} |
| 12 | + |
| 13 | +const showStatus = (text, bg) => { |
| 14 | + console.info(text) |
| 15 | + |
| 16 | + const log = document.getElementById('output') |
| 17 | + |
| 18 | + if (!log) { |
| 19 | + return |
| 20 | + } |
| 21 | + |
| 22 | + const line = document.createElement('p') |
| 23 | + line.innerText = text |
| 24 | + line.style.color = bg |
| 25 | + |
| 26 | + log.appendChild(line) |
| 27 | +} |
| 28 | + |
| 29 | +async function * streamFiles () { |
| 30 | + for (let i = 0; i < 100; i++) { |
| 31 | + await new Promise((resolve) => { |
| 32 | + setTimeout(() => resolve(), 100) |
| 33 | + }) |
| 34 | + |
| 35 | + showStatus(`Sending /file-${i}.txt`, COLORS.active) |
| 36 | + |
| 37 | + yield { |
| 38 | + path: `/file-${i}.txt`, |
| 39 | + content: `file ${i}` |
| 40 | + } |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +async function main (grpcApi, httpApi) { |
| 45 | + showStatus(`Connecting to ${grpcApi} using ${httpApi} as fallback`, COLORS.active) |
| 46 | + |
| 47 | + ipfs = ipfsClient({ |
| 48 | + grpc: grpcApi, |
| 49 | + http: httpApi |
| 50 | + }) |
| 51 | + |
| 52 | + const id = await ipfs.id() |
| 53 | + showStatus(`Daemon active\nID: ${id.id}`, COLORS.success) |
| 54 | + |
| 55 | + for await (const file of ipfs.addAll(streamFiles(), { |
| 56 | + wrapWithDirectory: true, |
| 57 | + // this is just to show the interleaving of uploads and progress events |
| 58 | + // otherwise we'd have to upload 50 files before we see any response from |
| 59 | + // the server. do not specify this so low in production as you'll have |
| 60 | + // greatly degraded import performance |
| 61 | + fileImportConcurrency: 1, |
| 62 | + progress: (bytes, file) => { |
| 63 | + showStatus(`File progress ${file} ${bytes}`, COLORS.active) |
| 64 | + } |
| 65 | + })) { |
| 66 | + showStatus(`Added file: ${file.path} ${file.cid}`, COLORS.success) |
| 67 | + } |
| 68 | + |
| 69 | + showStatus('Finished!', COLORS.success) |
| 70 | +} |
| 71 | + |
| 72 | +// Event listeners |
| 73 | +document.getElementById('connect-submit').onclick = (e) => { |
| 74 | + e.preventDefault() |
| 75 | + |
| 76 | + main(document.getElementById('grpc-input').value, document.getElementById('http-input').value) |
| 77 | + .catch(err => { |
| 78 | + showStatus(err.message, COLORS.error) |
| 79 | + console.error(err) |
| 80 | + }) |
| 81 | +} |
0 commit comments