- Notifications
You must be signed in to change notification settings - Fork75
FSharp implementation of Facebook GraphQL query language.
License
fsprojects/FSharp.Data.GraphQL
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
F# implementation of FacebookGraphQL query language specification.
Type the following commands to install the template for creating web applications:
From GitHub:dotnet new -i "FSharp.Data.GraphQL::2.0.0-ci-*" --nuget-source "https://nuget.pkg.github.com/fsprojects/index.json"
From NuGet:dotnet new -i "FSharp.Data.GraphQL::2.0.0"
openFSharp.Data.GraphQLopenFSharp.Data.GraphQL.TypestypePerson={ FirstName:string LastName:string}// Define GraphQL typeletPersonType= Define.Object( name="Person", fields=[// Property resolver will be auto-generated Define.AutoField("firstName", StringType)// Asynchronous explicit member resolver Define.AsyncField("lastName", StringType, resolve=fun context person->async{return person.LastName})])// Include person as a root query of a schemaletschema= Schema(query= PersonType)// Create an Exector for the schemaletexecutor= Executor(schema)// Retrieve person dataletjohnSnow={ FirstName="John"; LastName="Snow"}letreply= executor.AsyncExecute(Parser.parse"{ firstName, lastName }", johnSnow)|> Async.RunSynchronously// #> { data: { "firstName", "John", "lastName", "Snow" } }
It's type safe. Things like invalid fields or invalid return types will be checked at compile time.
See theAspNetCore/README.md
Go to theGraphiQL sample directory. In order to run it, build and run theStar Wars API sample project with Debug settings - this will create a Giraffe server compatible with the GraphQL spec, running on port 8086. Then what you need is to run node.js graphiql frontend. To do so, runnpm i
to get all dependencies, and then runnpm run serve | npm run dev
- this will start a webpack server running onhttp://localhost:8090/ . Visit this link, and GraphiQL editor should appear. You may try it by applying following query:
{hero(id:"1000") {id,name,appearsIn,homePlanet,friends {...onHuman {name }...onDroid {name } } }}
Thestream
directive now has additional features, like batching (buffering) by interval and/or batch size. To make it work, a custom stream directive must be placed inside theSchemaConfig.Directives
list, this custom directive containing two optional arguments calledinterval
andpreferredBatchSize
:
letcustomStreamDirective=letargs=[| Define.Input("interval", Nullable IntType, defaultValue= Some2000, description="An optional argument used to buffer stream results.") Define.Input("preferredBatchSize", Nullable IntType, defaultValue= None, description="An optional argument used to buffer stream results.")|]{ StreamDirectivewith Args= args}letschemaConfig={ SchemaConfig.Defaultwith Directives=[ IncludeDirective SkipDirective DeferDirective customStreamDirective LiveDirective]}
This boilerplate code can be easily reduced with a built-in implementation:
letstreamOptions={ Interval= Some2000; PreferredBatchSize= None}letschemaConfig= SchemaConfig.DefaultWithBufferedStream(streamOptions)
Thelive
directive is now supported by the server component. To support live queries, each field of each type of the schema needs to be configured as a live field. This is done by usingILiveFieldSubscription
andILiveQuerySubscriptionProvider
, which can be configured in theSchemaConfig
:
typeILiveFieldSubscription=interfaceabstractmemberIdentity :obj->objabstractmemberTypeName :stringabstractmemberFieldName :stringendandILiveFieldSubscription<'Object,'Identity>=interfaceinherit ILiveFieldSubscriptionabstractmemberIdentity :'Object->'IdentityendandILiveFieldSubscriptionProvider=interfaceabstractmemberHasSubscribers :string->string->boolabstractmemberIsRegistered :string->string->boolabstractmemberAsyncRegister :ILiveFieldSubscription->Async<unit>abstractmemberTryFind :string->string->ILiveFieldSubscriptionoptionabstractmemberAdd :obj->string->string->IObservable<obj>abstractmemberAsyncPublish<'T>:string->string->'T->Async<unit>end
To set a field as a live field, call theRegister
extension method. Each subscription needs to know an object identity, so it must be configured on the Identity function of theILiveFieldSubscription
. Also, the name of the Type and the field inside theObjectDef
needs to be passed along:
letschemaConfig= SchemaConfig.Defaultletschema= Schema(root, config= schemaConfig)letsubscription={ Identity=fun(x: Human)-> x.Id TypeName="Hero" FieldName="name"}schemaConfig.LiveFieldSubscriptionProvider.Register subscription
With that, the field name of the hero is now able to go live, being updated to clients whenever it is queried with thelive
directive. To push updates to subscribers, just call Publish method, passing along the type name, the field name and the updated object:
letupdatedHero={ herowith Name="Han Solo - Test"}schemaConfig.LiveFieldSubscriptionProvider.Publish"Hero""name" updatedHero
Our client library now has a completely redesigned type provider. To start using it, you will first need access to the introspection schema for the server you are trying to connect. This can be done with the provider in one of two ways:
- Provide the URL to the desired GraphQL server (without any custom HTTP headers required). The provider will access the server, send an Introspection Query, and use the schema to provide the types used to make queries.
typeMyProvider= GraphQLProvider<"http://some.graphqlserver.development.org">
- Provide an introspection json file to be used by the provider. Beware though that the introspection json should have all fields required by the provider. You can get the correct fields by runningour standard introspection query on the desired server and saving it into a file on the same path as the project using the provider:
typeMyProvider= GraphQLProvider<"swapi_schema.json">
From now on, you can start running queries and mutations:
letoperation= MyProvider.Operation<"""query q { hero (id: "1001") { name appearsIn homePlanet friends { ... on Human { name homePlanet } ... on Droid { name primaryFunction } } } }""">()// This is a instance of GraphQLProviderRuntimeContext.// You can use it to provider a runtime URL to access your server,// and optionally additional HTTP headers (auth headers, for example).// If you use a local introspection file to parse the schema,// The runtime context is mandatory.letruntimeContext={ ServerUrl="http://some.graphqlserver.production.org" CustomHttpHeaders= None}letresult= operation.Run(runtimeContext)// Query result objects have pretty-printing and structural equality.printfn"Data:%A\n" result.Dataprintfn"Errors:%A\n" result.Errorsprintfn"Custom data:%A\n" result.CustomData// Response from the server:// Data: Some// {Hero = Some// {Name = Some "Darth Vader";// AppearsIn = [|NewHope; Empire; Jedi|];// HomePlanet = Some "Tatooine";// Friends = [|Some {Name = Some "Wilhuff Tarkin";// HomePlanet = <null>;}|];};}// Errors: <null>// Custom data: map [("documentId", 1221427401)]
For more information about how to use the client provider, see theexamples folder.
You can create and use middleware on top of theExecutor<'Root>
object.
The query execution process through the use of the Executor involves three phases:
Schema compile phase: this phase happens when the
Executor<'Root>
class is instantiated. In this phase, the Schema map of types is used to build a field execute map, which contains all field definitions alongside their field resolution functions. This map is used later on in the planning and execution phases to retrieve the values of the queried fields of the schema.Operation planning phase: this phase happens before running a query that has no execution plan. This phase is responsible for analyzing the AST document generated by the query, and building an ExecutionPlan to execute it.
Operation execution phase: this phase is the phase that executes the query. It needs an execution plan, so, it commonly happens after the operation planning phase.
All the phases wrap the needed data to do the phase job inside a context object. They are expressed internally by functions:
letinternalcompileSchema(ctx:SchemaCompileContext):unit=// ...letinternalplanOperation(ctx:PlanningContext):ExecutionPlan=// ...letinternalexecuteOperation(ctx:ExecutionContext):AsyncVal<GQLResponse>=// ...
That way, in the compile schema phase, the schema is modified and execution maps are generated inside theSchemaCompileContext
object. During the operation planning phase, values of thePlanningContext
object are used to generate an execution plan, and finally, this plan is passed alongside other values in theExecutionContext
object to the operation execution phase, which finally uses them to execute the query and generate aGQLResponse
.
With that being said, a middleware can be used to intercept each phase and customize them as necessary. Each middleware must be implemented as a function with a specific signature, and wrapped inside anIExecutorMiddleware
interface:
typeSchemaCompileMiddleware= SchemaCompileContext->(SchemaCompileContext-> unit)-> unittypeOperationPlanningMiddleware= PlanningContext->(PlanningContext-> ExecutionPlan)-> ExecutionPlantypeOperationExecutionMiddleware= ExecutionContext->(ExecutionContext-> AsyncVal<GQLResponse>)-> AsyncVal<GQLResponse>typeIExecutorMiddleware=abstractCompileSchema :SchemaCompileMiddlewareoptionabstractPlanOperation :OperationPlanningMiddlewareoptionabstractExecuteOperationAsync :OperationExecutionMiddlewareoption
Optionally, for ease of implementation, concrete class to derive from can be used, receiving only the optional sub-middleware functions in the constructor:
typeExecutorMiddleware(?compile,?plan,?execute)=interface IExecutorMiddlewarewithmember_.CompileSchema= compilemember_.PlanOperation= planmember_.ExecuteOperationAsync= execute
Each of the middleware functions act like an intercept function, with two parameters: the context of the phase, the function of the next middleware (or the actual phase itself, which is the last to run), and the return value. Those functions can be passed as an argument to the constructor of theExecutor<'Root>
object:
letmiddleware=[ ExecutorMiddleware(compileFn, planningFn, executionFn)]letexecutor= Executor(schema, middleware)
A simple example of a practical middleware can be one that measures the time needed to plan a query. The results of which get returned as part of theMetadata
of the planning context. TheMetadata
object is aMap<string, obj>
implementation that acts like a bag of information to be passed through each phase, until it is returned inside theGQLResponse
object. You can use it to thread custom information through middleware:
letplanningMiddleware(ctx:PlanningContext)(next:PlanningContext->ExecutionPlan)=letwatch= Stopwatch() watch.Start()letresult= next ctx watch.Stop()letmetadata= result.Metadata.Add("planningTime", watch.ElapsedMilliseconds){ resultwith Metadata= metadata}
There are some built-in middleware insideFSharp.Data.GraphQL.Server.Middleware
package:
This middleware can be used to place weights on fields of the schema. Those weighted fields can now be used to protect the server from complex queries that could otherwise be used in DDOS attacks.
When defining a field, we use the extension methodWithQueryWeight
to place a weight on it:
letresolveFn(h:Human)= h.Friends|> List.map getCharacter|> List.toSeqletfield= Define.Field("friends", ListOf(Nullable CharacterType), resolve= resolveFn).WithQueryWeight(0.5)
Then we define the threshold middleware for the Executor. If we execute a query that ask for "friends of friends" in a recursive way, the executor will only accept nesting them 4 times before the query exceeds the weight threshold of 2.0:
letmiddleware=[ Define.QueryWeightMiddleware(2.0)]
This middleware can be used to automatically generate a filter for list fields inside an object of the schema. This filter can be passed as an argument for the field on the query, and recovered in theResolveFieldContext
argument of the resolve function of the field.
For example, we can create a middleware for filtering list fields of anHuman
object, that are of the typeCharacter option
:
letmiddleware=[ Define.ObjectListFilterMiddleware<Human, Character option>()]
The filter argument is an object that is mapped through a JSON definition inside anfilter
argument on the field. A simple example would be filtering friends of a hero that have their names starting with the letter A:
queryTestQuery {hero(id:"1000") {idnameappearsInhomePlanetfriends (filter : {name_starts_with:"A" }) {idname } }}
Also you can applynot
operator like this:
queryTestQuery {hero(id:"1000") {idnameappearsInhomePlanetfriends (filter : {not : {name_starts_with:"A" } }) {idname } }}
And combine filters withand
andor
operators like this:
queryTestQuery {hero(id:"1000") {idnameappearsInhomePlanetfriends (filter : {or : [{name_starts_with:"A"}, {name_starts_with:"B" }]}) {idname } }}
This filter is mapped by the middleware inside anObjectListFilter
definition:
typeFieldFilter<'Val>={ FieldName:string Value:'Val}typeObjectListFilter=| AndofObjectListFilter*ObjectListFilter| OrofObjectListFilter*ObjectListFilter| NotofObjectListFilter| EqualsofFieldFilter<System.IComparable>| GreaterThanofFieldFilter<System.IComparable>| LessThanofFieldFilter<System.IComparable>| StartsWithofFieldFilter<string>| EndsWithofFieldFilter<string>| ContainsofFieldFilter<string>| FilterFieldofFieldFilter<ObjectListFilter>
And the value recovered by the filter in the query is usable in theResolveFieldContext
of the resolve function of the field. To easily access it, you can use the extension methodFilter
, which returns anObjectListFilter voption
(it does not have a value if the object doesn't implement a list with the middleware generic definition, or if the user didn't provide a filter input).
Define.Field("friends", ListOf(Nullable CharacterType), resolve=fun ctx(d: Droid)-> ctx.Filter|> printfn"Droid friends filter:%A" d.Friends|> List.map getCharacter|> List.toSeq)
By retrieving this filter from the field resolution context, it is possible to use client code to customize the query to run against a database, for example, and extend your GraphQL API features.
This middleware can be used to quickly allow your schema fields to be able to be queried with alive
directive, assuming that all of them have an identity property name that can be discovered by a function,IdentityNameResolver
:
/// A function that resolves an identity name for a schema object, based on a object definition of it.typeIdentityNameResolver= ObjectDef-> string
For example, if all of our schema objects have an identity field namedId
, we could use our middleware like this:
letschema= Schema(query= queryType)letmiddleware=[ Define.LiveQueryMiddleware(fun _->"Id")]letexecutor= Executor(schema, middleware)
TheIdentityNameResolver
is optional, though. If no resolver function is provided, this default implementation of is used. Also, notifications to subscribers must be done viaPublish
ofILiveFieldSubscriptionProvider
, like explained above.
You can use extension methods provided by theFSharp.Data.GraphQL.Shared
package to help building your own middleware. When making a middleware, often you will need to modify schema definitions to add features to the schema defined by the user code. TheObjectListFilter
middleware is an example, where all fields that implements lists of a certain type needs to be modified, by accepting an argument calledfilter
.
As field definitions are immutable by default, generating copies of them with improved features can be hard work sometimes. This is where the extension methods can help: for example, if you need to add an argument to an already defined field inside the schema compile phase, you can use the methodWithArgs
of theFieldDef<'Val>
interface:
letfield:FieldDef<'Val>=// Search for field inside ISchemaletarg:Define.Input("id",StringType)letfieldWithArg= field.WithArgs([ arg])
To see the complete list of extensions used to augment definitions, you can take a look at theTypeSystemExtensions
module contained in theFSharp.Data.GraphQL.Shared
package.
About
FSharp implementation of Facebook GraphQL query language.
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Uh oh!
There was an error while loading.Please reload this page.