Coder Social home page Coder Social logo

fetcher-ts's Introduction

Hey there! ๐Ÿ‘‹

I'm Yuriy Bogomolov, a seasoned software architect with a passion for functional programming, type systems, and category theory. You might recognize me from my work on #MonadicMondays, my lectures and workshops on YouTube, or my contributions to the fp-ts ecosystem. And if you're looking for some additional resources, I also write articles on my personal blog that cover everything from the basics of functional programming to advanced techniques and best practices.

Are you an individual developer or part of a small team looking to level up your functional programming skills in TypeScript? Look no further, because I'm here to help. As a mentor, I offer personalized guidance and support as you navigate the complex world of functional programming. Whether you're just starting out or looking to take your skills to the next level, I'll work with you to develop a customized learning plan that fits your unique needs and goals.

So why wait? Let's start your journey towards mastering functional programming in TypeScript today. You can reach me via email at [email protected], or shoot me a message on Telegram - I'm always happy to chat!

fetcher-ts's People

Contributors

dependabot[bot] avatar ritschwumm avatar ybogomolov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

fetcher-ts's Issues

Feedback

Based on the following (self imposed) requirements:

  • the library shouldn't be tied to io-ts
  • the library shouldn't be tied to cross-fetch
  • decoding shouldn't be optional (not recommended but you can always resort to a dummy decoder like E.right)
  • a handler for unexpected errors shouldn't be optional

I would propose an API like this:

import * as E from 'fp-ts/lib/Either'
import { ReaderEither } from 'fp-ts/lib/ReaderEither'
import { TaskEither } from 'fp-ts/lib/TaskEither'

type _Fetch = typeof fetch

export interface Fetch extends _Fetch {}

export interface Decoder<E, A> extends ReaderEither<unknown, E, A> {}

type Status = 200 | 400 | 500 // etc...

export type FetcherError =
  | { readonly type: 'JsonDeserializationError'; readonly details: unknown }
  | { readonly type: 'HandlerNotSetError'; readonly status: number }

export interface Fetcher<S extends Status, E, A> {
  readonly input: RequestInfo
  readonly handlers: Record<S, Decoder<E, A>>
  readonly onUnexpectedError: (error: FetcherError) => E.Either<E, A>
  readonly init?: RequestInit
}

export function make<S extends Status, E, A>(
  input: RequestInfo,
  handlers: Record<S, Decoder<E, A>>,
  onUnexpectedError: (error: FetcherError) => E.Either<E, A>,
  init?: RequestInit
): Fetcher<S, E, A> {
  return { input, onUnexpectedError, handlers, init }
}

export function toTaskEither(fetch: Fetch): <S extends Status, E, A>(fetcher: Fetcher<S, E, A>) => TaskEither<E, A> {
  // sketch implementation
  return <S extends Status, E, A>(fetcher: Fetcher<S, E, A>) => async () => {
    const isStatus = (status: number): status is S => fetcher.handlers.hasOwnProperty(status)
    const response = await fetch(fetcher.input, fetcher.init)
    const status = response.status
    if (isStatus(status)) {
      try {
        const contentType = response.headers.get('content-type')
        const body: unknown =
          contentType?.includes('application/json') !== undefined ? await response.json() : await response.text()
        const handler = fetcher.handlers[status]
        return handler(body)
      } catch (details) {
        return fetcher.onUnexpectedError({ type: 'JsonDeserializationError', details })
      }
    } else {
      return fetcher.onUnexpectedError({ type: 'HandlerNotSetError', status })
    }
  }
}

Example

import * as t from 'io-ts'
import { failure } from 'io-ts/lib/PathReporter'
import { flow } from 'fp-ts/lib/function'
import { fetch } from 'cross-fetch'

const taskify = toTaskEither(fetch)

type MyError = { readonly type: 'unexpectedError' } | { readonly type: 'decodeError'; readonly message: string }

const unexpectedError: MyError = { type: 'unexpectedError' }

const decodeError = (errors: t.Errors): MyError => ({
  type: 'decodeError',
  message: failure(errors).join('\n')
})

const getFetcher = (url: string): Fetcher<200 | 400, MyError, string> =>
  make(
    url,
    {
      200: flow(
        t.type({ title: t.string }).decode,
        E.bimap(decodeError, user => user.title)
      ),
      400: flow(t.string.decode, E.mapLeft(decodeError))
    },
    () => E.left(unexpectedError)
  )

// te: TaskEither<Err, string>
const te = taskify(getFetcher('https://jsonplaceholder.typicode.com/posts/1'))

te().then(console.log)
/*
{ _tag: 'Right',
  right:
   'sunt aut facere repellat provident occaecati excepturi optio reprehenderit' }
*/

taskify(getFetcher('https://jsonplaceholder.typicode.com/posts'))().then(console.log)
/*
{ _tag: 'Left',
  left:
   { type: 'decodeError',
     message:
      'Invalid value undefined supplied to : { title: string }/title: string' } }
*/

Why does the return type has a optional decode Error?

I've been scratching my head not able to figure out the reason for the run()'s return type's signature. Is it possible to have a decode error while also having an output?

I was expecting a return type of run() to be Either<io.Error, To>, where To itself can be an Either.

What was the reason to have a tuple with an optional decode error?

Response headers are lost

Currently response is treated either as JSON or as text. No header information is extracted during processing. This may be required for codes like 202/204, as they usually carry no useful payload in the body of response.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.