klequis / coding-notebook

notes on coding issues
MIT License
0 stars 0 forks source link

Decode Parse URL Node #16

Open klequis opened 2 years ago

klequis commented 2 years ago

urlToHttpOptions requires node 16.x and up.

Decode

const url = 'https://example.com'
const b =const result = decodeURIComponent(url)
log('b', b)

Parse

requires node 16+

const parse = (url) => {
  return urlToHttpOptions(new URL(url))
}

Do both using Either

import { urlToHttpOptions } from 'url'
import { Either } from './Either'
const log = console.log
const l = (msg) => (val) => console.log(msg, val)

function decode(url) {
  try {
    const result = decodeURIComponent(url)
    return Either.of(result)
  } catch (uriError) {
    return Either.left(uriError)
  }
}

const parse = (url) => {
  return urlToHttpOptions(new URL(url))
}

const a = decode('%').map(parse) //-> Left(Error('URI malformed'))
log('a', a)
const b = decode('http%3A%2F%2Fexample.com').map(parse)
log('b', b)