async post (action: unknown, data: unknown): Promise<unknown> {
const env = typeof process !== 'undefined' && 'env' in process ? process.env : null
this.#validate(action)
- action = action.toLowerCase()
const headers: Record<string, string> = {}
headers['Content-Type'] = 'application/json'
if (this.#n && env?.LIBNEMO_RPC_API_KEY) {
if (data !== undefined && typeof data !== 'object') {
throw new TypeError('Invalid RPC post data')
}
- const body = (data as Record<string, unknown>) ?? {}
- if ('action' in body && (typeof body.action !== 'string' || body.action.toLowerCase() !== action)) {
- throw new RangeError(`RPC post data contains 'action' property and does not match 'action' parameter argument. Do not include 'action' in request data.`, { cause: JSON.stringify({ data, body }) })
+ const reqBody: Record<string, unknown> = { ...data }
+ if ('action' in reqBody && (typeof reqBody.action !== 'string' || reqBody.action.toLowerCase() !== action.toLowerCase())) {
+ throw new RangeError(`RPC post data contains 'action' property and does not match 'action' parameter argument. Do not include 'action' in request data.`, { cause: JSON.stringify(reqBody) })
}
- body.action = action
+ reqBody.action = action.toLowerCase()
const aborter = new AbortController()
const req = new Request(this.#u, {
signal: aborter.signal,
method: 'POST',
headers,
- body: JSON.stringify(body)
+ body: JSON.stringify(reqBody)
})
const kill = setTimeout(() => {
console.log('aborting RPC call')
}, 10000)
try {
const res = await fetch(req)
- const data = await res.json()
+ const resBody = await res.json()
if (res.status !== 200) {
- throw new Error(`${res.status} ${res.statusText}`, { cause: data })
+ throw new Error(`${res.status} ${res.statusText}`, { cause: resBody })
}
- if (data.error != null) {
- const msg = data.message == null
- ? data.error
- : `${data.error} ${data.message}`
+ if (resBody.error != null) {
+ const msg = resBody.message == null
+ ? resBody.error
+ : `${resBody.error} ${resBody.message}`
throw new Error(msg)
}
- return data
+ return resBody
} catch (err) {
console.error(err)
throw new Error(`RPC ${action} request failed`, { cause: err })