github.com/kaleido-io/firefly@v0.0.0-20210622132723-8b4b6aacb971/kat/src/clients/ipfs.ts (about) 1 // Copyright © 2021 Kaleido, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 import FormData from 'form-data'; 16 import { Stream, Readable } from 'stream'; 17 import { constants } from '../lib/utils'; 18 import { config } from '../lib/config'; 19 import * as utils from '../lib/utils'; 20 21 export const init = async () => { 22 try { 23 const response = await utils.axiosWithRetry({ 24 url: `${config.ipfs.apiEndpoint}/api/v0/version`, 25 method: 'post', 26 auth: { 27 username: config.appCredentials.user, 28 password: config.appCredentials.password 29 } 30 }); 31 if (response.data.Version === undefined) { 32 throw 'Invalid response'; 33 } 34 } catch (err) { 35 throw new Error(`IPFS Connection failed. ${err}`); 36 } 37 }; 38 39 export const downloadJSON = async <T>(hash: string): Promise<T> => { 40 const response = await utils.axiosWithRetry({ 41 url: `${config.ipfs.gatewayEndpoint || config.ipfs.apiEndpoint}/ipfs/${hash}`, 42 method: 'get', 43 responseType: 'json', 44 timeout: constants.IPFS_TIMEOUT_MS, 45 auth: { 46 username: config.appCredentials.user, 47 password: config.appCredentials.password 48 } 49 }); 50 return response.data; 51 }; 52 53 export const uploadString = (value: string): Promise<string> => { 54 const readable = new Readable(); 55 readable.push(value); 56 readable.push(null); 57 return uploadStream(readable); 58 }; 59 60 export const uploadStream = async (stream: Stream): Promise<string> => { 61 const formData = new FormData(); 62 formData.append('document', stream); 63 const response = await utils.axiosWithRetry({ 64 url: `${config.ipfs.apiEndpoint}/api/v0/add`, 65 method: 'post', 66 data: formData, 67 headers: formData.getHeaders(), 68 auth: { 69 username: config.appCredentials.user, 70 password: config.appCredentials.password 71 } 72 }); 73 return response.data.Hash; 74 };