|
| 1 | +{-# LANGUAGE AllowAmbiguousTypes #-} |
| 2 | +{-# LANGUAGE FlexibleContexts #-} |
| 3 | +{-# LANGUAGE ScopedTypeVariables #-} |
| 4 | + |
| 5 | +module GraphQL.Wai |
| 6 | + ( toApplication |
| 7 | + ) where |
| 8 | + |
| 9 | +import Protolude |
| 10 | + |
| 11 | +import GraphQL (interpretAnonymousQuery) |
| 12 | +import GraphQL.Resolver (HasResolver, Handler) |
| 13 | +import Network.Wai (Application, queryString, responseLBS) |
| 14 | +import GraphQL.Value.ToValue (toValue) |
| 15 | +import Network.HTTP.Types.Header (hContentType) |
| 16 | +import Network.HTTP.Types.Status (status200, status400) |
| 17 | +import qualified Data.Aeson as Aeson |
| 18 | + |
| 19 | + |
| 20 | +-- | Adapt a GraphQL handler to a WAI application. This is really just |
| 21 | +-- to illustrate the mechanism, and not production ready at this point |
| 22 | +-- in time. |
| 23 | +-- |
| 24 | +-- If you have a 'Cat' type and a corresponding 'catHandler' then you |
| 25 | +-- can use "toApplication @Cat catHandler". |
| 26 | +toApplication :: forall r. (HasResolver IO r) => Handler IO r -> Application |
| 27 | +toApplication handler = app |
| 28 | + where |
| 29 | + app req respond = |
| 30 | + case queryString req of |
| 31 | + [("query", Just query)] -> do |
| 32 | + r <- interpretAnonymousQuery @r handler (toS query) |
| 33 | + let json = Aeson.encode (toValue r) |
| 34 | + respond $ responseLBS status200 [(hContentType, "application/json")] json |
| 35 | + _ -> respond $ responseLBS status400 [] "Must provide excatly one query GET argument." |
0 commit comments