UNPKG

coinbase-pro-node-api

Version:
86 lines (85 loc) 2.58 kB
import { stringify } from "node:querystring"; import { Headers } from "node-fetch"; import { FetchClient } from "rpc-request"; export const ApiUri = "https://api.exchange.coinbase.com"; export const SandboxApiUri = "https://api-public.sandbox.exchange.coinbase.com"; export const DefaultProductID = "BTC-USD"; export class PublicClient extends FetchClient { #product_id; #api_url; constructor({ product_id = DefaultProductID, sandbox = false, apiUri = sandbox ? SandboxApiUri : ApiUri, } = {}) { super({}, { rejectNotOk: false, transform: "raw", baseUrl: apiUri }); this.#api_url = new URL(apiUri); this.#product_id = product_id; } get product_id() { return this.#product_id; } get apiUri() { return new URL(this.#api_url.toString()); } async fetch(path, options = {}) { const headers = new Headers(options.headers); if (options.body) { headers.set("Content-Type", "application/json"); } const response = await super.fetch(path, { ...options, headers, }); const text = await response.text(); const data = PublicClient.#parseJSON(text); if (!response.ok) { throw new Error(data?.message ?? text); } return data ?? text; } getProducts() { return this.get("/products"); } getProduct({ product_id = this.product_id } = {}) { return this.get(`/products/${product_id}`); } getOrderBook({ product_id = this.product_id, ...qs } = {}) { const url = new URL(`/products/${product_id}/book`, this.apiUri); url.search = stringify({ ...qs }); return this.get(url.toString()); } getTicker({ product_id = this.product_id } = {}) { return this.get(`/products/${product_id}/ticker`); } getTrades({ product_id = this.product_id, ...qs } = {}) { const url = new URL(`/products/${product_id}/trades`, this.apiUri); url.search = stringify({ ...qs }); return this.get(url.toString()); } getHistoricRates({ product_id = this.product_id, ...qs }) { const url = new URL(`/products/${product_id}/candles`, this.apiUri); url.search = stringify({ ...qs }); return this.get(url.toString()); } get24hrStats({ product_id = this.product_id } = {}) { return this.get(`/products/${product_id}/stats`); } getCurrencies() { return this.get("/currencies"); } getCurrency({ id }) { return this.get(`/currencies/${id}`); } getTime() { return this.get("/time"); } static #parseJSON(string) { let output; try { return JSON.parse(string); } catch { return output; } } }