1
0
mirror of https://github.com/oceanprotocol/ocean.js.git synced 2024-11-26 20:39:05 +01:00
ocean.js/src/utils/FetchHelper.ts
mihaisc 56a3aad20d
heleper+ remove old ibs (#1238)
* heleper+ remove old ibs

* fix tests

* fix gaslimt

* fix approve

* fix

* remove console.log

* upate package-lock
2022-01-25 08:32:55 -08:00

79 lines
1.8 KiB
TypeScript

import fetch from 'cross-fetch'
import LoggerInstance from './Logger'
import { DownloadResponse } from '../@types/DownloadResponse'
export async function fetchData(url: string, opts: RequestInit): Promise<Response> {
const result = await fetch(url, opts)
if (!result.ok) {
LoggerInstance.error(`Error requesting [${opts.method}] ${url}`)
LoggerInstance.error(`Response message: \n${await result.text()}`)
throw result
}
return result
}
export async function downloadFileBrowser(url: string): Promise<void> {
const anchor = document.createElement('a')
anchor.download = ''
anchor.href = url
anchor.click()
}
export async function downloadFile(
url: string,
index?: number
): Promise<DownloadResponse> {
const response = await fetch(url)
if (!response.ok) {
throw new Error('Response error.')
}
let filename: string
try {
filename = response.headers
.get('content-disposition')
.match(/attachment;filename=(.+)/)[1]
} catch {
try {
filename = url.split('/').pop()
} catch {
filename = `file${index}`
}
}
return { data: await response.arrayBuffer(), filename }
}
export async function getData(url: string): Promise<Response> {
return fetch(url, {
method: 'GET',
headers: {
'Content-type': 'application/json'
}
})
}
async function postWithHeaders(
url: string,
payload: BodyInit,
headers: any
): Promise<Response> {
if (payload != null) {
return fetch(url, {
method: 'POST',
body: payload,
headers
})
} else {
return fetch(url, {
method: 'POST'
})
}
}
export async function postData(url: string, payload: BodyInit): Promise<Response> {
const headers = {
'Content-type': 'application/json'
}
return postWithHeaders(url, payload, headers)
}