All files / src/api client.ts

75% Statements 27/36
52.5% Branches 21/40
100% Functions 8/8
75% Lines 27/36

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138                                                              1x     1x             1x                                   1x 1x       1x 1x 1x         3x 3x         1x 1x         1x 1x         1x 1x         1x         5x 5x               5x                                 57x 57x 57x 1x   56x 40x   16x      
import {APIProvider, APIResponse, FetchProvider, FetchProviderOptions} from './provider'
import {ABISerializableConstructor, ABISerializableType} from '../serializer/serializable'
import {abiDecode} from '../serializer/decoder'
import {ChainAPI} from './v1/chain'
import {HistoryAPI} from './v1/history'
import {BuiltinTypes} from '../serializer/builtins'
 
export {ChainAPI, HistoryAPI}
 
export interface APIClientOptions extends FetchProviderOptions {
    /** URL to the API node to use, only used if the provider option is not set. */
    url?: string
    /** API provider to use, if omitted and the url option is set the default provider will be used.  */
    provider?: APIProvider
}
 
export interface APIErrorDetail {
    message: string
    file: string
    line_number: number
    method: string
}
 
export interface APIErrorData {
    code: number
    name: string
    what: string
    details: APIErrorDetail[]
}
 
export class APIError extends Error {
    static __className = 'APIError'
 
    static formatError(error: APIErrorData) {
        Eif (
            error.what === 'unspecified' &&
            error.details[0].file &&
            error.details[0].file === 'http_plugin.cpp' &&
            error.details[0].message.slice(0, 11) === 'unknown key'
        ) {
            // fix cryptic error messages from nodeos for missing accounts
            return 'Account not found'
        } else if (error.what === 'unspecified' && error.details && error.details.length > 0) {
            return error.details[0].message
        } else if (error.what && error.what.length > 0) {
            return error.what
        } else {
            return 'Unknown API error'
        }
    }
 
    /** The path to the API that failed, e.g. `/v1/chain/get_info`. */
    readonly path: string
 
    /** The full response from the API that failed. */
    readonly response: APIResponse
 
    constructor(path: string, response: APIResponse) {
        let message: string
        Eif (response.json && response.json.error) {
            message = `${APIError.formatError(response.json.error)} at ${path}`
        } else {
            message = `HTTP ${response.status} at ${path}`
        }
        super(message)
        this.path = path
        this.response = response
    }
 
    /** The nodeos error object. */
    get error() {
        const {json} = this.response
        return (json ? json.error : undefined) as APIErrorData | undefined
    }
 
    /** The nodeos error name, e.g. `tx_net_usage_exceeded` */
    get name() {
        const {error} = this
        return error ? error.name : 'unspecified'
    }
 
    /** The nodeos error code, e.g. `3080002`. */
    get code() {
        const {error} = this
        return error ? error.code : 0
    }
 
    /** List of exceptions, if any. */
    get details() {
        const {error} = this
        return error ? error.details : []
    }
}
 
export class APIClient {
    static __className = 'APIClient'
 
    readonly provider: APIProvider
 
    constructor(options: APIClientOptions) {
        Eif (options.provider) {
            this.provider = options.provider
        } else if (options.url) {
            this.provider = new FetchProvider(options.url, options)
        } else {
            throw new Error('Missing url or provider')
        }
    }
 
    v1 = {
        chain: new ChainAPI(this),
        history: new HistoryAPI(this),
    }
 
    async call<T extends ABISerializableConstructor>(args: {
        path: string
        params?: unknown
        responseType: T
    }): Promise<InstanceType<T>>
    async call<T extends keyof BuiltinTypes>(args: {
        path: string
        params?: unknown
        responseType: T
    }): Promise<BuiltinTypes[T]>
    async call<T = unknown>(args: {path: string; params?: unknown}): Promise<T>
    async call(args: {path: string; params?: unknown; responseType?: ABISerializableType}) {
        const response = await this.provider.call(args.path, args.params)
        const {json} = response
        if (Math.floor(response.status / 100) !== 2 || (json && typeof json.error === 'object')) {
            throw new APIError(args.path, response)
        }
        if (args.responseType) {
            return abiDecode({type: args.responseType, object: response.json})
        }
        return response.json || response.text
    }
}