diff --git a/components/webapi.js b/components/webapi.js index 1335783..1312f6d 100644 --- a/components/webapi.js +++ b/components/webapi.js @@ -1,48 +1,52 @@ +const StdLib = require('@doctormckay/stdlib'); + const SteamCommunity = require('../index.js'); const Helpers = require('./helpers.js'); +/** + * @param {string} domain + * @param {function} [callback] + * @return Promise<{key: string}> + */ SteamCommunity.prototype.getWebApiKey = function(domain, callback) { - this.httpRequest({ - uri: 'https://steamcommunity.com/dev/apikey?l=english', - followRedirect: false - }, (err, response, body) => { - if (err) { - callback(err); - return; + return StdLib.Promises.callbackPromise(['key'], callback, false, async (resolve, reject) => { + let {textBody} = await this.httpRequest({ + method: 'GET', + url: 'https://steamcommunity.com/dev/apikey?l=english', + followRedirect: false, + source: 'steamcommunity' + }); + + if (textBody.includes('

Access Denied

')) { + return reject(new Error('Access Denied')); } - if (body.includes('

Access Denied

')) { - return callback(new Error('Access Denied')); + if (textBody.includes('You must have a validated email address to create a Steam Web API key.')) { + return reject(new Error('You must have a validated email address to create a Steam Web API key.')); } - if (body.includes('You must have a validated email address to create a Steam Web API key.')) { - return callback(new Error('You must have a validated email address to create a Steam Web API key.')); - } - - let match = body.match(/

Key: ([0-9A-F]+)<\/p>/); + let match = textBody.match(/

Key: ([0-9A-F]+)<\/p>/); if (match) { // We already have an API key registered - callback(null, match[1]); - } else { - // We need to register a new API key - this.httpRequestPost('https://steamcommunity.com/dev/registerkey?l=english', { - form: { - domain, - agreeToTerms: 'agreed', - sessionid: this.getSessionID(), - Submit: 'Register' - } - }, (err, response, body) => { - if (err) { - callback(err); - return; - } - - this.getWebApiKey(domain, callback); - }, 'steamcommunity'); + return resolve({key: match[1]}); } - }, "steamcommunity"); + + // We need to register a new API key + await this.httpRequest({ + method: 'POST', + url: 'https://steamcommunity.com/dev/registerkey?l=english', + form: { + domain, + agreeToTerms: 'agreed', + sessionid: this.getSessionID(), + Submit: 'Register' + }, + source: 'steamcommunity' + }); + + resolve({key: await this.getWebApiKey(domain)}); + }); }; /**