#javascript #technology

idea

Date

Default dates are already pretty powerful, you don't need moment.

This is how you format a date[1]:

new Date().toLocaleString('en-us', { weekday:"long", year:"numeric", month:"short", day:"numeric"}) 
// "Friday, Jul 2, 2021"

Options are using available there.

When parsing a date, if it's local append the timediff to the string (e.g. -0800). If it's UTC add "Z".

Network

Request in browser

function sendQueryAsync(url, method = "GET", body = undefined, headers = {}) {
  return new Promise((resolve, reject) => {
    const request = new XMLHttpRequest()
    request.onreadystatechange = function () {
      if (this.readyState === 4) {
        try {
        if (this.getResponseHeader("Content-Type") === "application/json") {
          const response = JSON.parse(this.responseText)
            if (response.result === "success") {
              resolve(response.data)
            } else {
              reject(Error(response.error))
            }
        } else {
          resolve(this.responseText)
        }

        } catch (err) {
          reject(Error(this.responseText))
        }
      }
    }
    request.open(method, `/api/${url}`, true)
    Object.keys(headers).forEach(header => {
      request.setRequestHeader(header, headers[header])
    })
    if (body) {
      request.setRequestHeader("content-type", "application/json")
    }
    request.send(body ? JSON.stringify(body) : undefined)
  })
}

links

references

[1]: Some freecode article and MDN doc