Compare commits
30 Commits
Author | SHA1 | Date | |
---|---|---|---|
3497784984 | |||
587aab005e | |||
625d7100ca | |||
73e21661b4 | |||
7b92e5bcfd | |||
115aa02672 | |||
31c516927d | |||
1dd6b7b013 | |||
b77da3d492 | |||
73fc334bf8 | |||
417ff5da7d | |||
0e3b6184be | |||
51d39b69e8 | |||
75bc3b8509 | |||
c7d5b02911 | |||
37254c8c95 | |||
856efc5d25 | |||
b2a9ec7d82 | |||
0d142fb01c | |||
f767f6cd40 | |||
eb98c36258 | |||
70f7e1bd8e | |||
2b5c719ab0 | |||
c075a41582 | |||
721cbaee17 | |||
1704022e74 | |||
63d4de485d | |||
22313d05df | |||
c1943c1979 | |||
5175586def |
1
.gitignore
vendored
1
.gitignore
vendored
@ -8,3 +8,4 @@
|
|||||||
.cabal-sandbox/
|
.cabal-sandbox/
|
||||||
cabal.sandbox.config
|
cabal.sandbox.config
|
||||||
cabal.project.local
|
cabal.project.local
|
||||||
|
/graphql.cabal
|
||||||
|
81
CHANGELOG.md
81
CHANGELOG.md
@ -1,6 +1,84 @@
|
|||||||
# Change Log
|
# Change Log
|
||||||
All notable changes to this project will be documented in this file.
|
All notable changes to this project will be documented in this file.
|
||||||
|
|
||||||
|
## [0.6.0.0] - 2019-11-27
|
||||||
|
### Changed
|
||||||
|
- `Language.GraphQL.Encoder` moved to `Language.GraphQL.AST.Encoder`.
|
||||||
|
- `Language.GraphQL.Parser` moved to `Language.GraphQL.AST.Parser`.
|
||||||
|
- `Language.GraphQL.Lexer` moved to `Language.GraphQL.AST.Lexer`.
|
||||||
|
- All `Language.GraphQL.AST.Value` data constructor prefixes were removed. The
|
||||||
|
module should be imported qualified.
|
||||||
|
- All `Language.GraphQL.AST.Core.Value` data constructor prefixes were removed.
|
||||||
|
The module should be imported qualified.
|
||||||
|
- `Language.GraphQL.AST.Core.Object` is now just a HashMap.
|
||||||
|
- `Language.GraphQL.AST.Transform` is isn't exposed publically anymore.
|
||||||
|
- `Language.GraphQL.Schema.resolve` accepts a selection `Seq` (`Data.Sequence`)
|
||||||
|
instead of a list. Selections are stored as sequences internally as well.
|
||||||
|
- Add a reader instance to the resolver's monad stack. The Reader contains
|
||||||
|
a Name/Value hashmap, which will contain resolver arguments.
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Nested fragment support.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- Consume ignored tokens after `$` and `!`. I mistakenly assumed that
|
||||||
|
`$variable` is a single token, same as `Type!` is a single token. This is not
|
||||||
|
the case, for example `Variable` is defined as `$ Name`, so these are two
|
||||||
|
tokens, therefore whitespaces and commas after `$` and `!` should be
|
||||||
|
consumed.
|
||||||
|
|
||||||
|
### Improved
|
||||||
|
- `Language.GraphQL.AST.Parser.type_`: Try type parsers in a variable
|
||||||
|
definition in a different order to avoid using `but`.
|
||||||
|
|
||||||
|
### Removed
|
||||||
|
- `Language.GraphQL.AST.Arguments`. Use `[Language.GraphQL.AST.Argument]`
|
||||||
|
instead.
|
||||||
|
- `Language.GraphQL.AST.Directives`. Use `[Language.GraphQL.AST.Directives]`
|
||||||
|
instead.
|
||||||
|
- `Language.GraphQL.AST.VariableDefinitions`. Use
|
||||||
|
`[Language.GraphQL.AST.VariableDefinition]` instead.
|
||||||
|
- `Language.GraphQL.AST.FragmentName`. Use `Language.GraphQL.AST.Name` instead.
|
||||||
|
- `Language.GraphQL.Execute.Schema` - It was a resolver list, not a schema.
|
||||||
|
- `Language.GraphQL.Schema`: `enum`, `enumA`, `wrappedEnum` and `wrappedEnumA`.
|
||||||
|
Use `scalar`, `scalarA`, `wrappedScalar` and `wrappedScalarA` instead.
|
||||||
|
|
||||||
|
|
||||||
|
## [0.5.1.0] - 2019-10-22
|
||||||
|
### Deprecated
|
||||||
|
- `Language.GraphQL.AST.Arguments`. Use `[Language.GraphQL.AST.Argument]`
|
||||||
|
instead.
|
||||||
|
- `Language.GraphQL.AST.Directives`. Use `[Language.GraphQL.AST.Directives]`
|
||||||
|
instead.
|
||||||
|
- `Language.GraphQL.AST.VariableDefinitions`. Use
|
||||||
|
`[Language.GraphQL.AST.VariableDefinition]` instead.
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Module documentation.
|
||||||
|
- Inline fragment support.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- Top-level fragments.
|
||||||
|
- Fragment for execution is chosen based on the type.
|
||||||
|
|
||||||
|
## [0.5.0.1] - 2019-09-10
|
||||||
|
### Added
|
||||||
|
- Minimal documentation for all public symbols.
|
||||||
|
|
||||||
|
### Deprecated
|
||||||
|
- `Language.GraphQL.AST.FragmentName`. Replaced with Language.GraphQL.AST.Name.
|
||||||
|
- `Language.GraphQL.Execute.Schema` - It is not a schema (at least not a
|
||||||
|
complete one), but a resolver list, and the resolvers should be provided by
|
||||||
|
the user separately, because the schema can originate from a GraphQL
|
||||||
|
document. `Schema` name should be free to provide a data type for the real
|
||||||
|
schema later.
|
||||||
|
- `Language.GraphQL.Schema`: `enum`, `enumA`, `wrappedEnum` and `wrappedEnumA`.
|
||||||
|
There are actually only two generic types in GraphQL: Scalars and objects.
|
||||||
|
Enum is a scalar value.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- Parsing block string values.
|
||||||
|
|
||||||
## [0.5.0.0] - 2019-08-14
|
## [0.5.0.0] - 2019-08-14
|
||||||
### Added
|
### Added
|
||||||
- `executeWithName` executes an operation with the given name.
|
- `executeWithName` executes an operation with the given name.
|
||||||
@ -70,6 +148,9 @@ All notable changes to this project will be documented in this file.
|
|||||||
### Added
|
### Added
|
||||||
- Data types for the GraphQL language.
|
- Data types for the GraphQL language.
|
||||||
|
|
||||||
|
[0.6.0.0]: https://github.com/caraus-ecms/graphql/compare/v0.5.1.0...v0.6.0.0
|
||||||
|
[0.5.1.0]: https://github.com/caraus-ecms/graphql/compare/v0.5.0.1...v0.5.1.0
|
||||||
|
[0.5.0.1]: https://github.com/caraus-ecms/graphql/compare/v0.5.0.0...v0.5.0.1
|
||||||
[0.5.0.0]: https://github.com/caraus-ecms/graphql/compare/v0.4.0.0...v0.5.0.0
|
[0.5.0.0]: https://github.com/caraus-ecms/graphql/compare/v0.4.0.0...v0.5.0.0
|
||||||
[0.4.0.0]: https://github.com/caraus-ecms/graphql/compare/v0.3...v0.4.0.0
|
[0.4.0.0]: https://github.com/caraus-ecms/graphql/compare/v0.3...v0.4.0.0
|
||||||
[0.3]: https://github.com/caraus-ecms/graphql/compare/v0.2.1...v0.3
|
[0.3]: https://github.com/caraus-ecms/graphql/compare/v0.2.1...v0.3
|
||||||
|
@ -8,8 +8,8 @@ GraphQL implementation in Haskell.
|
|||||||
|
|
||||||
This implementation is relatively low-level by design, it doesn't provide any
|
This implementation is relatively low-level by design, it doesn't provide any
|
||||||
mappings between the GraphQL types and Haskell's type system and avoids
|
mappings between the GraphQL types and Haskell's type system and avoids
|
||||||
compile-time magic. It focuses on flexibility instead instead, so other
|
compile-time magic. It focuses on flexibility instead, so other solutions can
|
||||||
solutions can be built on top of it.
|
be built on top of it.
|
||||||
|
|
||||||
## State of the work
|
## State of the work
|
||||||
|
|
||||||
|
@ -24,7 +24,6 @@ Since this file is a literate haskell file, we start by importing some dependenc
|
|||||||
> import Data.Time (getCurrentTime)
|
> import Data.Time (getCurrentTime)
|
||||||
>
|
>
|
||||||
> import Language.GraphQL
|
> import Language.GraphQL
|
||||||
> import Language.GraphQL.Schema (Schema)
|
|
||||||
> import qualified Language.GraphQL.Schema as Schema
|
> import qualified Language.GraphQL.Schema as Schema
|
||||||
> import Language.GraphQL.Trans (ActionT(..))
|
> import Language.GraphQL.Trans (ActionT(..))
|
||||||
>
|
>
|
||||||
@ -37,7 +36,7 @@ example from [graphql.js](https://github.com/graphql/graphql-js).
|
|||||||
|
|
||||||
First we build a GraphQL schema.
|
First we build a GraphQL schema.
|
||||||
|
|
||||||
> schema1 :: Schema IO
|
> schema1 :: NonEmpty (Schema.Resolver IO)
|
||||||
> schema1 = hello :| []
|
> schema1 = hello :| []
|
||||||
>
|
>
|
||||||
> hello :: Schema.Resolver IO
|
> hello :: Schema.Resolver IO
|
||||||
@ -67,7 +66,7 @@ returning
|
|||||||
|
|
||||||
For this example, we're going to be using time.
|
For this example, we're going to be using time.
|
||||||
|
|
||||||
> schema2 :: Schema IO
|
> schema2 :: NonEmpty (Schema.Resolver IO)
|
||||||
> schema2 = time :| []
|
> schema2 = time :| []
|
||||||
>
|
>
|
||||||
> time :: Schema.Resolver IO
|
> time :: Schema.Resolver IO
|
||||||
@ -127,7 +126,7 @@ This will fail
|
|||||||
|
|
||||||
Now that we have two resolvers, we can define a schema which uses them both.
|
Now that we have two resolvers, we can define a schema which uses them both.
|
||||||
|
|
||||||
> schema3 :: Schema IO
|
> schema3 :: NonEmpty (Schema.Resolver IO)
|
||||||
> schema3 = hello :| [time]
|
> schema3 = hello :| [time]
|
||||||
>
|
>
|
||||||
> query3 :: Text
|
> query3 :: Text
|
||||||
|
@ -1,91 +0,0 @@
|
|||||||
cabal-version: 1.12
|
|
||||||
|
|
||||||
-- This file has been generated from package.yaml by hpack version 0.31.2.
|
|
||||||
--
|
|
||||||
-- see: https://github.com/sol/hpack
|
|
||||||
--
|
|
||||||
-- hash: 6598c2424405b7a92a4672ad7d1a4e8ad768ea47bf3ed0c3c5ae51bac8730301
|
|
||||||
|
|
||||||
name: graphql
|
|
||||||
version: 0.5.0.0
|
|
||||||
synopsis: Haskell GraphQL implementation
|
|
||||||
description: This package provides a rudimentary parser for the <https://graphql.github.io/graphql-spec/June2018/ GraphQL> language.
|
|
||||||
category: Language
|
|
||||||
homepage: https://github.com/caraus-ecms/graphql#readme
|
|
||||||
bug-reports: https://github.com/caraus-ecms/graphql/issues
|
|
||||||
author: Danny Navarro <j@dannynavarro.net>,
|
|
||||||
Matthías Páll Gissurarson <mpg@mpg.is>,
|
|
||||||
Sólrún Halla Einarsdóttir <she@mpg.is>
|
|
||||||
maintainer: belka@caraus.de
|
|
||||||
copyright: (c) 2019 Eugen Wissner,
|
|
||||||
(c) 2015-2017 J. Daniel Navarro
|
|
||||||
license: BSD3
|
|
||||||
license-file: LICENSE
|
|
||||||
build-type: Simple
|
|
||||||
extra-source-files:
|
|
||||||
CHANGELOG.md
|
|
||||||
README.md
|
|
||||||
LICENSE
|
|
||||||
docs/tutorial/tutorial.lhs
|
|
||||||
data-files:
|
|
||||||
tests/data/kitchen-sink.graphql
|
|
||||||
tests/data/kitchen-sink.min.graphql
|
|
||||||
|
|
||||||
source-repository head
|
|
||||||
type: git
|
|
||||||
location: https://github.com/caraus-ecms/graphql
|
|
||||||
|
|
||||||
library
|
|
||||||
exposed-modules:
|
|
||||||
Language.GraphQL
|
|
||||||
Language.GraphQL.AST
|
|
||||||
Language.GraphQL.AST.Core
|
|
||||||
Language.GraphQL.AST.Transform
|
|
||||||
Language.GraphQL.Encoder
|
|
||||||
Language.GraphQL.Error
|
|
||||||
Language.GraphQL.Execute
|
|
||||||
Language.GraphQL.Lexer
|
|
||||||
Language.GraphQL.Parser
|
|
||||||
Language.GraphQL.Schema
|
|
||||||
Language.GraphQL.Trans
|
|
||||||
Language.GraphQL.Type
|
|
||||||
other-modules:
|
|
||||||
Paths_graphql
|
|
||||||
hs-source-dirs:
|
|
||||||
src
|
|
||||||
build-depends:
|
|
||||||
aeson
|
|
||||||
, base >=4.7 && <5
|
|
||||||
, megaparsec
|
|
||||||
, text
|
|
||||||
, transformers
|
|
||||||
, unordered-containers
|
|
||||||
default-language: Haskell2010
|
|
||||||
|
|
||||||
test-suite tasty
|
|
||||||
type: exitcode-stdio-1.0
|
|
||||||
main-is: Spec.hs
|
|
||||||
other-modules:
|
|
||||||
Language.GraphQL.EncoderSpec
|
|
||||||
Language.GraphQL.ErrorSpec
|
|
||||||
Language.GraphQL.LexerSpec
|
|
||||||
Language.GraphQL.ParserSpec
|
|
||||||
Test.KitchenSinkSpec
|
|
||||||
Test.StarWars.Data
|
|
||||||
Test.StarWars.QuerySpec
|
|
||||||
Test.StarWars.Schema
|
|
||||||
Paths_graphql
|
|
||||||
hs-source-dirs:
|
|
||||||
tests
|
|
||||||
ghc-options: -threaded -rtsopts -with-rtsopts=-N
|
|
||||||
build-depends:
|
|
||||||
aeson
|
|
||||||
, base >=4.7 && <5
|
|
||||||
, graphql
|
|
||||||
, hspec
|
|
||||||
, hspec-expectations
|
|
||||||
, megaparsec
|
|
||||||
, raw-strings-qq
|
|
||||||
, text
|
|
||||||
, transformers
|
|
||||||
default-language: Haskell2010
|
|
@ -1,5 +1,5 @@
|
|||||||
name: graphql
|
name: graphql
|
||||||
version: 0.5.0.0
|
version: 0.6.0.0
|
||||||
synopsis: Haskell GraphQL implementation
|
synopsis: Haskell GraphQL implementation
|
||||||
description:
|
description:
|
||||||
This package provides a rudimentary parser for the
|
This package provides a rudimentary parser for the
|
||||||
@ -28,14 +28,16 @@ data-files:
|
|||||||
dependencies:
|
dependencies:
|
||||||
- aeson
|
- aeson
|
||||||
- base >= 4.7 && < 5
|
- base >= 4.7 && < 5
|
||||||
|
- containers
|
||||||
- megaparsec
|
- megaparsec
|
||||||
- text
|
- text
|
||||||
- transformers
|
- transformers
|
||||||
|
- unordered-containers
|
||||||
|
|
||||||
library:
|
library:
|
||||||
source-dirs: src
|
source-dirs: src
|
||||||
dependencies:
|
other-modules:
|
||||||
- unordered-containers
|
- Language.GraphQL.AST.Transform
|
||||||
|
|
||||||
tests:
|
tests:
|
||||||
tasty:
|
tasty:
|
||||||
@ -49,4 +51,5 @@ tests:
|
|||||||
- graphql
|
- graphql
|
||||||
- hspec
|
- hspec
|
||||||
- hspec-expectations
|
- hspec-expectations
|
||||||
|
- hspec-megaparsec
|
||||||
- raw-strings-qq
|
- raw-strings-qq
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
|
|
||||||
STACK=$SEMAPHORE_CACHE_DIR/stack
|
STACK=$SEMAPHORE_CACHE_DIR/stack
|
||||||
|
export STACK_ROOT=$SEMAPHORE_CACHE_DIR/.stack
|
||||||
|
|
||||||
setup() {
|
setup() {
|
||||||
if [ ! -e "$STACK" ]
|
if [ ! -e "$STACK" ]
|
||||||
@ -19,7 +20,8 @@ test() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
test_docs() {
|
test_docs() {
|
||||||
$STACK --no-terminal ghc -- -Wall -fno-code docs/tutorial/tutorial.lhs
|
$STACK --no-terminal ghc -- -Wall -Werror -fno-code docs/tutorial/tutorial.lhs
|
||||||
|
$STACK --no-terminal haddock --no-haddock-deps
|
||||||
}
|
}
|
||||||
|
|
||||||
setup_lint() {
|
setup_lint() {
|
||||||
|
@ -5,32 +5,31 @@ module Language.GraphQL
|
|||||||
) where
|
) where
|
||||||
|
|
||||||
import Control.Monad.IO.Class (MonadIO)
|
import Control.Monad.IO.Class (MonadIO)
|
||||||
import qualified Data.Text as T
|
|
||||||
|
|
||||||
import qualified Data.Aeson as Aeson
|
import qualified Data.Aeson as Aeson
|
||||||
|
import Data.List.NonEmpty (NonEmpty)
|
||||||
|
import qualified Data.Text as T
|
||||||
|
import Language.GraphQL.Error
|
||||||
|
import Language.GraphQL.Execute
|
||||||
|
import Language.GraphQL.AST.Parser
|
||||||
|
import qualified Language.GraphQL.Schema as Schema
|
||||||
import Text.Megaparsec (parse)
|
import Text.Megaparsec (parse)
|
||||||
|
|
||||||
import Language.GraphQL.Execute
|
-- | If the text parses correctly as a @GraphQL@ query the query is
|
||||||
import Language.GraphQL.Parser
|
-- executed using the given 'Schema.Resolver's.
|
||||||
import Language.GraphQL.Schema
|
graphql :: MonadIO m
|
||||||
|
=> NonEmpty (Schema.Resolver m) -- ^ Resolvers.
|
||||||
import Language.GraphQL.Error
|
-> T.Text -- ^ Text representing a @GraphQL@ request document.
|
||||||
|
-> m Aeson.Value -- ^ Response.
|
||||||
-- | Takes a 'Schema' and text representing a @GraphQL@ request document.
|
|
||||||
-- If the text parses correctly as a @GraphQL@ query the query is
|
|
||||||
-- executed according to the given 'Schema'.
|
|
||||||
--
|
|
||||||
-- Returns the response as an @Aeson.@'Aeson.Value'.
|
|
||||||
graphql :: MonadIO m => Schema m -> T.Text -> m Aeson.Value
|
|
||||||
graphql = flip graphqlSubs $ const Nothing
|
graphql = flip graphqlSubs $ const Nothing
|
||||||
|
|
||||||
-- | Takes a 'Schema', a variable substitution function and text
|
-- | If the text parses correctly as a @GraphQL@ query the substitution is
|
||||||
-- representing a @GraphQL@ request document. If the text parses
|
-- applied to the query and the query is then executed using to the given
|
||||||
-- correctly as a @GraphQL@ query the substitution is applied to the
|
-- 'Schema.Resolver's.
|
||||||
-- query and the query is then executed according to the given 'Schema'.
|
graphqlSubs :: MonadIO m
|
||||||
--
|
=> NonEmpty (Schema.Resolver m) -- ^ Resolvers.
|
||||||
-- Returns the response as an @Aeson.@'Aeson.Value'.
|
-> Schema.Subs -- ^ Variable substitution function.
|
||||||
graphqlSubs :: MonadIO m => Schema m -> Subs -> T.Text -> m Aeson.Value
|
-> T.Text -- ^ Text representing a @GraphQL@ request document.
|
||||||
graphqlSubs schema f =
|
-> m Aeson.Value -- ^ Response.
|
||||||
either parseError (execute schema f)
|
graphqlSubs schema f
|
||||||
|
= either parseError (execute schema f)
|
||||||
. parse document ""
|
. parse document ""
|
||||||
|
@ -5,14 +5,11 @@
|
|||||||
module Language.GraphQL.AST
|
module Language.GraphQL.AST
|
||||||
( Alias
|
( Alias
|
||||||
, Argument(..)
|
, Argument(..)
|
||||||
, Arguments
|
|
||||||
, Definition(..)
|
, Definition(..)
|
||||||
, Directive(..)
|
, Directive(..)
|
||||||
, Directives
|
|
||||||
, Document
|
, Document
|
||||||
, Field(..)
|
, Field(..)
|
||||||
, FragmentDefinition(..)
|
, FragmentDefinition(..)
|
||||||
, FragmentName
|
|
||||||
, FragmentSpread(..)
|
, FragmentSpread(..)
|
||||||
, InlineFragment(..)
|
, InlineFragment(..)
|
||||||
, Name
|
, Name
|
||||||
@ -27,108 +24,162 @@ module Language.GraphQL.AST
|
|||||||
, TypeCondition
|
, TypeCondition
|
||||||
, Value(..)
|
, Value(..)
|
||||||
, VariableDefinition(..)
|
, VariableDefinition(..)
|
||||||
, VariableDefinitions
|
|
||||||
) where
|
) where
|
||||||
|
|
||||||
import Data.Int (Int32)
|
import Data.Int (Int32)
|
||||||
import Data.List.NonEmpty (NonEmpty)
|
import Data.List.NonEmpty (NonEmpty)
|
||||||
import Data.Text (Text)
|
import Data.Text (Text)
|
||||||
import Language.GraphQL.AST.Core ( Alias
|
|
||||||
, Name
|
|
||||||
)
|
|
||||||
|
|
||||||
-- * Document
|
-- * Document
|
||||||
|
|
||||||
|
-- | GraphQL document.
|
||||||
type Document = NonEmpty Definition
|
type Document = NonEmpty Definition
|
||||||
|
|
||||||
|
-- | Name
|
||||||
|
type Name = Text
|
||||||
|
|
||||||
|
-- | Directive.
|
||||||
|
data Directive = Directive Name [Argument] deriving (Eq, Show)
|
||||||
|
|
||||||
-- * Operations
|
-- * Operations
|
||||||
|
|
||||||
data Definition = DefinitionOperation OperationDefinition
|
-- | Top-level definition of a document, either an operation or a fragment.
|
||||||
|
data Definition
|
||||||
|
= DefinitionOperation OperationDefinition
|
||||||
| DefinitionFragment FragmentDefinition
|
| DefinitionFragment FragmentDefinition
|
||||||
deriving (Eq,Show)
|
deriving (Eq, Show)
|
||||||
|
|
||||||
data OperationDefinition = OperationSelectionSet SelectionSet
|
-- | Operation definition.
|
||||||
|
data OperationDefinition
|
||||||
|
= OperationSelectionSet SelectionSet
|
||||||
| OperationDefinition OperationType
|
| OperationDefinition OperationType
|
||||||
(Maybe Name)
|
(Maybe Name)
|
||||||
VariableDefinitions
|
[VariableDefinition]
|
||||||
Directives
|
[Directive]
|
||||||
SelectionSet
|
SelectionSet
|
||||||
deriving (Eq,Show)
|
deriving (Eq, Show)
|
||||||
|
|
||||||
data OperationType = Query | Mutation deriving (Eq,Show)
|
-- | GraphQL has 3 operation types: queries, mutations and subscribtions.
|
||||||
|
--
|
||||||
|
-- Currently only queries and mutations are supported.
|
||||||
|
data OperationType = Query | Mutation deriving (Eq, Show)
|
||||||
|
|
||||||
-- * SelectionSet
|
-- * Selections
|
||||||
|
|
||||||
|
-- | "Top-level" selection, selection on an operation or fragment.
|
||||||
type SelectionSet = NonEmpty Selection
|
type SelectionSet = NonEmpty Selection
|
||||||
|
|
||||||
|
-- | Field selection.
|
||||||
type SelectionSetOpt = [Selection]
|
type SelectionSetOpt = [Selection]
|
||||||
|
|
||||||
data Selection = SelectionField Field
|
-- | Single selection element.
|
||||||
|
data Selection
|
||||||
|
= SelectionField Field
|
||||||
| SelectionFragmentSpread FragmentSpread
|
| SelectionFragmentSpread FragmentSpread
|
||||||
| SelectionInlineFragment InlineFragment
|
| SelectionInlineFragment InlineFragment
|
||||||
deriving (Eq,Show)
|
deriving (Eq, Show)
|
||||||
|
|
||||||
-- * Field
|
-- * Field
|
||||||
|
|
||||||
data Field = Field (Maybe Alias) Name Arguments Directives SelectionSetOpt
|
-- | Single GraphQL field.
|
||||||
deriving (Eq,Show)
|
--
|
||||||
|
-- The only required property of a field is its name. Optionally it can also
|
||||||
|
-- have an alias, arguments or a list of subfields.
|
||||||
|
--
|
||||||
|
-- Given the following query:
|
||||||
|
--
|
||||||
|
-- @
|
||||||
|
-- {
|
||||||
|
-- zuck: user(id: 4) {
|
||||||
|
-- id
|
||||||
|
-- name
|
||||||
|
-- }
|
||||||
|
-- }
|
||||||
|
-- @
|
||||||
|
--
|
||||||
|
-- * "user", "id" and "name" are field names.
|
||||||
|
-- * "user" has two subfields, "id" and "name".
|
||||||
|
-- * "zuck" is an alias for "user". "id" and "name" have no aliases.
|
||||||
|
-- * "id: 4" is an argument for "user". "id" and "name" don't have any
|
||||||
|
-- arguments.
|
||||||
|
data Field
|
||||||
|
= Field (Maybe Alias) Name [Argument] [Directive] SelectionSetOpt
|
||||||
|
deriving (Eq, Show)
|
||||||
|
|
||||||
-- * Arguments
|
-- | Alternative field name.
|
||||||
|
--
|
||||||
type Arguments = [Argument]
|
-- @
|
||||||
|
-- {
|
||||||
|
-- smallPic: profilePic(size: 64)
|
||||||
|
-- bigPic: profilePic(size: 1024)
|
||||||
|
-- }
|
||||||
|
-- @
|
||||||
|
--
|
||||||
|
-- Here "smallPic" and "bigPic" are aliases for the same field, "profilePic",
|
||||||
|
-- used to distinquish between profile pictures with different arguments
|
||||||
|
-- (sizes).
|
||||||
|
type Alias = Name
|
||||||
|
|
||||||
|
-- | Single argument.
|
||||||
|
--
|
||||||
|
-- @
|
||||||
|
-- {
|
||||||
|
-- user(id: 4) {
|
||||||
|
-- name
|
||||||
|
-- }
|
||||||
|
-- }
|
||||||
|
-- @
|
||||||
|
--
|
||||||
|
-- Here "id" is an argument for the field "user" and its value is 4.
|
||||||
data Argument = Argument Name Value deriving (Eq,Show)
|
data Argument = Argument Name Value deriving (Eq,Show)
|
||||||
|
|
||||||
-- * Fragments
|
-- * Fragments
|
||||||
|
|
||||||
data FragmentSpread = FragmentSpread Name Directives deriving (Eq,Show)
|
-- | Fragment spread.
|
||||||
|
data FragmentSpread = FragmentSpread Name [Directive] deriving (Eq, Show)
|
||||||
|
|
||||||
data InlineFragment = InlineFragment (Maybe TypeCondition) Directives SelectionSet
|
-- | Inline fragment.
|
||||||
deriving (Eq,Show)
|
data InlineFragment = InlineFragment (Maybe TypeCondition) [Directive] SelectionSet
|
||||||
|
|
||||||
data FragmentDefinition =
|
|
||||||
FragmentDefinition FragmentName TypeCondition Directives SelectionSet
|
|
||||||
deriving (Eq,Show)
|
|
||||||
|
|
||||||
type FragmentName = Name
|
|
||||||
|
|
||||||
type TypeCondition = Name
|
|
||||||
|
|
||||||
-- * Input values
|
|
||||||
|
|
||||||
data Value = ValueVariable Name
|
|
||||||
| ValueInt Int32
|
|
||||||
| ValueFloat Double
|
|
||||||
| ValueString Text
|
|
||||||
| ValueBoolean Bool
|
|
||||||
| ValueNull
|
|
||||||
| ValueEnum Name
|
|
||||||
| ValueList [Value]
|
|
||||||
| ValueObject [ObjectField]
|
|
||||||
deriving (Eq, Show)
|
deriving (Eq, Show)
|
||||||
|
|
||||||
|
-- | Fragment definition.
|
||||||
|
data FragmentDefinition
|
||||||
|
= FragmentDefinition Name TypeCondition [Directive] SelectionSet
|
||||||
|
deriving (Eq, Show)
|
||||||
|
|
||||||
|
-- * Inputs
|
||||||
|
|
||||||
|
-- | Input value.
|
||||||
|
data Value = Variable Name
|
||||||
|
| Int Int32
|
||||||
|
| Float Double
|
||||||
|
| String Text
|
||||||
|
| Boolean Bool
|
||||||
|
| Null
|
||||||
|
| Enum Name
|
||||||
|
| List [Value]
|
||||||
|
| Object [ObjectField]
|
||||||
|
deriving (Eq, Show)
|
||||||
|
|
||||||
|
-- | Key-value pair.
|
||||||
|
--
|
||||||
|
-- A list of 'ObjectField's represents a GraphQL object type.
|
||||||
data ObjectField = ObjectField Name Value deriving (Eq, Show)
|
data ObjectField = ObjectField Name Value deriving (Eq, Show)
|
||||||
|
|
||||||
-- * Variables
|
-- | Variable definition.
|
||||||
|
|
||||||
type VariableDefinitions = [VariableDefinition]
|
|
||||||
|
|
||||||
data VariableDefinition = VariableDefinition Name Type (Maybe Value)
|
data VariableDefinition = VariableDefinition Name Type (Maybe Value)
|
||||||
deriving (Eq,Show)
|
deriving (Eq, Show)
|
||||||
|
|
||||||
-- * Input types
|
-- | Type condition.
|
||||||
|
type TypeCondition = Name
|
||||||
|
|
||||||
|
-- | Type representation.
|
||||||
data Type = TypeNamed Name
|
data Type = TypeNamed Name
|
||||||
| TypeList Type
|
| TypeList Type
|
||||||
| TypeNonNull NonNullType
|
| TypeNonNull NonNullType
|
||||||
deriving (Eq,Show)
|
deriving (Eq, Show)
|
||||||
|
|
||||||
|
-- | Helper type to represent Non-Null types and lists of such types.
|
||||||
data NonNullType = NonNullTypeNamed Name
|
data NonNullType = NonNullTypeNamed Name
|
||||||
| NonNullTypeList Type
|
| NonNullTypeList Type
|
||||||
deriving (Eq,Show)
|
deriving (Eq, Show)
|
||||||
|
|
||||||
-- * Directives
|
|
||||||
|
|
||||||
type Directives = [Directive]
|
|
||||||
|
|
||||||
data Directive = Directive Name [Argument] deriving (Eq,Show)
|
|
||||||
|
@ -4,45 +4,63 @@ module Language.GraphQL.AST.Core
|
|||||||
, Argument(..)
|
, Argument(..)
|
||||||
, Document
|
, Document
|
||||||
, Field(..)
|
, Field(..)
|
||||||
|
, Fragment(..)
|
||||||
, Name
|
, Name
|
||||||
, ObjectField(..)
|
|
||||||
, Operation(..)
|
, Operation(..)
|
||||||
|
, Selection(..)
|
||||||
|
, TypeCondition
|
||||||
, Value(..)
|
, Value(..)
|
||||||
) where
|
) where
|
||||||
|
|
||||||
import Data.Int (Int32)
|
import Data.Int (Int32)
|
||||||
|
import Data.HashMap.Strict (HashMap)
|
||||||
import Data.List.NonEmpty (NonEmpty)
|
import Data.List.NonEmpty (NonEmpty)
|
||||||
import Data.String
|
import Data.Sequence (Seq)
|
||||||
|
import Data.String (IsString(..))
|
||||||
import Data.Text (Text)
|
import Data.Text (Text)
|
||||||
|
import Language.GraphQL.AST (Alias, Name, TypeCondition)
|
||||||
|
|
||||||
-- | Name
|
-- | GraphQL document is a non-empty list of operations.
|
||||||
type Name = Text
|
|
||||||
|
|
||||||
type Document = NonEmpty Operation
|
type Document = NonEmpty Operation
|
||||||
|
|
||||||
data Operation = Query (Maybe Text) (NonEmpty Field)
|
-- | GraphQL has 3 operation types: queries, mutations and subscribtions.
|
||||||
| Mutation (Maybe Text) (NonEmpty Field)
|
--
|
||||||
deriving (Eq,Show)
|
-- Currently only queries and mutations are supported.
|
||||||
|
data Operation
|
||||||
|
= Query (Maybe Text) (Seq Selection)
|
||||||
|
| Mutation (Maybe Text) (Seq Selection)
|
||||||
|
deriving (Eq, Show)
|
||||||
|
|
||||||
data Field = Field (Maybe Alias) Name [Argument] [Field] deriving (Eq,Show)
|
-- | Single GraphQL field.
|
||||||
|
data Field
|
||||||
|
= Field (Maybe Alias) Name [Argument] (Seq Selection)
|
||||||
|
deriving (Eq, Show)
|
||||||
|
|
||||||
type Alias = Name
|
-- | Single argument.
|
||||||
|
data Argument = Argument Name Value deriving (Eq, Show)
|
||||||
|
|
||||||
data Argument = Argument Name Value deriving (Eq,Show)
|
-- | Represents fragments and inline fragments.
|
||||||
|
data Fragment
|
||||||
|
= Fragment TypeCondition (Seq Selection)
|
||||||
|
deriving (Eq, Show)
|
||||||
|
|
||||||
data Value = ValueInt Int32
|
-- | Single selection element.
|
||||||
-- GraphQL Float is double precision
|
data Selection
|
||||||
| ValueFloat Double
|
= SelectionFragment Fragment
|
||||||
| ValueString Text
|
| SelectionField Field
|
||||||
| ValueBoolean Bool
|
deriving (Eq, Show)
|
||||||
| ValueNull
|
|
||||||
| ValueEnum Name
|
-- | Represents accordingly typed GraphQL values.
|
||||||
| ValueList [Value]
|
data Value
|
||||||
| ValueObject [ObjectField]
|
= Int Int32
|
||||||
deriving (Eq,Show)
|
| Float Double -- ^ GraphQL Float is double precision
|
||||||
|
| String Text
|
||||||
|
| Boolean Bool
|
||||||
|
| Null
|
||||||
|
| Enum Name
|
||||||
|
| List [Value]
|
||||||
|
| Object (HashMap Name Value)
|
||||||
|
deriving (Eq, Show)
|
||||||
|
|
||||||
instance IsString Value where
|
instance IsString Value where
|
||||||
fromString = ValueString . fromString
|
fromString = String . fromString
|
||||||
|
|
||||||
data ObjectField = ObjectField Name Value deriving (Eq,Show)
|
|
||||||
|
@ -2,7 +2,7 @@
|
|||||||
{-# LANGUAGE ExplicitForAll #-}
|
{-# LANGUAGE ExplicitForAll #-}
|
||||||
|
|
||||||
-- | This module defines a minifier and a printer for the @GraphQL@ language.
|
-- | This module defines a minifier and a printer for the @GraphQL@ language.
|
||||||
module Language.GraphQL.Encoder
|
module Language.GraphQL.AST.Encoder
|
||||||
( Formatter
|
( Formatter
|
||||||
, definition
|
, definition
|
||||||
, directive
|
, directive
|
||||||
@ -21,56 +21,56 @@ import qualified Data.Text.Lazy as Text.Lazy
|
|||||||
import Data.Text.Lazy.Builder (toLazyText)
|
import Data.Text.Lazy.Builder (toLazyText)
|
||||||
import Data.Text.Lazy.Builder.Int (decimal)
|
import Data.Text.Lazy.Builder.Int (decimal)
|
||||||
import Data.Text.Lazy.Builder.RealFloat (realFloat)
|
import Data.Text.Lazy.Builder.RealFloat (realFloat)
|
||||||
import Language.GraphQL.AST
|
import qualified Language.GraphQL.AST as Full
|
||||||
|
|
||||||
-- | Instructs the encoder whether a GraphQL should be minified or pretty
|
-- | Instructs the encoder whether the GraphQL document should be minified or
|
||||||
-- printed.
|
-- pretty printed.
|
||||||
--
|
--
|
||||||
-- Use 'pretty' and 'minified' to construct the formatter.
|
-- Use 'pretty' or 'minified' to construct the formatter.
|
||||||
data Formatter
|
data Formatter
|
||||||
= Minified
|
= Minified
|
||||||
| Pretty Word
|
| Pretty Word
|
||||||
|
|
||||||
-- Constructs a formatter for pretty printing.
|
-- | Constructs a formatter for pretty printing.
|
||||||
pretty :: Formatter
|
pretty :: Formatter
|
||||||
pretty = Pretty 0
|
pretty = Pretty 0
|
||||||
|
|
||||||
-- Constructs a formatter for minifying.
|
-- | Constructs a formatter for minifying.
|
||||||
minified :: Formatter
|
minified :: Formatter
|
||||||
minified = Minified
|
minified = Minified
|
||||||
|
|
||||||
-- | Converts a 'Document' into a string.
|
-- | Converts a 'Full.Document' into a string.
|
||||||
document :: Formatter -> Document -> Text
|
document :: Formatter -> Full.Document -> Text
|
||||||
document formatter defs
|
document formatter defs
|
||||||
| Pretty _ <- formatter = Text.Lazy.intercalate "\n" encodeDocument
|
| Pretty _ <- formatter = Text.Lazy.intercalate "\n" encodeDocument
|
||||||
| Minified <-formatter = Text.Lazy.snoc (mconcat encodeDocument) '\n'
|
| Minified <-formatter = Text.Lazy.snoc (mconcat encodeDocument) '\n'
|
||||||
where
|
where
|
||||||
encodeDocument = NonEmpty.toList $ definition formatter <$> defs
|
encodeDocument = NonEmpty.toList $ definition formatter <$> defs
|
||||||
|
|
||||||
-- | Converts a 'Definition' into a string.
|
-- | Converts a 'Full.Definition' into a string.
|
||||||
definition :: Formatter -> Definition -> Text
|
definition :: Formatter -> Full.Definition -> Text
|
||||||
definition formatter x
|
definition formatter x
|
||||||
| Pretty _ <- formatter = Text.Lazy.snoc (encodeDefinition x) '\n'
|
| Pretty _ <- formatter = Text.Lazy.snoc (encodeDefinition x) '\n'
|
||||||
| Minified <- formatter = encodeDefinition x
|
| Minified <- formatter = encodeDefinition x
|
||||||
where
|
where
|
||||||
encodeDefinition (DefinitionOperation operation)
|
encodeDefinition (Full.DefinitionOperation operation)
|
||||||
= operationDefinition formatter operation
|
= operationDefinition formatter operation
|
||||||
encodeDefinition (DefinitionFragment fragment)
|
encodeDefinition (Full.DefinitionFragment fragment)
|
||||||
= fragmentDefinition formatter fragment
|
= fragmentDefinition formatter fragment
|
||||||
|
|
||||||
operationDefinition :: Formatter -> OperationDefinition -> Text
|
operationDefinition :: Formatter -> Full.OperationDefinition -> Text
|
||||||
operationDefinition formatter (OperationSelectionSet sels)
|
operationDefinition formatter (Full.OperationSelectionSet sels)
|
||||||
= selectionSet formatter sels
|
= selectionSet formatter sels
|
||||||
operationDefinition formatter (OperationDefinition Query name vars dirs sels)
|
operationDefinition formatter (Full.OperationDefinition Full.Query name vars dirs sels)
|
||||||
= "query " <> node formatter name vars dirs sels
|
= "query " <> node formatter name vars dirs sels
|
||||||
operationDefinition formatter (OperationDefinition Mutation name vars dirs sels)
|
operationDefinition formatter (Full.OperationDefinition Full.Mutation name vars dirs sels)
|
||||||
= "mutation " <> node formatter name vars dirs sels
|
= "mutation " <> node formatter name vars dirs sels
|
||||||
|
|
||||||
node :: Formatter
|
node :: Formatter
|
||||||
-> Maybe Name
|
-> Maybe Full.Name
|
||||||
-> VariableDefinitions
|
-> [Full.VariableDefinition]
|
||||||
-> Directives
|
-> [Full.Directive]
|
||||||
-> SelectionSet
|
-> Full.SelectionSet
|
||||||
-> Text
|
-> Text
|
||||||
node formatter name vars dirs sels
|
node formatter name vars dirs sels
|
||||||
= Text.Lazy.fromStrict (fold name)
|
= Text.Lazy.fromStrict (fold name)
|
||||||
@ -79,39 +79,39 @@ node formatter name vars dirs sels
|
|||||||
<> eitherFormat formatter " " mempty
|
<> eitherFormat formatter " " mempty
|
||||||
<> selectionSet formatter sels
|
<> selectionSet formatter sels
|
||||||
|
|
||||||
variableDefinitions :: Formatter -> [VariableDefinition] -> Text
|
variableDefinitions :: Formatter -> [Full.VariableDefinition] -> Text
|
||||||
variableDefinitions formatter
|
variableDefinitions formatter
|
||||||
= parensCommas formatter $ variableDefinition formatter
|
= parensCommas formatter $ variableDefinition formatter
|
||||||
|
|
||||||
variableDefinition :: Formatter -> VariableDefinition -> Text
|
variableDefinition :: Formatter -> Full.VariableDefinition -> Text
|
||||||
variableDefinition formatter (VariableDefinition var ty dv)
|
variableDefinition formatter (Full.VariableDefinition var ty dv)
|
||||||
= variable var
|
= variable var
|
||||||
<> eitherFormat formatter ": " ":"
|
<> eitherFormat formatter ": " ":"
|
||||||
<> type' ty
|
<> type' ty
|
||||||
<> maybe mempty (defaultValue formatter) dv
|
<> maybe mempty (defaultValue formatter) dv
|
||||||
|
|
||||||
defaultValue :: Formatter -> Value -> Text
|
defaultValue :: Formatter -> Full.Value -> Text
|
||||||
defaultValue formatter val
|
defaultValue formatter val
|
||||||
= eitherFormat formatter " = " "="
|
= eitherFormat formatter " = " "="
|
||||||
<> value formatter val
|
<> value formatter val
|
||||||
|
|
||||||
variable :: Name -> Text
|
variable :: Full.Name -> Text
|
||||||
variable var = "$" <> Text.Lazy.fromStrict var
|
variable var = "$" <> Text.Lazy.fromStrict var
|
||||||
|
|
||||||
selectionSet :: Formatter -> SelectionSet -> Text
|
selectionSet :: Formatter -> Full.SelectionSet -> Text
|
||||||
selectionSet formatter
|
selectionSet formatter
|
||||||
= bracesList formatter (selection formatter)
|
= bracesList formatter (selection formatter)
|
||||||
. NonEmpty.toList
|
. NonEmpty.toList
|
||||||
|
|
||||||
selectionSetOpt :: Formatter -> SelectionSetOpt -> Text
|
selectionSetOpt :: Formatter -> Full.SelectionSetOpt -> Text
|
||||||
selectionSetOpt formatter = bracesList formatter $ selection formatter
|
selectionSetOpt formatter = bracesList formatter $ selection formatter
|
||||||
|
|
||||||
selection :: Formatter -> Selection -> Text
|
selection :: Formatter -> Full.Selection -> Text
|
||||||
selection formatter = Text.Lazy.append indent . f
|
selection formatter = Text.Lazy.append indent . f
|
||||||
where
|
where
|
||||||
f (SelectionField x) = field incrementIndent x
|
f (Full.SelectionField x) = field incrementIndent x
|
||||||
f (SelectionInlineFragment x) = inlineFragment incrementIndent x
|
f (Full.SelectionInlineFragment x) = inlineFragment incrementIndent x
|
||||||
f (SelectionFragmentSpread x) = fragmentSpread incrementIndent x
|
f (Full.SelectionFragmentSpread x) = fragmentSpread incrementIndent x
|
||||||
incrementIndent
|
incrementIndent
|
||||||
| Pretty n <- formatter = Pretty $ n + 1
|
| Pretty n <- formatter = Pretty $ n + 1
|
||||||
| otherwise = Minified
|
| otherwise = Minified
|
||||||
@ -119,8 +119,8 @@ selection formatter = Text.Lazy.append indent . f
|
|||||||
| Pretty n <- formatter = Text.Lazy.replicate (fromIntegral $ n + 1) " "
|
| Pretty n <- formatter = Text.Lazy.replicate (fromIntegral $ n + 1) " "
|
||||||
| otherwise = mempty
|
| otherwise = mempty
|
||||||
|
|
||||||
field :: Formatter -> Field -> Text
|
field :: Formatter -> Full.Field -> Text
|
||||||
field formatter (Field alias name args dirs selso)
|
field formatter (Full.Field alias name args dirs selso)
|
||||||
= optempty (`Text.Lazy.append` colon) (Text.Lazy.fromStrict $ fold alias)
|
= optempty (`Text.Lazy.append` colon) (Text.Lazy.fromStrict $ fold alias)
|
||||||
<> Text.Lazy.fromStrict name
|
<> Text.Lazy.fromStrict name
|
||||||
<> optempty (arguments formatter) args
|
<> optempty (arguments formatter) args
|
||||||
@ -132,31 +132,31 @@ field formatter (Field alias name args dirs selso)
|
|||||||
| null selso = mempty
|
| null selso = mempty
|
||||||
| otherwise = eitherFormat formatter " " mempty <> selectionSetOpt formatter selso
|
| otherwise = eitherFormat formatter " " mempty <> selectionSetOpt formatter selso
|
||||||
|
|
||||||
arguments :: Formatter -> [Argument] -> Text
|
arguments :: Formatter -> [Full.Argument] -> Text
|
||||||
arguments formatter = parensCommas formatter $ argument formatter
|
arguments formatter = parensCommas formatter $ argument formatter
|
||||||
|
|
||||||
argument :: Formatter -> Argument -> Text
|
argument :: Formatter -> Full.Argument -> Text
|
||||||
argument formatter (Argument name v)
|
argument formatter (Full.Argument name v)
|
||||||
= Text.Lazy.fromStrict name
|
= Text.Lazy.fromStrict name
|
||||||
<> eitherFormat formatter ": " ":"
|
<> eitherFormat formatter ": " ":"
|
||||||
<> value formatter v
|
<> value formatter v
|
||||||
|
|
||||||
-- * Fragments
|
-- * Fragments
|
||||||
|
|
||||||
fragmentSpread :: Formatter -> FragmentSpread -> Text
|
fragmentSpread :: Formatter -> Full.FragmentSpread -> Text
|
||||||
fragmentSpread formatter (FragmentSpread name ds)
|
fragmentSpread formatter (Full.FragmentSpread name ds)
|
||||||
= "..." <> Text.Lazy.fromStrict name <> optempty (directives formatter) ds
|
= "..." <> Text.Lazy.fromStrict name <> optempty (directives formatter) ds
|
||||||
|
|
||||||
inlineFragment :: Formatter -> InlineFragment -> Text
|
inlineFragment :: Formatter -> Full.InlineFragment -> Text
|
||||||
inlineFragment formatter (InlineFragment tc dirs sels)
|
inlineFragment formatter (Full.InlineFragment tc dirs sels)
|
||||||
= "... on "
|
= "... on "
|
||||||
<> Text.Lazy.fromStrict (fold tc)
|
<> Text.Lazy.fromStrict (fold tc)
|
||||||
<> directives formatter dirs
|
<> directives formatter dirs
|
||||||
<> eitherFormat formatter " " mempty
|
<> eitherFormat formatter " " mempty
|
||||||
<> selectionSet formatter sels
|
<> selectionSet formatter sels
|
||||||
|
|
||||||
fragmentDefinition :: Formatter -> FragmentDefinition -> Text
|
fragmentDefinition :: Formatter -> Full.FragmentDefinition -> Text
|
||||||
fragmentDefinition formatter (FragmentDefinition name tc dirs sels)
|
fragmentDefinition formatter (Full.FragmentDefinition name tc dirs sels)
|
||||||
= "fragment " <> Text.Lazy.fromStrict name
|
= "fragment " <> Text.Lazy.fromStrict name
|
||||||
<> " on " <> Text.Lazy.fromStrict tc
|
<> " on " <> Text.Lazy.fromStrict tc
|
||||||
<> optempty (directives formatter) dirs
|
<> optempty (directives formatter) dirs
|
||||||
@ -165,26 +165,26 @@ fragmentDefinition formatter (FragmentDefinition name tc dirs sels)
|
|||||||
|
|
||||||
-- * Miscellaneous
|
-- * Miscellaneous
|
||||||
|
|
||||||
-- | Converts a 'Directive' into a string.
|
-- | Converts a 'Full.Directive' into a string.
|
||||||
directive :: Formatter -> Directive -> Text
|
directive :: Formatter -> Full.Directive -> Text
|
||||||
directive formatter (Directive name args)
|
directive formatter (Full.Directive name args)
|
||||||
= "@" <> Text.Lazy.fromStrict name <> optempty (arguments formatter) args
|
= "@" <> Text.Lazy.fromStrict name <> optempty (arguments formatter) args
|
||||||
|
|
||||||
directives :: Formatter -> Directives -> Text
|
directives :: Formatter -> [Full.Directive] -> Text
|
||||||
directives formatter@(Pretty _) = Text.Lazy.cons ' ' . spaces (directive formatter)
|
directives formatter@(Pretty _) = Text.Lazy.cons ' ' . spaces (directive formatter)
|
||||||
directives Minified = spaces (directive Minified)
|
directives Minified = spaces (directive Minified)
|
||||||
|
|
||||||
-- | Converts a 'Value' into a string.
|
-- | Converts a 'Full.Value' into a string.
|
||||||
value :: Formatter -> Value -> Text
|
value :: Formatter -> Full.Value -> Text
|
||||||
value _ (ValueVariable x) = variable x
|
value _ (Full.Variable x) = variable x
|
||||||
value _ (ValueInt x) = toLazyText $ decimal x
|
value _ (Full.Int x) = toLazyText $ decimal x
|
||||||
value _ (ValueFloat x) = toLazyText $ realFloat x
|
value _ (Full.Float x) = toLazyText $ realFloat x
|
||||||
value _ (ValueBoolean x) = booleanValue x
|
value _ (Full.Boolean x) = booleanValue x
|
||||||
value _ ValueNull = mempty
|
value _ Full.Null = mempty
|
||||||
value _ (ValueString x) = stringValue $ Text.Lazy.fromStrict x
|
value _ (Full.String x) = stringValue $ Text.Lazy.fromStrict x
|
||||||
value _ (ValueEnum x) = Text.Lazy.fromStrict x
|
value _ (Full.Enum x) = Text.Lazy.fromStrict x
|
||||||
value formatter (ValueList x) = listValue formatter x
|
value formatter (Full.List x) = listValue formatter x
|
||||||
value formatter (ValueObject x) = objectValue formatter x
|
value formatter (Full.Object x) = objectValue formatter x
|
||||||
|
|
||||||
booleanValue :: Bool -> Text
|
booleanValue :: Bool -> Text
|
||||||
booleanValue True = "true"
|
booleanValue True = "true"
|
||||||
@ -196,10 +196,10 @@ stringValue
|
|||||||
. Text.Lazy.replace "\"" "\\\""
|
. Text.Lazy.replace "\"" "\\\""
|
||||||
. Text.Lazy.replace "\\" "\\\\"
|
. Text.Lazy.replace "\\" "\\\\"
|
||||||
|
|
||||||
listValue :: Formatter -> [Value] -> Text
|
listValue :: Formatter -> [Full.Value] -> Text
|
||||||
listValue formatter = bracketsCommas formatter $ value formatter
|
listValue formatter = bracketsCommas formatter $ value formatter
|
||||||
|
|
||||||
objectValue :: Formatter -> [ObjectField] -> Text
|
objectValue :: Formatter -> [Full.ObjectField] -> Text
|
||||||
objectValue formatter = intercalate $ objectField formatter
|
objectValue formatter = intercalate $ objectField formatter
|
||||||
where
|
where
|
||||||
intercalate f
|
intercalate f
|
||||||
@ -208,26 +208,26 @@ objectValue formatter = intercalate $ objectField formatter
|
|||||||
. fmap f
|
. fmap f
|
||||||
|
|
||||||
|
|
||||||
objectField :: Formatter -> ObjectField -> Text
|
objectField :: Formatter -> Full.ObjectField -> Text
|
||||||
objectField formatter (ObjectField name v)
|
objectField formatter (Full.ObjectField name v)
|
||||||
= Text.Lazy.fromStrict name <> colon <> value formatter v
|
= Text.Lazy.fromStrict name <> colon <> value formatter v
|
||||||
where
|
where
|
||||||
colon
|
colon
|
||||||
| Pretty _ <- formatter = ": "
|
| Pretty _ <- formatter = ": "
|
||||||
| Minified <- formatter = ":"
|
| Minified <- formatter = ":"
|
||||||
|
|
||||||
-- | Converts a 'Type' a type into a string.
|
-- | Converts a 'Full.Type' a type into a string.
|
||||||
type' :: Type -> Text
|
type' :: Full.Type -> Text
|
||||||
type' (TypeNamed x) = Text.Lazy.fromStrict x
|
type' (Full.TypeNamed x) = Text.Lazy.fromStrict x
|
||||||
type' (TypeList x) = listType x
|
type' (Full.TypeList x) = listType x
|
||||||
type' (TypeNonNull x) = nonNullType x
|
type' (Full.TypeNonNull x) = nonNullType x
|
||||||
|
|
||||||
listType :: Type -> Text
|
listType :: Full.Type -> Text
|
||||||
listType x = brackets (type' x)
|
listType x = brackets (type' x)
|
||||||
|
|
||||||
nonNullType :: NonNullType -> Text
|
nonNullType :: Full.NonNullType -> Text
|
||||||
nonNullType (NonNullTypeNamed x) = Text.Lazy.fromStrict x <> "!"
|
nonNullType (Full.NonNullTypeNamed x) = Text.Lazy.fromStrict x <> "!"
|
||||||
nonNullType (NonNullTypeList x) = listType x <> "!"
|
nonNullType (Full.NonNullTypeList x) = listType x <> "!"
|
||||||
|
|
||||||
-- * Internal
|
-- * Internal
|
||||||
|
|
@ -3,7 +3,7 @@
|
|||||||
|
|
||||||
-- | This module defines a bunch of small parsers used to parse individual
|
-- | This module defines a bunch of small parsers used to parse individual
|
||||||
-- lexemes.
|
-- lexemes.
|
||||||
module Language.GraphQL.Lexer
|
module Language.GraphQL.AST.Lexer
|
||||||
( Parser
|
( Parser
|
||||||
, amp
|
, amp
|
||||||
, at
|
, at
|
||||||
@ -71,6 +71,8 @@ type Parser = Parsec Void T.Text
|
|||||||
ignoredCharacters :: Parser ()
|
ignoredCharacters :: Parser ()
|
||||||
ignoredCharacters = space1 <|> skipSome (char ',')
|
ignoredCharacters = space1 <|> skipSome (char ',')
|
||||||
|
|
||||||
|
-- | Parser that skips comments and meaningless characters, whitespaces and
|
||||||
|
-- commas.
|
||||||
spaceConsumer :: Parser ()
|
spaceConsumer :: Parser ()
|
||||||
spaceConsumer = Lexer.space ignoredCharacters comment empty
|
spaceConsumer = Lexer.space ignoredCharacters comment empty
|
||||||
|
|
||||||
@ -87,12 +89,12 @@ symbol :: T.Text -> Parser T.Text
|
|||||||
symbol = Lexer.symbol spaceConsumer
|
symbol = Lexer.symbol spaceConsumer
|
||||||
|
|
||||||
-- | Parser for "!".
|
-- | Parser for "!".
|
||||||
bang :: Parser Char
|
bang :: Parser T.Text
|
||||||
bang = char '!'
|
bang = symbol "!"
|
||||||
|
|
||||||
-- | Parser for "$".
|
-- | Parser for "$".
|
||||||
dollar :: Parser Char
|
dollar :: Parser T.Text
|
||||||
dollar = char '$'
|
dollar = symbol "$"
|
||||||
|
|
||||||
-- | Parser for "@".
|
-- | Parser for "@".
|
||||||
at :: Parser Char
|
at :: Parser Char
|
@ -1,6 +1,8 @@
|
|||||||
{-# LANGUAGE LambdaCase #-}
|
{-# LANGUAGE LambdaCase #-}
|
||||||
{-# LANGUAGE OverloadedStrings #-}
|
{-# LANGUAGE OverloadedStrings #-}
|
||||||
module Language.GraphQL.Parser
|
|
||||||
|
-- | @GraphQL@ document parser.
|
||||||
|
module Language.GraphQL.AST.Parser
|
||||||
( document
|
( document
|
||||||
) where
|
) where
|
||||||
|
|
||||||
@ -9,13 +11,14 @@ import Control.Applicative ( Alternative(..)
|
|||||||
)
|
)
|
||||||
import Data.List.NonEmpty (NonEmpty(..))
|
import Data.List.NonEmpty (NonEmpty(..))
|
||||||
import Language.GraphQL.AST
|
import Language.GraphQL.AST
|
||||||
import Language.GraphQL.Lexer
|
import Language.GraphQL.AST.Lexer
|
||||||
import Text.Megaparsec ( lookAhead
|
import Text.Megaparsec ( lookAhead
|
||||||
, option
|
, option
|
||||||
, try
|
, try
|
||||||
, (<?>)
|
, (<?>)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
-- | Parser for the GraphQL documents.
|
||||||
document :: Parser Document
|
document :: Parser Document
|
||||||
document = unicodeBOM >> spaceConsumer >> lexeme (manyNE definition)
|
document = unicodeBOM >> spaceConsumer >> lexeme (manyNE definition)
|
||||||
|
|
||||||
@ -66,7 +69,7 @@ alias = try $ name <* colon
|
|||||||
|
|
||||||
-- * Arguments
|
-- * Arguments
|
||||||
|
|
||||||
arguments :: Parser Arguments
|
arguments :: Parser [Argument]
|
||||||
arguments = parens $ some argument
|
arguments = parens $ some argument
|
||||||
|
|
||||||
argument :: Parser Argument
|
argument :: Parser Argument
|
||||||
@ -93,7 +96,7 @@ fragmentDefinition = FragmentDefinition
|
|||||||
<*> opt directives
|
<*> opt directives
|
||||||
<*> selectionSet
|
<*> selectionSet
|
||||||
|
|
||||||
fragmentName :: Parser FragmentName
|
fragmentName :: Parser Name
|
||||||
fragmentName = but (symbol "on") *> name
|
fragmentName = but (symbol "on") *> name
|
||||||
|
|
||||||
typeCondition :: Parser TypeCondition
|
typeCondition :: Parser TypeCondition
|
||||||
@ -102,16 +105,16 @@ typeCondition = symbol "on" *> name
|
|||||||
-- * Input Values
|
-- * Input Values
|
||||||
|
|
||||||
value :: Parser Value
|
value :: Parser Value
|
||||||
value = ValueVariable <$> variable
|
value = Variable <$> variable
|
||||||
<|> ValueFloat <$> try float
|
<|> Float <$> try float
|
||||||
<|> ValueInt <$> integer
|
<|> Int <$> integer
|
||||||
<|> ValueBoolean <$> booleanValue
|
<|> Boolean <$> booleanValue
|
||||||
<|> ValueNull <$ symbol "null"
|
<|> Null <$ symbol "null"
|
||||||
<|> ValueString <$> string
|
<|> String <$> blockString
|
||||||
<|> ValueString <$> blockString
|
<|> String <$> string
|
||||||
<|> ValueEnum <$> try enumValue
|
<|> Enum <$> try enumValue
|
||||||
<|> ValueList <$> listValue
|
<|> List <$> listValue
|
||||||
<|> ValueObject <$> objectValue
|
<|> Object <$> objectValue
|
||||||
<?> "value error!"
|
<?> "value error!"
|
||||||
where
|
where
|
||||||
booleanValue :: Parser Bool
|
booleanValue :: Parser Bool
|
||||||
@ -132,7 +135,7 @@ objectField = ObjectField <$> name <* symbol ":" <*> value
|
|||||||
|
|
||||||
-- * Variables
|
-- * Variables
|
||||||
|
|
||||||
variableDefinitions :: Parser VariableDefinitions
|
variableDefinitions :: Parser [VariableDefinition]
|
||||||
variableDefinitions = parens $ some variableDefinition
|
variableDefinitions = parens $ some variableDefinition
|
||||||
|
|
||||||
variableDefinition :: Parser VariableDefinition
|
variableDefinition :: Parser VariableDefinition
|
||||||
@ -149,9 +152,9 @@ defaultValue = equals *> value
|
|||||||
-- * Input Types
|
-- * Input Types
|
||||||
|
|
||||||
type_ :: Parser Type
|
type_ :: Parser Type
|
||||||
type_ = try (TypeNamed <$> name <* but "!")
|
type_ = try (TypeNonNull <$> nonNullType)
|
||||||
<|> TypeList <$> brackets type_
|
<|> TypeList <$> brackets type_
|
||||||
<|> TypeNonNull <$> nonNullType
|
<|> TypeNamed <$> name
|
||||||
<?> "type_ error!"
|
<?> "type_ error!"
|
||||||
|
|
||||||
nonNullType :: Parser NonNullType
|
nonNullType :: Parser NonNullType
|
||||||
@ -161,7 +164,7 @@ nonNullType = NonNullTypeNamed <$> name <* bang
|
|||||||
|
|
||||||
-- * Directives
|
-- * Directives
|
||||||
|
|
||||||
directives :: Parser Directives
|
directives :: Parser [Directive]
|
||||||
directives = some directive
|
directives = some directive
|
||||||
|
|
||||||
directive :: Parser Directive
|
directive :: Parser Directive
|
@ -1,119 +1,150 @@
|
|||||||
{-# LANGUAGE OverloadedStrings #-}
|
{-# LANGUAGE TupleSections #-}
|
||||||
|
{-# LANGUAGE ExplicitForAll #-}
|
||||||
|
|
||||||
|
-- | After the document is parsed, before getting executed the AST is
|
||||||
|
-- transformed into a similar, simpler AST. This module is responsible for
|
||||||
|
-- this transformation.
|
||||||
module Language.GraphQL.AST.Transform
|
module Language.GraphQL.AST.Transform
|
||||||
( document
|
( document
|
||||||
) where
|
) where
|
||||||
|
|
||||||
import Control.Applicative (empty)
|
import Control.Arrow (first)
|
||||||
import Control.Monad ((<=<))
|
import Control.Monad (foldM, unless)
|
||||||
import Data.Bifunctor (first)
|
import Control.Monad.Trans.Class (lift)
|
||||||
import Data.Either (partitionEithers)
|
import Control.Monad.Trans.Reader (ReaderT, ask, runReaderT)
|
||||||
import Data.Foldable (fold, foldMap)
|
import Control.Monad.Trans.State (StateT, evalStateT, gets, modify)
|
||||||
|
import Data.HashMap.Strict (HashMap)
|
||||||
|
import qualified Data.HashMap.Strict as HashMap
|
||||||
import qualified Data.List.NonEmpty as NonEmpty
|
import qualified Data.List.NonEmpty as NonEmpty
|
||||||
import Data.Monoid (Alt(Alt,getAlt), (<>))
|
import Data.Sequence (Seq, (<|), (><))
|
||||||
import qualified Language.GraphQL.AST as Full
|
import qualified Language.GraphQL.AST as Full
|
||||||
import qualified Language.GraphQL.AST.Core as Core
|
import qualified Language.GraphQL.AST.Core as Core
|
||||||
import qualified Language.GraphQL.Schema as Schema
|
import qualified Language.GraphQL.Schema as Schema
|
||||||
|
|
||||||
-- | Replaces a fragment name by a list of 'Field'. If the name doesn't match an
|
-- | Associates a fragment name with a list of 'Core.Field's.
|
||||||
-- empty list is returned.
|
data Replacement = Replacement
|
||||||
type Fragmenter = Core.Name -> [Core.Field]
|
{ fragments :: HashMap Core.Name (Seq Core.Selection)
|
||||||
|
, fragmentDefinitions :: HashMap Full.Name Full.FragmentDefinition
|
||||||
|
}
|
||||||
|
|
||||||
-- TODO: Replace Maybe by MonadThrow with CustomError
|
type TransformT a = StateT Replacement (ReaderT Schema.Subs Maybe) a
|
||||||
|
|
||||||
|
-- | Rewrites the original syntax tree into an intermediate representation used
|
||||||
|
-- for query execution.
|
||||||
document :: Schema.Subs -> Full.Document -> Maybe Core.Document
|
document :: Schema.Subs -> Full.Document -> Maybe Core.Document
|
||||||
document subs doc = operations subs fr ops
|
document subs document' =
|
||||||
|
flip runReaderT subs
|
||||||
|
$ evalStateT (collectFragments >> operations operationDefinitions)
|
||||||
|
$ Replacement HashMap.empty fragmentTable
|
||||||
where
|
where
|
||||||
(fr, ops) = first foldFrags
|
(fragmentTable, operationDefinitions) = foldr defragment mempty document'
|
||||||
. partitionEithers
|
defragment (Full.DefinitionOperation definition) acc =
|
||||||
. NonEmpty.toList
|
(definition :) <$> acc
|
||||||
$ defrag subs
|
defragment (Full.DefinitionFragment definition) acc =
|
||||||
<$> doc
|
let (Full.FragmentDefinition name _ _ _) = definition
|
||||||
|
in first (HashMap.insert name definition) acc
|
||||||
foldFrags :: [Fragmenter] -> Fragmenter
|
|
||||||
foldFrags fs n = getAlt $ foldMap (Alt . ($ n)) fs
|
|
||||||
|
|
||||||
-- * Operation
|
-- * Operation
|
||||||
|
|
||||||
-- TODO: Replace Maybe by MonadThrow CustomError
|
-- TODO: Replace Maybe by MonadThrow CustomError
|
||||||
operations
|
operations :: [Full.OperationDefinition] -> TransformT Core.Document
|
||||||
:: Schema.Subs
|
operations operations' = do
|
||||||
-> Fragmenter
|
coreOperations <- traverse operation operations'
|
||||||
-> [Full.OperationDefinition]
|
lift . lift $ NonEmpty.nonEmpty coreOperations
|
||||||
-> Maybe Core.Document
|
|
||||||
operations subs fr = NonEmpty.nonEmpty <=< traverse (operation subs fr)
|
|
||||||
|
|
||||||
operation
|
operation :: Full.OperationDefinition -> TransformT Core.Operation
|
||||||
:: Schema.Subs
|
operation (Full.OperationSelectionSet sels) =
|
||||||
-> Fragmenter
|
operation $ Full.OperationDefinition Full.Query mempty mempty mempty sels
|
||||||
-> Full.OperationDefinition
|
|
||||||
-> Maybe Core.Operation
|
|
||||||
operation subs fr (Full.OperationSelectionSet sels) =
|
|
||||||
operation subs fr $ Full.OperationDefinition Full.Query empty empty empty sels
|
|
||||||
-- TODO: Validate Variable definitions with substituter
|
-- TODO: Validate Variable definitions with substituter
|
||||||
operation subs fr (Full.OperationDefinition operationType name _vars _dirs sels)
|
operation (Full.OperationDefinition Full.Query name _vars _dirs sels) =
|
||||||
= case operationType of
|
Core.Query name <$> appendSelection sels
|
||||||
Full.Query -> Core.Query name <$> node
|
operation (Full.OperationDefinition Full.Mutation name _vars _dirs sels) =
|
||||||
Full.Mutation -> Core.Mutation name <$> node
|
Core.Mutation name <$> appendSelection sels
|
||||||
where
|
|
||||||
node = traverse (hush . selection subs fr) sels
|
|
||||||
|
|
||||||
selection
|
selection ::
|
||||||
:: Schema.Subs
|
Full.Selection ->
|
||||||
-> Fragmenter
|
TransformT (Either (Seq Core.Selection) Core.Selection)
|
||||||
-> Full.Selection
|
selection (Full.SelectionField fld) = Right . Core.SelectionField <$> field fld
|
||||||
-> Either [Core.Field] Core.Field
|
selection (Full.SelectionFragmentSpread (Full.FragmentSpread name _)) = do
|
||||||
selection subs fr (Full.SelectionField fld) =
|
fragments' <- gets fragments
|
||||||
Right $ field subs fr fld
|
Left <$> maybe lookupDefinition liftJust (HashMap.lookup name fragments')
|
||||||
selection _ fr (Full.SelectionFragmentSpread (Full.FragmentSpread n _dirs)) =
|
where
|
||||||
Left $ fr n
|
lookupDefinition :: TransformT (Seq Core.Selection)
|
||||||
selection _ _ (Full.SelectionInlineFragment _) =
|
lookupDefinition = do
|
||||||
error "Inline fragments not supported yet"
|
fragmentDefinitions' <- gets fragmentDefinitions
|
||||||
|
found <- lift . lift $ HashMap.lookup name fragmentDefinitions'
|
||||||
|
fragmentDefinition found
|
||||||
|
selection (Full.SelectionInlineFragment fragment)
|
||||||
|
| (Full.InlineFragment (Just typeCondition) _ selectionSet) <- fragment
|
||||||
|
= Right
|
||||||
|
. Core.SelectionFragment
|
||||||
|
. Core.Fragment typeCondition
|
||||||
|
<$> appendSelection selectionSet
|
||||||
|
| (Full.InlineFragment Nothing _ selectionSet) <- fragment
|
||||||
|
= Left <$> appendSelection selectionSet
|
||||||
|
|
||||||
-- * Fragment replacement
|
-- * Fragment replacement
|
||||||
|
|
||||||
-- | Extract Fragments into a single Fragmenter function and a Operation
|
-- | Extract fragment definitions into a single 'HashMap'.
|
||||||
-- Definition.
|
collectFragments :: TransformT ()
|
||||||
defrag
|
collectFragments = do
|
||||||
:: Schema.Subs
|
fragDefs <- gets fragmentDefinitions
|
||||||
-> Full.Definition
|
let nextValue = head $ HashMap.elems fragDefs
|
||||||
-> Either Fragmenter Full.OperationDefinition
|
unless (HashMap.null fragDefs) $ do
|
||||||
defrag _ (Full.DefinitionOperation op) =
|
_ <- fragmentDefinition nextValue
|
||||||
Right op
|
collectFragments
|
||||||
defrag subs (Full.DefinitionFragment fragDef) =
|
|
||||||
Left $ fragmentDefinition subs fragDef
|
|
||||||
|
|
||||||
fragmentDefinition :: Schema.Subs -> Full.FragmentDefinition -> Fragmenter
|
fragmentDefinition ::
|
||||||
fragmentDefinition subs (Full.FragmentDefinition name _tc _dirs sels) name' =
|
Full.FragmentDefinition ->
|
||||||
-- TODO: Support fragments within fragments. Fold instead of map.
|
TransformT (Seq Core.Selection)
|
||||||
if name == name'
|
fragmentDefinition (Full.FragmentDefinition name _tc _dirs selections) = do
|
||||||
then either id pure =<< NonEmpty.toList (selection subs mempty <$> sels)
|
modify deleteFragmentDefinition
|
||||||
else empty
|
newValue <- appendSelection selections
|
||||||
|
modify $ insertFragment newValue
|
||||||
field :: Schema.Subs -> Fragmenter -> Full.Field -> Core.Field
|
liftJust newValue
|
||||||
field subs fr (Full.Field a n args _dirs sels) =
|
|
||||||
Core.Field a n (fold $ argument subs `traverse` args) (foldr go empty sels)
|
|
||||||
where
|
where
|
||||||
go :: Full.Selection -> [Core.Field] -> [Core.Field]
|
deleteFragmentDefinition (Replacement fragments' fragmentDefinitions') =
|
||||||
go (Full.SelectionFragmentSpread (Full.FragmentSpread name _dirs)) = (fr name <>)
|
Replacement fragments' $ HashMap.delete name fragmentDefinitions'
|
||||||
go sel = (either id pure (selection subs fr sel) <>)
|
insertFragment newValue (Replacement fragments' fragmentDefinitions') =
|
||||||
|
let newFragments = HashMap.insert name newValue fragments'
|
||||||
|
in Replacement newFragments fragmentDefinitions'
|
||||||
|
|
||||||
argument :: Schema.Subs -> Full.Argument -> Maybe Core.Argument
|
field :: Full.Field -> TransformT Core.Field
|
||||||
argument subs (Full.Argument n v) = Core.Argument n <$> value subs v
|
field (Full.Field a n args _dirs sels) = do
|
||||||
|
arguments <- traverse argument args
|
||||||
|
selection' <- appendSelection sels
|
||||||
|
return $ Core.Field a n arguments selection'
|
||||||
|
|
||||||
value :: Schema.Subs -> Full.Value -> Maybe Core.Value
|
argument :: Full.Argument -> TransformT Core.Argument
|
||||||
value subs (Full.ValueVariable n) = subs n
|
argument (Full.Argument n v) = Core.Argument n <$> value v
|
||||||
value _ (Full.ValueInt i) = pure $ Core.ValueInt i
|
|
||||||
value _ (Full.ValueFloat f) = pure $ Core.ValueFloat f
|
|
||||||
value _ (Full.ValueString x) = pure $ Core.ValueString x
|
|
||||||
value _ (Full.ValueBoolean b) = pure $ Core.ValueBoolean b
|
|
||||||
value _ Full.ValueNull = pure Core.ValueNull
|
|
||||||
value _ (Full.ValueEnum e) = pure $ Core.ValueEnum e
|
|
||||||
value subs (Full.ValueList l) =
|
|
||||||
Core.ValueList <$> traverse (value subs) l
|
|
||||||
value subs (Full.ValueObject o) =
|
|
||||||
Core.ValueObject <$> traverse (objectField subs) o
|
|
||||||
|
|
||||||
objectField :: Schema.Subs -> Full.ObjectField -> Maybe Core.ObjectField
|
value :: Full.Value -> TransformT Core.Value
|
||||||
objectField subs (Full.ObjectField n v) = Core.ObjectField n <$> value subs v
|
value (Full.Variable n) = do
|
||||||
|
substitute' <- lift ask
|
||||||
|
lift . lift $ substitute' n
|
||||||
|
value (Full.Int i) = pure $ Core.Int i
|
||||||
|
value (Full.Float f) = pure $ Core.Float f
|
||||||
|
value (Full.String x) = pure $ Core.String x
|
||||||
|
value (Full.Boolean b) = pure $ Core.Boolean b
|
||||||
|
value Full.Null = pure Core.Null
|
||||||
|
value (Full.Enum e) = pure $ Core.Enum e
|
||||||
|
value (Full.List l) =
|
||||||
|
Core.List <$> traverse value l
|
||||||
|
value (Full.Object o) =
|
||||||
|
Core.Object . HashMap.fromList <$> traverse objectField o
|
||||||
|
|
||||||
hush :: Either a b -> Maybe b
|
objectField :: Full.ObjectField -> TransformT (Core.Name, Core.Value)
|
||||||
hush = either (const Nothing) Just
|
objectField (Full.ObjectField n v) = (n,) <$> value v
|
||||||
|
|
||||||
|
appendSelection ::
|
||||||
|
Traversable t =>
|
||||||
|
t Full.Selection ->
|
||||||
|
TransformT (Seq Core.Selection)
|
||||||
|
appendSelection = foldM go mempty
|
||||||
|
where
|
||||||
|
go acc sel = append acc <$> selection sel
|
||||||
|
append acc (Left list) = list >< acc
|
||||||
|
append acc (Right one) = one <| acc
|
||||||
|
|
||||||
|
liftJust :: forall a. a -> TransformT a
|
||||||
|
liftJust = lift . lift . Just
|
||||||
|
@ -1,5 +1,7 @@
|
|||||||
{-# LANGUAGE OverloadedStrings #-}
|
{-# LANGUAGE OverloadedStrings #-}
|
||||||
{-# LANGUAGE RecordWildCards #-}
|
{-# LANGUAGE RecordWildCards #-}
|
||||||
|
|
||||||
|
-- | Error handling.
|
||||||
module Language.GraphQL.Error
|
module Language.GraphQL.Error
|
||||||
( parseError
|
( parseError
|
||||||
, CollectErrsT
|
, CollectErrsT
|
||||||
|
@ -1,7 +1,6 @@
|
|||||||
{-# LANGUAGE OverloadedStrings #-}
|
{-# LANGUAGE OverloadedStrings #-}
|
||||||
|
|
||||||
-- | This module provides the function to execute a @GraphQL@ request --
|
-- | This module provides functions to execute a @GraphQL@ request.
|
||||||
-- according to a 'Schema'.
|
|
||||||
module Language.GraphQL.Execute
|
module Language.GraphQL.Execute
|
||||||
( execute
|
( execute
|
||||||
, executeWithName
|
, executeWithName
|
||||||
@ -9,51 +8,54 @@ module Language.GraphQL.Execute
|
|||||||
|
|
||||||
import Control.Monad.IO.Class (MonadIO)
|
import Control.Monad.IO.Class (MonadIO)
|
||||||
import qualified Data.Aeson as Aeson
|
import qualified Data.Aeson as Aeson
|
||||||
|
import Data.Foldable (toList)
|
||||||
|
import Data.List.NonEmpty (NonEmpty(..))
|
||||||
import qualified Data.List.NonEmpty as NE
|
import qualified Data.List.NonEmpty as NE
|
||||||
import Data.List.NonEmpty (NonEmpty((:|)))
|
|
||||||
import Data.Text (Text)
|
import Data.Text (Text)
|
||||||
import qualified Data.Text as Text
|
import qualified Data.Text as Text
|
||||||
import qualified Language.GraphQL.AST as AST
|
import qualified Language.GraphQL.AST as AST
|
||||||
import qualified Language.GraphQL.AST.Core as AST.Core
|
import qualified Language.GraphQL.AST.Core as AST.Core
|
||||||
import qualified Language.GraphQL.AST.Transform as Transform
|
import qualified Language.GraphQL.AST.Transform as Transform
|
||||||
import Language.GraphQL.Error
|
import Language.GraphQL.Error
|
||||||
import Language.GraphQL.Schema (Schema)
|
|
||||||
import qualified Language.GraphQL.Schema as Schema
|
import qualified Language.GraphQL.Schema as Schema
|
||||||
|
|
||||||
-- | Takes a 'Schema', a variable substitution function ('Schema.Subs'), and a
|
-- | The substitution is applied to the document, and the resolvers are applied
|
||||||
-- @GraphQL@ 'document'. The substitution is applied to the document using
|
-- to the resulting fields.
|
||||||
-- 'rootFields', and the 'Schema''s resolvers are applied to the resulting fields.
|
|
||||||
--
|
--
|
||||||
-- Returns the result of the query against the 'Schema' wrapped in a /data/ field, or
|
-- Returns the result of the query against the schema wrapped in a /data/
|
||||||
-- errors wrapped in an /errors/ field.
|
-- field, or errors wrapped in an /errors/ field.
|
||||||
execute :: MonadIO m
|
execute :: MonadIO m
|
||||||
=> Schema m
|
=> NonEmpty (Schema.Resolver m) -- ^ Resolvers.
|
||||||
-> Schema.Subs
|
-> Schema.Subs -- ^ Variable substitution function.
|
||||||
-> AST.Document
|
-> AST.Document -- @GraphQL@ document.
|
||||||
-> m Aeson.Value
|
-> m Aeson.Value
|
||||||
execute schema subs doc =
|
execute schema subs doc =
|
||||||
maybe transformError (document schema Nothing) $ Transform.document subs doc
|
maybe transformError (document schema Nothing) $ Transform.document subs doc
|
||||||
where
|
where
|
||||||
transformError = return $ singleError "Schema transformation error."
|
transformError = return $ singleError "Schema transformation error."
|
||||||
|
|
||||||
-- | Takes a 'Schema', operation name, a variable substitution function ('Schema.Subs'),
|
-- | The substitution is applied to the document, and the resolvers are applied
|
||||||
-- and a @GraphQL@ 'document'. The substitution is applied to the document using
|
-- to the resulting fields. The operation name can be used if the document
|
||||||
-- 'rootFields', and the 'Schema''s resolvers are applied to the resulting fields.
|
-- defines multiple root operations.
|
||||||
--
|
--
|
||||||
-- Returns the result of the query against the 'Schema' wrapped in a /data/ field, or
|
-- Returns the result of the query against the schema wrapped in a /data/
|
||||||
-- errors wrapped in an /errors/ field.
|
-- field, or errors wrapped in an /errors/ field.
|
||||||
executeWithName :: MonadIO m
|
executeWithName :: MonadIO m
|
||||||
=> Schema m
|
=> NonEmpty (Schema.Resolver m) -- ^ Resolvers
|
||||||
-> Text
|
-> Text -- ^ Operation name.
|
||||||
-> Schema.Subs
|
-> Schema.Subs -- ^ Variable substitution function.
|
||||||
-> AST.Document
|
-> AST.Document -- ^ @GraphQL@ Document.
|
||||||
-> m Aeson.Value
|
-> m Aeson.Value
|
||||||
executeWithName schema name subs doc =
|
executeWithName schema name subs doc =
|
||||||
maybe transformError (document schema $ Just name) $ Transform.document subs doc
|
maybe transformError (document schema $ Just name) $ Transform.document subs doc
|
||||||
where
|
where
|
||||||
transformError = return $ singleError "Schema transformation error."
|
transformError = return $ singleError "Schema transformation error."
|
||||||
|
|
||||||
document :: MonadIO m => Schema m -> Maybe Text -> AST.Core.Document -> m Aeson.Value
|
document :: MonadIO m
|
||||||
|
=> NonEmpty (Schema.Resolver m)
|
||||||
|
-> Maybe Text
|
||||||
|
-> AST.Core.Document
|
||||||
|
-> m Aeson.Value
|
||||||
document schema Nothing (op :| []) = operation schema op
|
document schema Nothing (op :| []) = operation schema op
|
||||||
document schema (Just name) operations = case NE.dropWhile matchingName operations of
|
document schema (Just name) operations = case NE.dropWhile matchingName operations of
|
||||||
[] -> return $ singleError
|
[] -> return $ singleError
|
||||||
@ -65,8 +67,11 @@ document schema (Just name) operations = case NE.dropWhile matchingName operatio
|
|||||||
matchingName _ = False
|
matchingName _ = False
|
||||||
document _ _ _ = return $ singleError "Missing operation name."
|
document _ _ _ = return $ singleError "Missing operation name."
|
||||||
|
|
||||||
operation :: MonadIO m => Schema m -> AST.Core.Operation -> m Aeson.Value
|
operation :: MonadIO m
|
||||||
|
=> NonEmpty (Schema.Resolver m)
|
||||||
|
-> AST.Core.Operation
|
||||||
|
-> m Aeson.Value
|
||||||
operation schema (AST.Core.Query _ flds)
|
operation schema (AST.Core.Query _ flds)
|
||||||
= runCollectErrs (Schema.resolve (NE.toList schema) (NE.toList flds))
|
= runCollectErrs (Schema.resolve (toList schema) flds)
|
||||||
operation schema (AST.Core.Mutation _ flds)
|
operation schema (AST.Core.Mutation _ flds)
|
||||||
= runCollectErrs (Schema.resolve (NE.toList schema) (NE.toList flds))
|
= runCollectErrs (Schema.resolve (toList schema) flds)
|
||||||
|
@ -1,20 +1,15 @@
|
|||||||
{-# LANGUAGE OverloadedStrings #-}
|
{-# LANGUAGE OverloadedStrings #-}
|
||||||
|
|
||||||
-- | This module provides a representation of a @GraphQL@ Schema in addition to
|
-- | This module provides a representation of a @GraphQL@ Schema in addition to
|
||||||
-- functions for defining and manipulating Schemas.
|
-- functions for defining and manipulating schemas.
|
||||||
module Language.GraphQL.Schema
|
module Language.GraphQL.Schema
|
||||||
( Resolver
|
( Resolver
|
||||||
, Schema
|
|
||||||
, Subs
|
, Subs
|
||||||
, object
|
, object
|
||||||
, objectA
|
, objectA
|
||||||
, scalar
|
, scalar
|
||||||
, scalarA
|
, scalarA
|
||||||
, enum
|
|
||||||
, enumA
|
|
||||||
, resolve
|
, resolve
|
||||||
, wrappedEnum
|
|
||||||
, wrappedEnumA
|
|
||||||
, wrappedObject
|
, wrappedObject
|
||||||
, wrappedObjectA
|
, wrappedObjectA
|
||||||
, wrappedScalar
|
, wrappedScalar
|
||||||
@ -28,35 +23,27 @@ module Language.GraphQL.Schema
|
|||||||
import Control.Monad.IO.Class (MonadIO(..))
|
import Control.Monad.IO.Class (MonadIO(..))
|
||||||
import Control.Monad.Trans.Class (lift)
|
import Control.Monad.Trans.Class (lift)
|
||||||
import Control.Monad.Trans.Except (runExceptT)
|
import Control.Monad.Trans.Except (runExceptT)
|
||||||
import Data.Foldable ( find
|
import Control.Monad.Trans.Reader (runReaderT)
|
||||||
, fold
|
import Data.Foldable (find, fold)
|
||||||
)
|
|
||||||
import Data.List.NonEmpty (NonEmpty)
|
|
||||||
import Data.Maybe (fromMaybe)
|
import Data.Maybe (fromMaybe)
|
||||||
import qualified Data.Aeson as Aeson
|
import qualified Data.Aeson as Aeson
|
||||||
import Data.HashMap.Strict (HashMap)
|
import Data.HashMap.Strict (HashMap)
|
||||||
import qualified Data.HashMap.Strict as HashMap
|
import qualified Data.HashMap.Strict as HashMap
|
||||||
|
import Data.Sequence (Seq)
|
||||||
import Data.Text (Text)
|
import Data.Text (Text)
|
||||||
import qualified Data.Text as T
|
import qualified Data.Text as T
|
||||||
|
import Language.GraphQL.AST.Core
|
||||||
import Language.GraphQL.Error
|
import Language.GraphQL.Error
|
||||||
import Language.GraphQL.Trans
|
import Language.GraphQL.Trans
|
||||||
import Language.GraphQL.Type
|
import qualified Language.GraphQL.Type as Type
|
||||||
import Language.GraphQL.AST.Core
|
|
||||||
|
|
||||||
-- | A GraphQL schema.
|
-- | Resolves a 'Field' into an @Aeson.@'Data.Aeson.Types.Object' with error
|
||||||
-- @m@ is usually expected to be an instance of 'MonadIO'.
|
-- information (if an error has occurred). @m@ is usually expected to be an
|
||||||
type Schema m = NonEmpty (Resolver m)
|
-- instance of 'MonadIO'.
|
||||||
|
|
||||||
-- | Resolves a 'Field' into an @Aeson.@'Aeson.Object' with error information
|
|
||||||
-- (or 'empty'). @m@ is usually expected to be an instance of 'MonadIO.
|
|
||||||
data Resolver m = Resolver
|
data Resolver m = Resolver
|
||||||
Text -- ^ Name
|
Text -- ^ Name
|
||||||
(Field -> CollectErrsT m Aeson.Object) -- ^ Resolver
|
(Field -> CollectErrsT m Aeson.Object) -- ^ Resolver
|
||||||
|
|
||||||
type Fields = [Field]
|
|
||||||
|
|
||||||
type Arguments = [Argument]
|
|
||||||
|
|
||||||
-- | Variable substitution function.
|
-- | Variable substitution function.
|
||||||
type Subs = Name -> Maybe Value
|
type Subs = Name -> Maybe Value
|
||||||
|
|
||||||
@ -66,14 +53,14 @@ object name = objectA name . const
|
|||||||
|
|
||||||
-- | Like 'object' but also taking 'Argument's.
|
-- | Like 'object' but also taking 'Argument's.
|
||||||
objectA :: MonadIO m
|
objectA :: MonadIO m
|
||||||
=> Name -> (Arguments -> ActionT m [Resolver m]) -> Resolver m
|
=> Name -> ([Argument] -> ActionT m [Resolver m]) -> Resolver m
|
||||||
objectA name f = Resolver name $ resolveFieldValue f resolveRight
|
objectA name f = Resolver name $ resolveFieldValue f resolveRight
|
||||||
where
|
where
|
||||||
resolveRight fld@(Field _ _ _ flds) resolver = withField (resolve resolver flds) fld
|
resolveRight fld@(Field _ _ _ flds) resolver = withField (resolve resolver flds) fld
|
||||||
|
|
||||||
-- | Like 'object' but also taking 'Argument's and can be null or a list of objects.
|
-- | Like 'object' but also taking 'Argument's and can be null or a list of objects.
|
||||||
wrappedObjectA :: MonadIO m
|
wrappedObjectA :: MonadIO m
|
||||||
=> Name -> (Arguments -> ActionT m (Wrapping [Resolver m])) -> Resolver m
|
=> Name -> ([Argument] -> ActionT m (Type.Wrapping [Resolver m])) -> Resolver m
|
||||||
wrappedObjectA name f = Resolver name $ resolveFieldValue f resolveRight
|
wrappedObjectA name f = Resolver name $ resolveFieldValue f resolveRight
|
||||||
where
|
where
|
||||||
resolveRight fld@(Field _ _ _ sels) resolver
|
resolveRight fld@(Field _ _ _ sels) resolver
|
||||||
@ -81,7 +68,7 @@ wrappedObjectA name f = Resolver name $ resolveFieldValue f resolveRight
|
|||||||
|
|
||||||
-- | Like 'object' but can be null or a list of objects.
|
-- | Like 'object' but can be null or a list of objects.
|
||||||
wrappedObject :: MonadIO m
|
wrappedObject :: MonadIO m
|
||||||
=> Name -> ActionT m (Wrapping [Resolver m]) -> Resolver m
|
=> Name -> ActionT m (Type.Wrapping [Resolver m]) -> Resolver m
|
||||||
wrappedObject name = wrappedObjectA name . const
|
wrappedObject name = wrappedObjectA name . const
|
||||||
|
|
||||||
-- | A scalar represents a primitive value, like a string or an integer.
|
-- | A scalar represents a primitive value, like a string or an integer.
|
||||||
@ -90,60 +77,36 @@ scalar name = scalarA name . const
|
|||||||
|
|
||||||
-- | Like 'scalar' but also taking 'Argument's.
|
-- | Like 'scalar' but also taking 'Argument's.
|
||||||
scalarA :: (MonadIO m, Aeson.ToJSON a)
|
scalarA :: (MonadIO m, Aeson.ToJSON a)
|
||||||
=> Name -> (Arguments -> ActionT m a) -> Resolver m
|
=> Name -> ([Argument] -> ActionT m a) -> Resolver m
|
||||||
scalarA name f = Resolver name $ resolveFieldValue f resolveRight
|
scalarA name f = Resolver name $ resolveFieldValue f resolveRight
|
||||||
where
|
where
|
||||||
resolveRight fld result = withField (return result) fld
|
resolveRight fld result = withField (return result) fld
|
||||||
|
|
||||||
-- | Lika 'scalar' but also taking 'Argument's and can be null or a list of scalars.
|
-- | Like 'scalar' but also taking 'Argument's and can be null or a list of scalars.
|
||||||
wrappedScalarA :: (MonadIO m, Aeson.ToJSON a)
|
wrappedScalarA :: (MonadIO m, Aeson.ToJSON a)
|
||||||
=> Name -> (Arguments -> ActionT m (Wrapping a)) -> Resolver m
|
=> Name -> ([Argument] -> ActionT m (Type.Wrapping a)) -> Resolver m
|
||||||
wrappedScalarA name f = Resolver name $ resolveFieldValue f resolveRight
|
wrappedScalarA name f = Resolver name $ resolveFieldValue f resolveRight
|
||||||
where
|
where
|
||||||
resolveRight fld (Named result) = withField (return result) fld
|
resolveRight fld (Type.Named result) = withField (return result) fld
|
||||||
resolveRight fld Null
|
resolveRight fld Type.Null
|
||||||
= return $ HashMap.singleton (aliasOrName fld) Aeson.Null
|
= return $ HashMap.singleton (aliasOrName fld) Aeson.Null
|
||||||
resolveRight fld (List result) = withField (return result) fld
|
resolveRight fld (Type.List result) = withField (return result) fld
|
||||||
|
|
||||||
-- | Like 'scalar' but can be null or a list of scalars.
|
-- | Like 'scalar' but can be null or a list of scalars.
|
||||||
wrappedScalar :: (MonadIO m, Aeson.ToJSON a)
|
wrappedScalar :: (MonadIO m, Aeson.ToJSON a)
|
||||||
=> Name -> ActionT m (Wrapping a) -> Resolver m
|
=> Name -> ActionT m (Type.Wrapping a) -> Resolver m
|
||||||
wrappedScalar name = wrappedScalarA name . const
|
wrappedScalar name = wrappedScalarA name . const
|
||||||
|
|
||||||
-- | Represents one of a finite set of possible values.
|
|
||||||
-- Used in place of a 'scalar' when the possible responses are easily enumerable.
|
|
||||||
enum :: MonadIO m => Name -> ActionT m [Text] -> Resolver m
|
|
||||||
enum name = enumA name . const
|
|
||||||
|
|
||||||
-- | Like 'enum' but also taking 'Argument's.
|
|
||||||
enumA :: MonadIO m => Name -> (Arguments -> ActionT m [Text]) -> Resolver m
|
|
||||||
enumA name f = Resolver name $ resolveFieldValue f resolveRight
|
|
||||||
where
|
|
||||||
resolveRight fld resolver = withField (return resolver) fld
|
|
||||||
|
|
||||||
-- | Like 'enum' but also taking 'Argument's and can be null or a list of enums.
|
|
||||||
wrappedEnumA :: MonadIO m
|
|
||||||
=> Name -> (Arguments -> ActionT m (Wrapping [Text])) -> Resolver m
|
|
||||||
wrappedEnumA name f = Resolver name $ resolveFieldValue f resolveRight
|
|
||||||
where
|
|
||||||
resolveRight fld (Named resolver) = withField (return resolver) fld
|
|
||||||
resolveRight fld Null
|
|
||||||
= return $ HashMap.singleton (aliasOrName fld) Aeson.Null
|
|
||||||
resolveRight fld (List resolver) = withField (return resolver) fld
|
|
||||||
|
|
||||||
-- | Like 'enum' but can be null or a list of enums.
|
|
||||||
wrappedEnum :: MonadIO m => Name -> ActionT m (Wrapping [Text]) -> Resolver m
|
|
||||||
wrappedEnum name = wrappedEnumA name . const
|
|
||||||
|
|
||||||
resolveFieldValue :: MonadIO m
|
resolveFieldValue :: MonadIO m
|
||||||
=> ([Argument] -> ActionT m a)
|
=> ([Argument] -> ActionT m a)
|
||||||
-> (Field -> a -> CollectErrsT m (HashMap Text Aeson.Value))
|
-> (Field -> a -> CollectErrsT m (HashMap Text Aeson.Value))
|
||||||
-> Field
|
-> Field
|
||||||
-> CollectErrsT m (HashMap Text Aeson.Value)
|
-> CollectErrsT m (HashMap Text Aeson.Value)
|
||||||
resolveFieldValue f resolveRight fld@(Field _ _ args _) = do
|
resolveFieldValue f resolveRight fld@(Field _ _ args _) = do
|
||||||
result <- lift $ runExceptT . runActionT $ f args
|
result <- lift $ reader . runExceptT . runActionT $ f args
|
||||||
either resolveLeft (resolveRight fld) result
|
either resolveLeft (resolveRight fld) result
|
||||||
where
|
where
|
||||||
|
reader = flip runReaderT $ Context mempty
|
||||||
resolveLeft err = do
|
resolveLeft err = do
|
||||||
_ <- addErrMsg err
|
_ <- addErrMsg err
|
||||||
return $ HashMap.singleton (aliasOrName fld) Aeson.Null
|
return $ HashMap.singleton (aliasOrName fld) Aeson.Null
|
||||||
@ -158,11 +121,21 @@ withField v fld
|
|||||||
-- 'Resolver' to each 'Field'. Resolves into a value containing the
|
-- 'Resolver' to each 'Field'. Resolves into a value containing the
|
||||||
-- resolved 'Field', or a null value and error information.
|
-- resolved 'Field', or a null value and error information.
|
||||||
resolve :: MonadIO m
|
resolve :: MonadIO m
|
||||||
=> [Resolver m] -> Fields -> CollectErrsT m Aeson.Value
|
=> [Resolver m] -> Seq Selection -> CollectErrsT m Aeson.Value
|
||||||
resolve resolvers = fmap (Aeson.toJSON . fold) . traverse tryResolvers
|
resolve resolvers = fmap (Aeson.toJSON . fold) . traverse tryResolvers
|
||||||
where
|
where
|
||||||
tryResolvers fld = maybe (errmsg fld) (tryResolver fld) $ find (compareResolvers fld) resolvers
|
resolveTypeName (Resolver "__typename" f) = do
|
||||||
compareResolvers (Field _ name _ _) (Resolver name' _) = name == name'
|
value <- f $ Field Nothing "__typename" mempty mempty
|
||||||
|
return $ HashMap.lookupDefault "" "__typename" value
|
||||||
|
resolveTypeName _ = return ""
|
||||||
|
tryResolvers (SelectionField fld@(Field _ name _ _))
|
||||||
|
= maybe (errmsg fld) (tryResolver fld) $ find (compareResolvers name) resolvers
|
||||||
|
tryResolvers (SelectionFragment (Fragment typeCondition selections')) = do
|
||||||
|
that <- maybe (return "") resolveTypeName (find (compareResolvers "__typename") resolvers)
|
||||||
|
if Aeson.String typeCondition == that
|
||||||
|
then fmap fold . traverse tryResolvers $ selections'
|
||||||
|
else return mempty
|
||||||
|
compareResolvers name (Resolver name' _) = name == name'
|
||||||
tryResolver fld (Resolver _ resolver) = resolver fld
|
tryResolver fld (Resolver _ resolver) = resolver fld
|
||||||
errmsg fld@(Field _ name _ _) = do
|
errmsg fld@(Field _ name _ _) = do
|
||||||
addErrMsg $ T.unwords ["field", name, "not resolved."]
|
addErrMsg $ T.unwords ["field", name, "not resolved."]
|
||||||
|
@ -1,5 +1,7 @@
|
|||||||
|
-- | Monad transformer stack used by the @GraphQL@ resolvers.
|
||||||
module Language.GraphQL.Trans
|
module Language.GraphQL.Trans
|
||||||
( ActionT(..)
|
( ActionT(..)
|
||||||
|
, Context(Context)
|
||||||
) where
|
) where
|
||||||
|
|
||||||
import Control.Applicative (Alternative(..))
|
import Control.Applicative (Alternative(..))
|
||||||
@ -7,9 +9,19 @@ import Control.Monad (MonadPlus(..))
|
|||||||
import Control.Monad.IO.Class (MonadIO(..))
|
import Control.Monad.IO.Class (MonadIO(..))
|
||||||
import Control.Monad.Trans.Class (MonadTrans(..))
|
import Control.Monad.Trans.Class (MonadTrans(..))
|
||||||
import Control.Monad.Trans.Except (ExceptT)
|
import Control.Monad.Trans.Except (ExceptT)
|
||||||
|
import Control.Monad.Trans.Reader (ReaderT)
|
||||||
|
import Data.HashMap.Strict (HashMap)
|
||||||
import Data.Text (Text)
|
import Data.Text (Text)
|
||||||
|
import Language.GraphQL.AST.Core (Name, Value)
|
||||||
|
|
||||||
newtype ActionT m a = ActionT { runActionT :: ExceptT Text m a }
|
-- | Resolution context holds resolver arguments.
|
||||||
|
newtype Context = Context (HashMap Name Value)
|
||||||
|
|
||||||
|
-- | Monad transformer stack used by the resolvers to provide error handling
|
||||||
|
-- and resolution context (resolver arguments).
|
||||||
|
newtype ActionT m a = ActionT
|
||||||
|
{ runActionT :: ExceptT Text (ReaderT Context m) a
|
||||||
|
}
|
||||||
|
|
||||||
instance Functor m => Functor (ActionT m) where
|
instance Functor m => Functor (ActionT m) where
|
||||||
fmap f = ActionT . fmap f . runActionT
|
fmap f = ActionT . fmap f . runActionT
|
||||||
@ -23,7 +35,7 @@ instance Monad m => Monad (ActionT m) where
|
|||||||
(ActionT action) >>= f = ActionT $ action >>= runActionT . f
|
(ActionT action) >>= f = ActionT $ action >>= runActionT . f
|
||||||
|
|
||||||
instance MonadTrans ActionT where
|
instance MonadTrans ActionT where
|
||||||
lift = ActionT . lift
|
lift = ActionT . lift . lift
|
||||||
|
|
||||||
instance MonadIO m => MonadIO (ActionT m) where
|
instance MonadIO m => MonadIO (ActionT m) where
|
||||||
liftIO = lift . liftIO
|
liftIO = lift . liftIO
|
||||||
|
@ -1,11 +1,9 @@
|
|||||||
-- | Definitions for @GraphQL@ type system.
|
-- | Definitions for @GraphQL@ input types.
|
||||||
module Language.GraphQL.Type
|
module Language.GraphQL.Type
|
||||||
( Wrapping(..)
|
( Wrapping(..)
|
||||||
) where
|
) where
|
||||||
|
|
||||||
import Data.Aeson as Aeson ( ToJSON
|
import Data.Aeson as Aeson (ToJSON, toJSON)
|
||||||
, toJSON
|
|
||||||
)
|
|
||||||
import qualified Data.Aeson as Aeson
|
import qualified Data.Aeson as Aeson
|
||||||
|
|
||||||
-- | GraphQL distinguishes between "wrapping" and "named" types. Each wrapping
|
-- | GraphQL distinguishes between "wrapping" and "named" types. Each wrapping
|
||||||
|
@ -1,6 +1,9 @@
|
|||||||
resolver: lts-14.0
|
resolver: lts-14.16
|
||||||
|
|
||||||
packages:
|
packages:
|
||||||
- '.'
|
- .
|
||||||
|
|
||||||
extra-deps: []
|
extra-deps: []
|
||||||
flags: {}
|
flags: {}
|
||||||
extra-package-dbs: []
|
|
||||||
|
pvp-bounds: both
|
||||||
|
19
tests/Language/GraphQL/AST/EncoderSpec.hs
Normal file
19
tests/Language/GraphQL/AST/EncoderSpec.hs
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
{-# LANGUAGE OverloadedStrings #-}
|
||||||
|
module Language.GraphQL.AST.EncoderSpec
|
||||||
|
( spec
|
||||||
|
) where
|
||||||
|
|
||||||
|
import Language.GraphQL.AST (Value(..))
|
||||||
|
import Language.GraphQL.AST.Encoder
|
||||||
|
import Test.Hspec ( Spec
|
||||||
|
, describe
|
||||||
|
, it
|
||||||
|
, shouldBe
|
||||||
|
)
|
||||||
|
|
||||||
|
spec :: Spec
|
||||||
|
spec = describe "value" $ do
|
||||||
|
it "escapes \\" $
|
||||||
|
value minified (String "\\") `shouldBe` "\"\\\\\""
|
||||||
|
it "escapes quotes" $
|
||||||
|
value minified (String "\"") `shouldBe` "\"\\\"\""
|
92
tests/Language/GraphQL/AST/LexerSpec.hs
Normal file
92
tests/Language/GraphQL/AST/LexerSpec.hs
Normal file
@ -0,0 +1,92 @@
|
|||||||
|
{-# LANGUAGE OverloadedStrings #-}
|
||||||
|
{-# LANGUAGE QuasiQuotes #-}
|
||||||
|
module Language.GraphQL.AST.LexerSpec
|
||||||
|
( spec
|
||||||
|
) where
|
||||||
|
|
||||||
|
import Data.Text (Text)
|
||||||
|
import Data.Void (Void)
|
||||||
|
import Language.GraphQL.AST.Lexer
|
||||||
|
import Test.Hspec (Spec, context, describe, it)
|
||||||
|
import Test.Hspec.Megaparsec (shouldParse, shouldSucceedOn)
|
||||||
|
import Text.Megaparsec (ParseErrorBundle, parse)
|
||||||
|
import Text.RawString.QQ (r)
|
||||||
|
|
||||||
|
spec :: Spec
|
||||||
|
spec = describe "Lexer" $ do
|
||||||
|
context "Reference tests" $ do
|
||||||
|
it "accepts BOM header" $
|
||||||
|
parse unicodeBOM "" `shouldSucceedOn` "\xfeff"
|
||||||
|
|
||||||
|
it "lexes strings" $ do
|
||||||
|
parse string "" [r|"simple"|] `shouldParse` "simple"
|
||||||
|
parse string "" [r|" white space "|] `shouldParse` " white space "
|
||||||
|
parse string "" [r|"quote \""|] `shouldParse` [r|quote "|]
|
||||||
|
parse string "" [r|"escaped \n"|] `shouldParse` "escaped \n"
|
||||||
|
parse string "" [r|"slashes \\ \/"|] `shouldParse` [r|slashes \ /|]
|
||||||
|
parse string "" [r|"unicode \u1234\u5678\u90AB\uCDEF"|]
|
||||||
|
`shouldParse` "unicode ሴ噸邫췯"
|
||||||
|
|
||||||
|
it "lexes block string" $ do
|
||||||
|
parse blockString "" [r|"""simple"""|] `shouldParse` "simple"
|
||||||
|
parse blockString "" [r|""" white space """|]
|
||||||
|
`shouldParse` " white space "
|
||||||
|
parse blockString "" [r|"""contains " quote"""|]
|
||||||
|
`shouldParse` [r|contains " quote|]
|
||||||
|
parse blockString "" [r|"""contains \""" triplequote"""|]
|
||||||
|
`shouldParse` [r|contains """ triplequote|]
|
||||||
|
parse blockString "" "\"\"\"multi\nline\"\"\"" `shouldParse` "multi\nline"
|
||||||
|
parse blockString "" "\"\"\"multi\rline\r\nnormalized\"\"\""
|
||||||
|
`shouldParse` "multi\nline\nnormalized"
|
||||||
|
parse blockString "" "\"\"\"multi\rline\r\nnormalized\"\"\""
|
||||||
|
`shouldParse` "multi\nline\nnormalized"
|
||||||
|
parse blockString "" [r|"""unescaped \n\r\b\t\f\u1234"""|]
|
||||||
|
`shouldParse` [r|unescaped \n\r\b\t\f\u1234|]
|
||||||
|
parse blockString "" [r|"""slashes \\ \/"""|]
|
||||||
|
`shouldParse` [r|slashes \\ \/|]
|
||||||
|
parse blockString "" [r|"""
|
||||||
|
|
||||||
|
spans
|
||||||
|
multiple
|
||||||
|
lines
|
||||||
|
|
||||||
|
"""|] `shouldParse` "spans\n multiple\n lines"
|
||||||
|
|
||||||
|
it "lexes numbers" $ do
|
||||||
|
parse integer "" "4" `shouldParse` (4 :: Int)
|
||||||
|
parse float "" "4.123" `shouldParse` 4.123
|
||||||
|
parse integer "" "-4" `shouldParse` (-4 :: Int)
|
||||||
|
parse integer "" "9" `shouldParse` (9 :: Int)
|
||||||
|
parse integer "" "0" `shouldParse` (0 :: Int)
|
||||||
|
parse float "" "-4.123" `shouldParse` (-4.123)
|
||||||
|
parse float "" "0.123" `shouldParse` 0.123
|
||||||
|
parse float "" "123e4" `shouldParse` 123e4
|
||||||
|
parse float "" "123E4" `shouldParse` 123E4
|
||||||
|
parse float "" "123e-4" `shouldParse` 123e-4
|
||||||
|
parse float "" "123e+4" `shouldParse` 123e+4
|
||||||
|
parse float "" "-1.123e4" `shouldParse` (-1.123e4)
|
||||||
|
parse float "" "-1.123E4" `shouldParse` (-1.123E4)
|
||||||
|
parse float "" "-1.123e-4" `shouldParse` (-1.123e-4)
|
||||||
|
parse float "" "-1.123e+4" `shouldParse` (-1.123e+4)
|
||||||
|
parse float "" "-1.123e4567" `shouldParse` (-1.123e4567)
|
||||||
|
|
||||||
|
it "lexes punctuation" $ do
|
||||||
|
parse bang "" "!" `shouldParse` "!"
|
||||||
|
parse dollar "" "$" `shouldParse` "$"
|
||||||
|
runBetween parens `shouldSucceedOn` "()"
|
||||||
|
parse spread "" "..." `shouldParse` "..."
|
||||||
|
parse colon "" ":" `shouldParse` ":"
|
||||||
|
parse equals "" "=" `shouldParse` "="
|
||||||
|
parse at "" "@" `shouldParse` '@'
|
||||||
|
runBetween brackets `shouldSucceedOn` "[]"
|
||||||
|
runBetween braces `shouldSucceedOn` "{}"
|
||||||
|
parse pipe "" "|" `shouldParse` "|"
|
||||||
|
|
||||||
|
context "Implementation tests" $ do
|
||||||
|
it "lexes empty block strings" $
|
||||||
|
parse blockString "" [r|""""""|] `shouldParse` ""
|
||||||
|
it "lexes ampersand" $
|
||||||
|
parse amp "" "&" `shouldParse` "&"
|
||||||
|
|
||||||
|
runBetween :: (Parser () -> Parser ()) -> Text -> Either (ParseErrorBundle Text Void) ()
|
||||||
|
runBetween parser = parse (parser $ pure ()) ""
|
32
tests/Language/GraphQL/AST/ParserSpec.hs
Normal file
32
tests/Language/GraphQL/AST/ParserSpec.hs
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
{-# LANGUAGE OverloadedStrings #-}
|
||||||
|
{-# LANGUAGE QuasiQuotes #-}
|
||||||
|
module Language.GraphQL.AST.ParserSpec
|
||||||
|
( spec
|
||||||
|
) where
|
||||||
|
|
||||||
|
import Language.GraphQL.AST.Parser
|
||||||
|
import Test.Hspec (Spec, describe, it)
|
||||||
|
import Test.Hspec.Megaparsec (shouldSucceedOn)
|
||||||
|
import Text.Megaparsec (parse)
|
||||||
|
import Text.RawString.QQ (r)
|
||||||
|
|
||||||
|
spec :: Spec
|
||||||
|
spec = describe "Parser" $ do
|
||||||
|
it "accepts BOM header" $
|
||||||
|
parse document "" `shouldSucceedOn` "\xfeff{foo}"
|
||||||
|
|
||||||
|
it "accepts block strings as argument" $
|
||||||
|
parse document "" `shouldSucceedOn` [r|{
|
||||||
|
hello(text: """Argument""")
|
||||||
|
}|]
|
||||||
|
|
||||||
|
it "accepts strings as argument" $
|
||||||
|
parse document "" `shouldSucceedOn` [r|{
|
||||||
|
hello(text: "Argument")
|
||||||
|
}|]
|
||||||
|
|
||||||
|
it "accepts two required arguments" $
|
||||||
|
parse document "" `shouldSucceedOn` [r|
|
||||||
|
mutation auth($username: String!, $password: String!){
|
||||||
|
test
|
||||||
|
}|]
|
@ -1,21 +0,0 @@
|
|||||||
{-# LANGUAGE OverloadedStrings #-}
|
|
||||||
module Language.GraphQL.EncoderSpec
|
|
||||||
( spec
|
|
||||||
) where
|
|
||||||
|
|
||||||
import Language.GraphQL.AST ( Value(..))
|
|
||||||
import Language.GraphQL.Encoder ( value
|
|
||||||
, minified
|
|
||||||
)
|
|
||||||
import Test.Hspec ( Spec
|
|
||||||
, describe
|
|
||||||
, it
|
|
||||||
, shouldBe
|
|
||||||
)
|
|
||||||
|
|
||||||
spec :: Spec
|
|
||||||
spec = describe "value" $ do
|
|
||||||
it "escapes \\" $
|
|
||||||
value minified (ValueString "\\") `shouldBe` "\"\\\\\""
|
|
||||||
it "escapes quotes" $
|
|
||||||
value minified (ValueString "\"") `shouldBe` "\"\\\"\""
|
|
@ -1,104 +0,0 @@
|
|||||||
{-# LANGUAGE ExplicitForAll #-}
|
|
||||||
{-# LANGUAGE OverloadedStrings #-}
|
|
||||||
{-# LANGUAGE QuasiQuotes #-}
|
|
||||||
module Language.GraphQL.LexerSpec
|
|
||||||
( spec
|
|
||||||
) where
|
|
||||||
|
|
||||||
import Data.Either (isRight)
|
|
||||||
import Data.Text (Text)
|
|
||||||
import Data.Void (Void)
|
|
||||||
import Language.GraphQL.Lexer
|
|
||||||
import Test.Hspec ( Spec
|
|
||||||
, context
|
|
||||||
, describe
|
|
||||||
, it
|
|
||||||
, shouldBe
|
|
||||||
, shouldSatisfy
|
|
||||||
)
|
|
||||||
import Text.Megaparsec ( ParseErrorBundle
|
|
||||||
, parse
|
|
||||||
)
|
|
||||||
import Text.RawString.QQ (r)
|
|
||||||
|
|
||||||
spec :: Spec
|
|
||||||
spec = describe "Lexer" $ do
|
|
||||||
context "Reference tests" $ do
|
|
||||||
it "accepts BOM header" $
|
|
||||||
runParser unicodeBOM "\xfeff" `shouldSatisfy` isRight
|
|
||||||
|
|
||||||
it "lexes strings" $ do
|
|
||||||
runParser string [r|"simple"|] `shouldBe` Right "simple"
|
|
||||||
runParser string [r|" white space "|] `shouldBe` Right " white space "
|
|
||||||
runParser string [r|"quote \""|] `shouldBe` Right [r|quote "|]
|
|
||||||
runParser string [r|"escaped \n"|] `shouldBe` Right "escaped \n"
|
|
||||||
runParser string [r|"slashes \\ \/"|] `shouldBe` Right [r|slashes \ /|]
|
|
||||||
runParser string [r|"unicode \u1234\u5678\u90AB\uCDEF"|]
|
|
||||||
`shouldBe` Right "unicode ሴ噸邫췯"
|
|
||||||
|
|
||||||
it "lexes block string" $ do
|
|
||||||
runParser blockString [r|"""simple"""|] `shouldBe` Right "simple"
|
|
||||||
runParser blockString [r|""" white space """|]
|
|
||||||
`shouldBe` Right " white space "
|
|
||||||
runParser blockString [r|"""contains " quote"""|]
|
|
||||||
`shouldBe` Right [r|contains " quote|]
|
|
||||||
runParser blockString [r|"""contains \""" triplequote"""|]
|
|
||||||
`shouldBe` Right [r|contains """ triplequote|]
|
|
||||||
runParser blockString "\"\"\"multi\nline\"\"\"" `shouldBe` Right "multi\nline"
|
|
||||||
runParser blockString "\"\"\"multi\rline\r\nnormalized\"\"\""
|
|
||||||
`shouldBe` Right "multi\nline\nnormalized"
|
|
||||||
runParser blockString "\"\"\"multi\rline\r\nnormalized\"\"\""
|
|
||||||
`shouldBe` Right "multi\nline\nnormalized"
|
|
||||||
runParser blockString [r|"""unescaped \n\r\b\t\f\u1234"""|]
|
|
||||||
`shouldBe` Right [r|unescaped \n\r\b\t\f\u1234|]
|
|
||||||
runParser blockString [r|"""slashes \\ \/"""|]
|
|
||||||
`shouldBe` Right [r|slashes \\ \/|]
|
|
||||||
runParser blockString [r|"""
|
|
||||||
|
|
||||||
spans
|
|
||||||
multiple
|
|
||||||
lines
|
|
||||||
|
|
||||||
"""|] `shouldBe` Right "spans\n multiple\n lines"
|
|
||||||
|
|
||||||
it "lexes numbers" $ do
|
|
||||||
runParser integer "4" `shouldBe` Right (4 :: Int)
|
|
||||||
runParser float "4.123" `shouldBe` Right 4.123
|
|
||||||
runParser integer "-4" `shouldBe` Right (-4 :: Int)
|
|
||||||
runParser integer "9" `shouldBe` Right (9 :: Int)
|
|
||||||
runParser integer "0" `shouldBe` Right (0 :: Int)
|
|
||||||
runParser float "-4.123" `shouldBe` Right (-4.123)
|
|
||||||
runParser float "0.123" `shouldBe` Right 0.123
|
|
||||||
runParser float "123e4" `shouldBe` Right 123e4
|
|
||||||
runParser float "123E4" `shouldBe` Right 123E4
|
|
||||||
runParser float "123e-4" `shouldBe` Right 123e-4
|
|
||||||
runParser float "123e+4" `shouldBe` Right 123e+4
|
|
||||||
runParser float "-1.123e4" `shouldBe` Right (-1.123e4)
|
|
||||||
runParser float "-1.123E4" `shouldBe` Right (-1.123E4)
|
|
||||||
runParser float "-1.123e-4" `shouldBe` Right (-1.123e-4)
|
|
||||||
runParser float "-1.123e+4" `shouldBe` Right (-1.123e+4)
|
|
||||||
runParser float "-1.123e4567" `shouldBe` Right (-1.123e4567)
|
|
||||||
|
|
||||||
it "lexes punctuation" $ do
|
|
||||||
runParser bang "!" `shouldBe` Right '!'
|
|
||||||
runParser dollar "$" `shouldBe` Right '$'
|
|
||||||
runBetween parens "()" `shouldSatisfy` isRight
|
|
||||||
runParser spread "..." `shouldBe` Right "..."
|
|
||||||
runParser colon ":" `shouldBe` Right ":"
|
|
||||||
runParser equals "=" `shouldBe` Right "="
|
|
||||||
runParser at "@" `shouldBe` Right '@'
|
|
||||||
runBetween brackets "[]" `shouldSatisfy` isRight
|
|
||||||
runBetween braces "{}" `shouldSatisfy` isRight
|
|
||||||
runParser pipe "|" `shouldBe` Right "|"
|
|
||||||
|
|
||||||
context "Implementation tests" $ do
|
|
||||||
it "lexes empty block strings" $
|
|
||||||
runParser blockString [r|""""""|] `shouldBe` Right ""
|
|
||||||
it "lexes ampersand" $
|
|
||||||
runParser amp "&" `shouldBe` Right "&"
|
|
||||||
|
|
||||||
runParser :: forall a. Parser a -> Text -> Either (ParseErrorBundle Text Void) a
|
|
||||||
runParser = flip parse ""
|
|
||||||
|
|
||||||
runBetween :: (Parser () -> Parser ()) -> Text -> Either (ParseErrorBundle Text Void) ()
|
|
||||||
runBetween parser = parse (parser $ pure ()) ""
|
|
@ -1,18 +0,0 @@
|
|||||||
{-# LANGUAGE OverloadedStrings #-}
|
|
||||||
module Language.GraphQL.ParserSpec
|
|
||||||
( spec
|
|
||||||
) where
|
|
||||||
|
|
||||||
import Data.Either (isRight)
|
|
||||||
import Language.GraphQL.Parser (document)
|
|
||||||
import Test.Hspec ( Spec
|
|
||||||
, describe
|
|
||||||
, it
|
|
||||||
, shouldSatisfy
|
|
||||||
)
|
|
||||||
import Text.Megaparsec (parse)
|
|
||||||
|
|
||||||
spec :: Spec
|
|
||||||
spec = describe "Parser" $
|
|
||||||
it "accepts BOM header" $
|
|
||||||
parse document "" "\xfeff{foo}" `shouldSatisfy` isRight
|
|
164
tests/Test/FragmentSpec.hs
Normal file
164
tests/Test/FragmentSpec.hs
Normal file
@ -0,0 +1,164 @@
|
|||||||
|
{-# LANGUAGE OverloadedStrings #-}
|
||||||
|
{-# LANGUAGE QuasiQuotes #-}
|
||||||
|
module Test.FragmentSpec
|
||||||
|
( spec
|
||||||
|
) where
|
||||||
|
|
||||||
|
import Data.Aeson (Value(..), object, (.=))
|
||||||
|
import qualified Data.HashMap.Strict as HashMap
|
||||||
|
import Data.List.NonEmpty (NonEmpty(..))
|
||||||
|
import Data.Text (Text)
|
||||||
|
import Language.GraphQL
|
||||||
|
import qualified Language.GraphQL.Schema as Schema
|
||||||
|
import Test.Hspec ( Spec
|
||||||
|
, describe
|
||||||
|
, it
|
||||||
|
, shouldBe
|
||||||
|
, shouldSatisfy
|
||||||
|
, shouldNotSatisfy
|
||||||
|
)
|
||||||
|
import Text.RawString.QQ (r)
|
||||||
|
|
||||||
|
size :: Schema.Resolver IO
|
||||||
|
size = Schema.scalar "size" $ return ("L" :: Text)
|
||||||
|
|
||||||
|
circumference :: Schema.Resolver IO
|
||||||
|
circumference = Schema.scalar "circumference" $ return (60 :: Int)
|
||||||
|
|
||||||
|
garment :: Text -> Schema.Resolver IO
|
||||||
|
garment typeName = Schema.object "garment" $ return
|
||||||
|
[ if typeName == "Hat" then circumference else size
|
||||||
|
, Schema.scalar "__typename" $ return typeName
|
||||||
|
]
|
||||||
|
|
||||||
|
inlineQuery :: Text
|
||||||
|
inlineQuery = [r|{
|
||||||
|
garment {
|
||||||
|
... on Hat {
|
||||||
|
circumference
|
||||||
|
}
|
||||||
|
... on Shirt {
|
||||||
|
size
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}|]
|
||||||
|
|
||||||
|
hasErrors :: Value -> Bool
|
||||||
|
hasErrors (Object object') = HashMap.member "errors" object'
|
||||||
|
hasErrors _ = True
|
||||||
|
|
||||||
|
spec :: Spec
|
||||||
|
spec = describe "Inline fragment executor" $ do
|
||||||
|
it "chooses the first selection if the type matches" $ do
|
||||||
|
actual <- graphql (garment "Hat" :| []) inlineQuery
|
||||||
|
let expected = object
|
||||||
|
[ "data" .= object
|
||||||
|
[ "garment" .= object
|
||||||
|
[ "circumference" .= (60 :: Int)
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
in actual `shouldBe` expected
|
||||||
|
|
||||||
|
it "chooses the last selection if the type matches" $ do
|
||||||
|
actual <- graphql (garment "Shirt" :| []) inlineQuery
|
||||||
|
let expected = object
|
||||||
|
[ "data" .= object
|
||||||
|
[ "garment" .= object
|
||||||
|
[ "size" .= ("L" :: Text)
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
in actual `shouldBe` expected
|
||||||
|
|
||||||
|
it "embeds inline fragments without type" $ do
|
||||||
|
let query = [r|{
|
||||||
|
garment {
|
||||||
|
circumference
|
||||||
|
... {
|
||||||
|
size
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}|]
|
||||||
|
resolvers = Schema.object "garment" $ return [circumference, size]
|
||||||
|
|
||||||
|
actual <- graphql (resolvers :| []) query
|
||||||
|
let expected = object
|
||||||
|
[ "data" .= object
|
||||||
|
[ "garment" .= object
|
||||||
|
[ "circumference" .= (60 :: Int)
|
||||||
|
, "size" .= ("L" :: Text)
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
in actual `shouldBe` expected
|
||||||
|
|
||||||
|
it "evaluates fragments on Query" $ do
|
||||||
|
let query = [r|{
|
||||||
|
... {
|
||||||
|
size
|
||||||
|
}
|
||||||
|
}|]
|
||||||
|
|
||||||
|
actual <- graphql (size :| []) query
|
||||||
|
actual `shouldNotSatisfy` hasErrors
|
||||||
|
|
||||||
|
it "evaluates nested fragments" $ do
|
||||||
|
let query = [r|
|
||||||
|
{
|
||||||
|
...circumferenceFragment
|
||||||
|
}
|
||||||
|
|
||||||
|
fragment circumferenceFragment on Hat {
|
||||||
|
circumference
|
||||||
|
}
|
||||||
|
|
||||||
|
fragment hatFragment on Hat {
|
||||||
|
...circumferenceFragment
|
||||||
|
}
|
||||||
|
|]
|
||||||
|
|
||||||
|
actual <- graphql (circumference :| []) query
|
||||||
|
let expected = object
|
||||||
|
[ "data" .= object
|
||||||
|
[ "circumference" .= (60 :: Int)
|
||||||
|
]
|
||||||
|
]
|
||||||
|
in actual `shouldBe` expected
|
||||||
|
|
||||||
|
it "evaluates fragments defined in any order" $ do
|
||||||
|
let query = [r|
|
||||||
|
{
|
||||||
|
...circumferenceFragment
|
||||||
|
}
|
||||||
|
|
||||||
|
fragment circumferenceFragment on Hat {
|
||||||
|
...hatFragment
|
||||||
|
}
|
||||||
|
|
||||||
|
fragment hatFragment on Hat {
|
||||||
|
circumference
|
||||||
|
}
|
||||||
|
|]
|
||||||
|
|
||||||
|
actual <- graphql (circumference :| []) query
|
||||||
|
let expected = object
|
||||||
|
[ "data" .= object
|
||||||
|
[ "circumference" .= (60 :: Int)
|
||||||
|
]
|
||||||
|
]
|
||||||
|
in actual `shouldBe` expected
|
||||||
|
|
||||||
|
it "rejects recursive" $ do
|
||||||
|
let query = [r|
|
||||||
|
{
|
||||||
|
...circumferenceFragment
|
||||||
|
}
|
||||||
|
|
||||||
|
fragment circumferenceFragment on Hat {
|
||||||
|
...circumferenceFragment
|
||||||
|
}
|
||||||
|
|]
|
||||||
|
|
||||||
|
actual <- graphql (circumference :| []) query
|
||||||
|
actual `shouldSatisfy` hasErrors
|
@ -6,19 +6,13 @@ module Test.KitchenSinkSpec
|
|||||||
|
|
||||||
import qualified Data.Text.IO as Text.IO
|
import qualified Data.Text.IO as Text.IO
|
||||||
import qualified Data.Text.Lazy.IO as Text.Lazy.IO
|
import qualified Data.Text.Lazy.IO as Text.Lazy.IO
|
||||||
import qualified Language.GraphQL.Encoder as Encoder
|
import qualified Data.Text.Lazy as Lazy (Text)
|
||||||
import qualified Language.GraphQL.Parser as Parser
|
import qualified Language.GraphQL.AST.Encoder as Encoder
|
||||||
|
import qualified Language.GraphQL.AST.Parser as Parser
|
||||||
import Paths_graphql (getDataFileName)
|
import Paths_graphql (getDataFileName)
|
||||||
import Test.Hspec ( Spec
|
import Test.Hspec (Spec, describe, it)
|
||||||
, describe
|
import Test.Hspec.Megaparsec (parseSatisfies)
|
||||||
, it
|
import Text.Megaparsec (parse)
|
||||||
)
|
|
||||||
import Test.Hspec.Expectations ( expectationFailure
|
|
||||||
, shouldBe
|
|
||||||
)
|
|
||||||
import Text.Megaparsec ( errorBundlePretty
|
|
||||||
, parse
|
|
||||||
)
|
|
||||||
import Text.RawString.QQ (r)
|
import Text.RawString.QQ (r)
|
||||||
|
|
||||||
spec :: Spec
|
spec :: Spec
|
||||||
@ -26,17 +20,12 @@ spec = describe "Kitchen Sink" $ do
|
|||||||
it "minifies the query" $ do
|
it "minifies the query" $ do
|
||||||
dataFileName <- getDataFileName "tests/data/kitchen-sink.graphql"
|
dataFileName <- getDataFileName "tests/data/kitchen-sink.graphql"
|
||||||
minFileName <- getDataFileName "tests/data/kitchen-sink.min.graphql"
|
minFileName <- getDataFileName "tests/data/kitchen-sink.min.graphql"
|
||||||
actual <- Text.IO.readFile dataFileName
|
|
||||||
expected <- Text.Lazy.IO.readFile minFileName
|
expected <- Text.Lazy.IO.readFile minFileName
|
||||||
|
|
||||||
either
|
shouldNormalize Encoder.minified dataFileName expected
|
||||||
(expectationFailure . errorBundlePretty)
|
|
||||||
(flip shouldBe expected . Encoder.document Encoder.minified)
|
|
||||||
$ parse Parser.document dataFileName actual
|
|
||||||
|
|
||||||
it "pretty prints the query" $ do
|
it "pretty prints the query" $ do
|
||||||
dataFileName <- getDataFileName "tests/data/kitchen-sink.graphql"
|
dataFileName <- getDataFileName "tests/data/kitchen-sink.graphql"
|
||||||
actual <- Text.IO.readFile dataFileName
|
|
||||||
let expected = [r|query queryName($foo: ComplexType, $site: Site = MOBILE) {
|
let expected = [r|query queryName($foo: ComplexType, $site: Site = MOBILE) {
|
||||||
whoever123is: node(id: [123, 456]) {
|
whoever123is: node(id: [123, 456]) {
|
||||||
id
|
id
|
||||||
@ -70,7 +59,11 @@ fragment frag on Friend {
|
|||||||
}
|
}
|
||||||
|]
|
|]
|
||||||
|
|
||||||
either
|
shouldNormalize Encoder.pretty dataFileName expected
|
||||||
(expectationFailure . errorBundlePretty)
|
|
||||||
(flip shouldBe expected . Encoder.document Encoder.pretty)
|
shouldNormalize :: Encoder.Formatter -> FilePath -> Lazy.Text -> IO ()
|
||||||
$ parse Parser.document dataFileName actual
|
shouldNormalize formatter dataFileName expected = do
|
||||||
|
actual <- Text.IO.readFile dataFileName
|
||||||
|
parse Parser.document dataFileName actual `parseSatisfies` condition
|
||||||
|
where
|
||||||
|
condition = (expected ==) . Encoder.document formatter
|
||||||
|
@ -26,6 +26,7 @@ import Control.Monad.Trans.Except (throwE)
|
|||||||
import Data.Maybe (catMaybes)
|
import Data.Maybe (catMaybes)
|
||||||
import Data.Text (Text)
|
import Data.Text (Text)
|
||||||
import Language.GraphQL.Trans
|
import Language.GraphQL.Trans
|
||||||
|
import qualified Language.GraphQL.Type as Type
|
||||||
|
|
||||||
-- * Data
|
-- * Data
|
||||||
-- See https://github.com/graphql/graphql-js/blob/master/src/__tests__/starWarsData.js
|
-- See https://github.com/graphql/graphql-js/blob/master/src/__tests__/starWarsData.js
|
||||||
@ -190,8 +191,8 @@ getDroid' _ = empty
|
|||||||
getFriends :: Character -> [Character]
|
getFriends :: Character -> [Character]
|
||||||
getFriends char = catMaybes $ liftA2 (<|>) getDroid getHuman <$> friends char
|
getFriends char = catMaybes $ liftA2 (<|>) getDroid getHuman <$> friends char
|
||||||
|
|
||||||
getEpisode :: Alternative f => Int -> f Text
|
getEpisode :: Int -> Maybe (Type.Wrapping Text)
|
||||||
getEpisode 4 = pure "NEWHOPE"
|
getEpisode 4 = pure $ Type.Named "NEWHOPE"
|
||||||
getEpisode 5 = pure "EMPIRE"
|
getEpisode 5 = pure $ Type.Named "EMPIRE"
|
||||||
getEpisode 6 = pure "JEDI"
|
getEpisode 6 = pure $ Type.Named "JEDI"
|
||||||
getEpisode _ = empty
|
getEpisode _ = empty
|
||||||
|
@ -11,52 +11,48 @@ module Test.StarWars.Schema
|
|||||||
import Control.Monad.Trans.Except (throwE)
|
import Control.Monad.Trans.Except (throwE)
|
||||||
import Control.Monad.Trans.Class (lift)
|
import Control.Monad.Trans.Class (lift)
|
||||||
import Control.Monad.IO.Class (MonadIO(..))
|
import Control.Monad.IO.Class (MonadIO(..))
|
||||||
import Data.List.NonEmpty (NonEmpty((:|)))
|
import Data.List.NonEmpty (NonEmpty(..))
|
||||||
import Language.GraphQL.Schema ( Schema
|
import Data.Maybe (catMaybes)
|
||||||
, Resolver
|
|
||||||
, Argument(..)
|
|
||||||
, Value(..)
|
|
||||||
)
|
|
||||||
import qualified Language.GraphQL.Schema as Schema
|
import qualified Language.GraphQL.Schema as Schema
|
||||||
import Language.GraphQL.Trans
|
import Language.GraphQL.Trans
|
||||||
import Language.GraphQL.Type
|
import qualified Language.GraphQL.Type as Type
|
||||||
import Test.StarWars.Data
|
import Test.StarWars.Data
|
||||||
|
|
||||||
-- * Schema
|
|
||||||
-- See https://github.com/graphql/graphql-js/blob/master/src/__tests__/starWarsSchema.js
|
-- See https://github.com/graphql/graphql-js/blob/master/src/__tests__/starWarsSchema.js
|
||||||
|
|
||||||
schema :: MonadIO m => Schema m
|
schema :: MonadIO m => NonEmpty (Schema.Resolver m)
|
||||||
schema = hero :| [human, droid]
|
schema = hero :| [human, droid]
|
||||||
|
|
||||||
hero :: MonadIO m => Resolver m
|
hero :: MonadIO m => Schema.Resolver m
|
||||||
hero = Schema.objectA "hero" $ \case
|
hero = Schema.objectA "hero" $ \case
|
||||||
[] -> character artoo
|
[] -> character artoo
|
||||||
[Argument "episode" (ValueEnum "NEWHOPE")] -> character $ getHero 4
|
[Schema.Argument "episode" (Schema.Enum "NEWHOPE")] -> character $ getHero 4
|
||||||
[Argument "episode" (ValueEnum "EMPIRE" )] -> character $ getHero 5
|
[Schema.Argument "episode" (Schema.Enum "EMPIRE" )] -> character $ getHero 5
|
||||||
[Argument "episode" (ValueEnum "JEDI" )] -> character $ getHero 6
|
[Schema.Argument "episode" (Schema.Enum "JEDI" )] -> character $ getHero 6
|
||||||
_ -> ActionT $ throwE "Invalid arguments."
|
_ -> ActionT $ throwE "Invalid arguments."
|
||||||
|
|
||||||
human :: MonadIO m => Resolver m
|
human :: MonadIO m => Schema.Resolver m
|
||||||
human = Schema.wrappedObjectA "human" $ \case
|
human = Schema.wrappedObjectA "human" $ \case
|
||||||
[Argument "id" (ValueString i)] -> do
|
[Schema.Argument "id" (Schema.String i)] -> do
|
||||||
humanCharacter <- lift $ return $ getHuman i >>= Just
|
humanCharacter <- lift $ return $ getHuman i >>= Just
|
||||||
case humanCharacter of
|
case humanCharacter of
|
||||||
Nothing -> return Null
|
Nothing -> return Type.Null
|
||||||
Just e -> Named <$> character e
|
Just e -> Type.Named <$> character e
|
||||||
_ -> ActionT $ throwE "Invalid arguments."
|
_ -> ActionT $ throwE "Invalid arguments."
|
||||||
|
|
||||||
droid :: MonadIO m => Resolver m
|
droid :: MonadIO m => Schema.Resolver m
|
||||||
droid = Schema.objectA "droid" $ \case
|
droid = Schema.objectA "droid" $ \case
|
||||||
[Argument "id" (ValueString i)] -> character =<< liftIO (getDroid i)
|
[Schema.Argument "id" (Schema.String i)] -> character =<< liftIO (getDroid i)
|
||||||
_ -> ActionT $ throwE "Invalid arguments."
|
_ -> ActionT $ throwE "Invalid arguments."
|
||||||
|
|
||||||
character :: MonadIO m => Character -> ActionT m [Resolver m]
|
character :: MonadIO m => Character -> ActionT m [Schema.Resolver m]
|
||||||
character char = return
|
character char = return
|
||||||
[ Schema.scalar "id" $ return $ id_ char
|
[ Schema.scalar "id" $ return $ id_ char
|
||||||
, Schema.scalar "name" $ return $ name char
|
, Schema.scalar "name" $ return $ name char
|
||||||
, Schema.wrappedObject "friends"
|
, Schema.wrappedObject "friends"
|
||||||
$ traverse character $ List $ Named <$> getFriends char
|
$ traverse character $ Type.List $ Type.Named <$> getFriends char
|
||||||
, Schema.enum "appearsIn" $ return $ foldMap getEpisode $ appearsIn char
|
, Schema.wrappedScalar "appearsIn" $ return . Type.List
|
||||||
|
$ catMaybes (getEpisode <$> appearsIn char)
|
||||||
, Schema.scalar "secretBackstory" $ secretBackstory char
|
, Schema.scalar "secretBackstory" $ secretBackstory char
|
||||||
, Schema.scalar "homePlanet" $ return $ either mempty homePlanet char
|
, Schema.scalar "homePlanet" $ return $ either mempty homePlanet char
|
||||||
, Schema.scalar "__typename" $ return $ typeName char
|
, Schema.scalar "__typename" $ return $ typeName char
|
||||||
|
Reference in New Issue
Block a user