-1

I have an existing server written using the Servant library. I now want to make the endpoints conditional such that based on certain configuration or logic, I would like to serve (or not serve) a particular endpoint. What's the best way to do this?

I've tried using EmptyAPI from Servant.API but it didn't work. For context, I'm currently using toServant from Servant.API.Generic for most of my routes.

Fyodor Soikin
  • 78,590
  • 9
  • 125
  • 172
  • 1
    What would you like to happen if a client tries to access a particular endpoint, but your consideration says that this endpoint shouldn't be served? – Fyodor Soikin Jan 15 '20 at 12:24
  • 1
    What would normally happen if any client tries to access an endpoint that's not being served/does not exist. Either a 404 or some configured error message or page? – Kahlil Abreu Jan 15 '20 at 12:39
  • 1
    You can't conditionally use the proxy value because the type must match. Instead you can `if b then serve api1 else serve api2`. – Thomas M. DuBuisson Jan 15 '20 at 19:06

1 Answers1

1

If you're ok with returning 404 when the endpoint is "off", you can do that by throwing the corresponding Servant error:

server = toServant MyEndpointsRecord
    { ...

    , cleverEndpoint = do
        shouldServe <- isCleverEndpointEnabled
        if shouldServe 
            then serveCleverEndpoint
            else throwError err404

    ...
    }

You can also wrap this for reuse if you need to do this often:

guarded checkConfig f = do
    shouldServe <- checkConfig
    if shouldServe 
        then f
        else throwError err404


server = toServant MyEndpointsRecord
    { ...

    , cleverEndpoint = guarded isCleverEndpointEnabled serveCleverEndpoint

    ...
    }
Fyodor Soikin
  • 78,590
  • 9
  • 125
  • 172