cyperdark / osu-api-extended

Package for advanced work with "osu" api
MIT License
47 stars 16 forks source link

Replace axios with this script :D #5

Closed aqilc closed 2 years ago

aqilc commented 3 years ago

Axios is bloated, old, outdated, complicated, scuffed and bloated.

this literal 20sloc can replace almost all of the relevant functionalities :>


// HTTPS API
import https from 'https'

/**
 * Executes an HTTP request
 * @param {string | URL} url The url
 * @returns {Promise<any>} The response
 */
export default (url, { method, headers, data, referrer, refererPolicy, body, mode } = {}) => new Promise((res, rej) => {

  // Starts a new HTTPS request
  const req = https.request(url, { method, headers, referrer, refererPolicy, body, mode }, r => {

    // Stores data
    let data = ''

    // Stores data chunks
    r.on('data', chunk => data += chunk)

    // Sends response on end of request
    r.on('end', () => {

      // If the format was JSON, parse(with test) and return
      if (/^application\/json/.test(r.headers['content-type']))
        try { return res(JSON.parse(data)) } catch (err) { console.log(`JSON Parse on content of type ${r.headers['content-type']} failed.\nError: ${err}\nData: ${data}`) }

      // Sends raw data as response if no json
      res(data)
    })
  }).on('error', rej)

  // If there is data to be sent, send it
  if (data) req.write(data)

  // Sends the request
  req.end()
})

usage:


import get from "get.js"

await get("your mother's url", { body: "idk man maybe ur mom or something", method: "post" })
aqilc commented 2 years ago

p.s.

i did it for you here if you want https://github.com/AqilCont/osu-api-extended

roansong commented 2 years ago

Very cool. My only input here is that instead of "get" and "get.js" it should probably be "request" or something, given that you can do GET/POST/PUT etc with this

aqilc commented 2 years ago

I mean ultimately, it gets data from a source. I don't really care about naming though, up to you. This script is completely free to manipulate and use by anyone :D

aqilc commented 2 years ago

Oh, my Discord is aqil#7927