all files / RequestClient/ DDragonRequest.js

29.07% Statements 25/86
6.45% Branches 2/31
0% Functions 0/9
30.14% Lines 22/73
1 branch Ignored     
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 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157                                                                                                                                                                                                                                                                              
import request from 'request'
 
export const DDragonRequestTypes = {
    REALMS: 'realms',
    API: 'api',
    CDN: {
        DATA: 'cdn_data',
        IMAGE: 'cdn_img',
    },
}
 
// Not sure how I should handle realms, versions, and a regular URL in an easy-to-code way...
// As realm/version endpoints have different structures from cdn endpoints. We'll see!
// Committing this to just show my thought process for now.
const baseUrl = 'https://ddragon.leagueoflegends.com/'
const createRealmsUrl = endpoint => `${baseUrl}realms/${endpoint}`
const createApiUrl = endpoint => `${baseUrl}/api/${endpoint}`
const createVersionUrl = createApiUrl('versions.json')
const createCdnUrl = (type, version, locale, endpoint) =>
    `${baseUrl}cdn/${version}/${type}/${locale}/${endpoint}`
const createDataUrl = (version, locale, endpoint) =>
    createCdnUrl('data', version, locale, endpoint)
const createImageUrl = (version, locale, endpoint) =>
    createCdnUrl('img', version, locale, endpoint)
 
export const ddragonRequestTypeToUrl = (type, urlInformation) => {
    switch (type) {
        case DDragonRequestTypes.REALMS:
            return createRealmsUrl(urlInformation.endpoint)
        case DDragonRequestTypes.API:
            return createApiUrl(urlInformation.endpoint)
        case DDragonRequestTypes.CDN.DATA:
            return createDataUrl(
                urlInformation.version,
                urlInformation.locale,
                urlInformation.endpoint,
            )
        case DDragonRequestTypes.CDN.IMAGE:
            return createImageUrl(
                urlInformation.version,
                urlInformation.locale,
                urlInformation.endpoint,
            )
        default:
            throw new Error('Invalid DDragonRequestType.')
    }
}
 
function DDragonRequest(config, endpoint, requestType) {
    this.payload = {
        endpoint,
        locale: '',
        version: '',
        type: requestType,
    }
    this.config = config
    this.retriesLeft = this.config.requestOptions.numberOfRetriesBeforeAbort
}
 
DDragonRequest.prototype.locale = function(locale) {
    if (this.payload.locale)
        throw new Error('Do not call DDragonRequest.locale twice.')
    // Add locale checker
    if (locale) this.payload.locale = locale
    return this
}
 
DDragonRequest.prototype.version = function(version) {
    if (typeof obj !== 'string')
        throw new Error('DDragonRequest.version takes in a string.')
    if (version) this.payload.version = version
    return this
}
 
DDragonRequest.prototype.then = function then(resolve, reject) {
    const self = this
    return new Promise((innerResolve, innerReject) =>
        self.callback(
            (err, res) => (err ? innerReject(err) : innerResolve(res)),
        ),
    ).then(resolve, reject)
}
 
DDragonRequest.prototype.catch = callback => this.then(null, callback)
 
DDragonRequest.prototype.callback = function(cb) {
    // TODO: Error checking for `version` and `locale`?
    const { endpoint, locale, version, type } = this.payload
 
    const url = ddragonRequestTypeToUrl(type, { endpoint, locale, version })
 
    this.execute(url, this.retriesLeft, cb)
}
 
DDragonRequest.prototype.execute = async function(url, retriesLeft, cb) {
    const { cacheOptions, debugOptions, requestOptions } = this.config
    const fn = async (err, data) => {
        const debugURL = url
        try {
            if (data) {
                if (debugOptions.isEnabled) {
                    debugOptions.loggers.cache.get(debugURL)
                }
                ok(data)(cb)
            } else {
                if (debugOptions.isEnabled) {
                    debugOptions.loggers.request.outgoing(url)
                }
                // TODO: Handle this in the future, of course.
                const makeRequest = () => new Promise(resolve => resolve(true))
                const res = await makeRequest()
 
                if (debugOptions.isEnabled) {
                    debugOptions.loggers.request.incoming.success(debugURL)
                }
 
                try {
                    const blob = JSON.parse(res)
                    if (
                        cacheOptions.cache &&
                        cacheOptions.ttls[this.methodName] > 0
                    ) {
                        cacheOptions.cache.set(
                            {
                                key: url,
                                ttl: 0, // TODO: Temporary number.
                            },
                            blob,
                        )
                        if (debugOptions.isEnabled) {
                            debugOptions.loggers.cache.set(`${url}`)
                        }
                    }
                    ok(blob)(cb)
                } catch (ex) {
                    console.log(ex)
                }
            }
        } catch (ex) {
            console.error(ex)
            error({
                ddragonErrorTemporary: ex,
            })(cb)
        }
    }
    if (cacheOptions.cache) {
        cacheOptions.cache.get({ key: url }, fn)
    } else {
        fn()
    }
}
 
const ok = blob => cb => cb(null, blob)
const error = blob => cb => cb(blob, null)
 
export default DDragonRequest