From 28aff364a3fd9581e6fc0333392257c216bfb70e Mon Sep 17 00:00:00 2001 From: Felix Deiters Date: Mon, 28 Feb 2022 11:53:20 +0100 Subject: [PATCH] Allow to inject fetch to objectloader constructor --- packages/objectloader/examples/node/script.js | 25 ++++++++++++++++++- packages/objectloader/index.js | 8 +++--- 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/packages/objectloader/examples/node/script.js b/packages/objectloader/examples/node/script.js index 9267d5241..1afc85526 100644 --- a/packages/objectloader/examples/node/script.js +++ b/packages/objectloader/examples/node/script.js @@ -1 +1,24 @@ -// NOTE: This lib is not working in node, because node-fetch returns node-native readable streams - we need a workaround first. +// Since Node v<18 does not provide fetch, we need to pass it in the options object. Note that fetch must return a WHATWG compliant stream, so cross-fetch won't work, but node/undici's implementation will. + +import { fetch } from 'undici' +import ObjectLoader from '../../index.js' + +let loader = new ObjectLoader({ + serverUrl:"https://latest.speckle.dev", + streamId:"3ed8357f29", + objectId:"0408ab9caaa2ebefb2dd7f1f671e7555", + options:{ enableCaching: false, excludeProps:[], fetch } +}) + + +let loadData = async function loadData() { + + let obj = await loader.getAndConstructObject((e) =>{ + console.log(e) // log progress! + }) + + console.log('Done!') + console.log( obj ) +} + +loadData() diff --git a/packages/objectloader/index.js b/packages/objectloader/index.js index 2f73094df..6d3ee2a2a 100644 --- a/packages/objectloader/index.js +++ b/packages/objectloader/index.js @@ -10,7 +10,7 @@ export default class ObjectLoader { * Creates a new object loader instance. * @param {*} param0 */ - constructor( { serverUrl, streamId, token, objectId, options = { enableCaching: true, fullyTraverseArrays: false, excludeProps: [ ] } } ) { + constructor( { serverUrl, streamId, token, objectId, options = { enableCaching: true, fullyTraverseArrays: false, excludeProps: [ ], fetch:null } } ) { this.INTERVAL_MS = 20 this.TIMEOUT_MS = 180000 // three mins @@ -48,6 +48,8 @@ export default class ObjectLoader { this.lastAsyncPause = Date.now() this.existingAsyncPause = null + this.fetch = this.options.fetch || window.fetch + } async asyncPause() { @@ -329,7 +331,7 @@ export default class ObjectLoader { readBuffers.push( '' ) finishedRequests.push( false ) - fetch( + this.fetch( this.requestUrlChildren, { method: 'POST', @@ -397,7 +399,7 @@ export default class ObjectLoader { const cachedRootObject = await this.cacheGetObjects( [ this.objectId ] ) if ( cachedRootObject[ this.objectId ] ) return cachedRootObject[ this.objectId ] - const response = await fetch( this.requestUrlRootObj, { headers: this.headers } ) + const response = await this.fetch( this.requestUrlRootObj, { headers: this.headers } ) const responseText = await response.text() this.cacheStoreObjects( [ `${this.objectId}\t${responseText}` ] ) return responseText