fix: fetch in nodejs

This commit is contained in:
Xmader 2020-11-24 05:02:14 -05:00
parent 7f8f635677
commit bfdd80a364
No known key found for this signature in database
GPG Key ID: A20B97FB9EB730E4
2 changed files with 13 additions and 2 deletions

View File

@ -1,10 +1,10 @@
import { saveAs, assertRes } from './utils'
import { saveAs, assertRes, getFetch } from './utils'
import { ScoreInfo } from './scoreinfo'
const MSCZ_BUF_SYM = Symbol('msczBufferP')
export const fetchMscz = async (scoreinfo: ScoreInfo, _fetch = fetch): Promise<ArrayBuffer> => {
export const fetchMscz = async (scoreinfo: ScoreInfo, _fetch = getFetch()): Promise<ArrayBuffer> => {
let msczBufferP = scoreinfo.store.get(MSCZ_BUF_SYM) as Promise<ArrayBuffer> | undefined
if (!msczBufferP) {

View File

@ -1,5 +1,6 @@
import FileSaver from 'file-saver/dist/FileSaver.js'
import isNodeJs from 'detect-node'
export const saveAs: typeof import('file-saver').saveAs = FileSaver.saveAs
@ -13,6 +14,15 @@ export const getIndexPath = (id: number): string => {
return indexN.join('/')
}
export const getFetch = (): typeof fetch => {
if (!isNodeJs) {
return fetch
} else {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return require('node-fetch')
}
}
export const fetchData = async (url: string, init?: RequestInit): Promise<Uint8Array> => {
const r = await fetch(url, init)
const data = await r.arrayBuffer()
@ -37,6 +47,7 @@ export const useTimeout = async <T> (promise: T | Promise<T>, ms: number): Promi
}
export const getSandboxWindow = (): Window => {
if (typeof document === 'undefined') return {} as any as Window
const iframe = document.createElement('iframe')
iframe.style.display = 'none'
document.body.append(iframe)