hoodunit / purescript-payload

An HTTP server and client library for PureScript
Apache License 2.0
100 stars 11 forks source link

`DecodeResponse` are not extendable #30

Closed Renegatto closed 1 year ago

Renegatto commented 1 year ago

Due to use of default instance it is not currently possible to make user defined instances of DecodeResponse. The default instance has been made to not force users writing their own instances for undecodable responses. Since users are unable to define their own instances the feature seems as not worth it.

However, there is an alternative way of achieving the same goal. Using the solution an instances for undecidable responses will not be for free, but instead would require user to write three lines of simple boilerplate including library import.

Solution

Payload.Client.DecodeResponse.purs:

newtype FailResponseDecoding a = FailResponseDecoding a
derive instance Newtype (FailResponseDecoding a) _

instance Warn ... => DecodeResponse (FailResponseDecoding a) where
  ...

-- This function is meant to be exported
-- | Implementation for an instance that fails decoding
failResponseDecoding :: forall a. String -> Maybe a
failResponseDecoding = map (unwrap :: FailResponseDecoding a -> a) <<< decodeResponse

If user has some type Foo that will fail decoding as a response:

instance DecodeResponse (FailResponseDecoding Foo) where
  decodeResponse = failResponseDecoding

Here user gets a warning. Please note that user gets the warning exactly in place where it can be fixed, not in the code that uses the cursed instance.

hoodunit commented 1 year ago

Thanks for the clear issue - this is resolved in https://github.com/hoodunit/purescript-payload/commit/df202de84d5de825b9264c18e90655cbec65eca4 in the way you outlined here.