api.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import fetch from 'node-fetch';
  2. import {promisify} from 'util';
  3. import Config from './util/config.js';
  4. let oauth_token = null;
  5. async function osu_fetch(url, options) {
  6. options = options || {};
  7. let res;
  8. if (!oauth_token) {
  9. try {
  10. res = await fetch('https://osu.ppy.sh/oauth/token', {
  11. method: 'post',
  12. body: JSON.stringify({
  13. client_id: Config.osu_v2api_client_id,
  14. client_secret: Config.osu_v2api_client_secret,
  15. grant_type: 'client_credentials',
  16. scope: 'public',
  17. }),
  18. headers: {
  19. 'Accept': 'application/json',
  20. 'Content-Type': 'application/json',
  21. },
  22. });
  23. } catch (err) {
  24. throw new Error(`Got system error ${err.code} while fetching OAuth token.`);
  25. }
  26. const foo = await res.json();
  27. oauth_token = foo.access_token;
  28. }
  29. if (!options.headers) {
  30. options.headers = {
  31. 'Accept': 'application/json',
  32. 'Content-Type': 'application/json',
  33. };
  34. }
  35. options.headers['Authorization'] = 'Bearer ' + oauth_token;
  36. try {
  37. res = await fetch(url, options);
  38. } catch (err) {
  39. throw new Error(`Got system error ${err.code} while fetching '${url}'.`);
  40. }
  41. if (res.status == 401) {
  42. console.log('OAuth token expired, fetching a new one...');
  43. oauth_token = null;
  44. await promisify(setTimeout)(1000);
  45. return await osu_fetch(url, options);
  46. } else if (res.status == 404) {
  47. throw new Error('Not found');
  48. } else {
  49. const json = await res.json();
  50. return json;
  51. }
  52. }
  53. export {osu_fetch};