ES2017 Javascript Module - Cryptopia API

16 Sep 2017

Here’s a file you can use to connect to the Cryptopia API.

This snippet allows you to programmatically access the Cryptopia API using Promises, which is much, much easier than dealing with callbacks, in my opinion. I generally do not release any crypto-related code, but in this case, I think I can help a few people out.

// Sample Usage
public_api('GetMarkets', {hours: 1}).then(res => console.log(res))

const iso_fetch = require('isomorphic-fetch');

function public_api(method, params = {}) {
    return new Promise((resolve, reject) => {
        try {
            const public_methods = [
                'GetCurrencies',
                'GetTradePairs',
                'GetMarkets',
                'GetMarket',
                'GetMarketHistory',
                'GetMarketOrders'
            ];
            const host_name = 'https://www.cryptopia.co.nz';
            let uri = '/Api/' + method;
            if (public_methods.includes(method)) {
                if (params) {
                    uri += "/" + Object.values(params).join('/');
                }
                iso_fetch(host_name + uri)
                    .then(res => res.json())
                    .catch(err => reject(err))
                    .then(res => resolve(res))
                    .catch(err => reject(err))
            } else {
                return reject(new Error(`${method} does not exist in the Cryptopia Public API!`))
            }
        } catch (e) {
            return reject(e)
        }
    })
}

module.exports = public_api;