@filecoin-shipyard/lotus-client-provider-browser
Advanced tools
Comparing version 0.0.4 to 0.0.5
39
index.js
class BrowserProvider { | ||
constructor (url, options = {}) { | ||
this.url = url | ||
this.httpUrl = options.httpUrl || url.replace(/^wss:/, 'https:') | ||
this.httpUrl = | ||
options.httpUrl || url.replace(/^wss:/, 'https:').replace(/^ws:/, 'http:') | ||
this.importUrl = | ||
options.importUrl || this.httpUrl.replace(/\/rpc\//, '/rest/') + '/import' | ||
this.transport = options.transport || 'ws' | ||
this.id = 0 | ||
@@ -25,2 +27,3 @@ this.inflight = new Map() | ||
return new Promise((resolve, reject) => { | ||
if (this.transport !== 'ws') return resolve() | ||
this.ws = new WebSocket(this.url) | ||
@@ -33,3 +36,3 @@ // FIXME: reject on error or timeout | ||
console.error('ws error') | ||
reject() | ||
reject(new Error('websocket error')) | ||
} | ||
@@ -61,6 +64,11 @@ this.ws.onmessage = this.receive.bind(this) | ||
} | ||
return this.sendWs(jsonRpcRequest) | ||
if (this.transport === 'ws') { | ||
return this.sendWs(jsonRpcRequest) | ||
} else { | ||
return this.sendHttp(jsonRpcRequest) | ||
} | ||
} | ||
async sendHttp (jsonRpcRequest) { | ||
await this.connect() | ||
const headers = { | ||
@@ -112,2 +120,10 @@ 'Content-Type': 'text/plain;charset=UTF-8', | ||
} | ||
if (this.transport !== 'ws') { | ||
return [ | ||
() => {}, | ||
Promise.reject( | ||
new Error('Subscriptions only supported for WebSocket transport') | ||
) | ||
] | ||
} | ||
const promise = this.connect().then(() => { | ||
@@ -141,7 +157,9 @@ this.ws.send(JSON.stringify(json)) | ||
}) | ||
this.sendWs({ | ||
jsonrpc: '2.0', | ||
method: 'xrpc.cancel', | ||
params: [json.id] | ||
}) | ||
if (!this.destroyed) { | ||
this.sendWs({ | ||
jsonrpc: '2.0', | ||
method: 'xrpc.cancel', | ||
params: [json.id] | ||
}) | ||
} | ||
}) | ||
@@ -205,2 +223,3 @@ // console.info(`Subscription ${json.id} cancelled, channel ${chanId} closed.`) | ||
async import (body) { | ||
await this.connect() | ||
const headers = { | ||
@@ -218,3 +237,5 @@ 'Content-Type': body.type, | ||
const result = await response.json() | ||
const { Cid: { "/": cid }} = result | ||
const { | ||
Cid: { '/': cid } | ||
} = result | ||
@@ -221,0 +242,0 @@ return cid |
{ | ||
"name": "@filecoin-shipyard/lotus-client-provider-browser", | ||
"version": "0.0.4", | ||
"version": "0.0.5", | ||
"type": "module", | ||
@@ -5,0 +5,0 @@ "scripts": { |
9821
236