Nova integration for egql GraphQL.
Provides a controller for handling GraphQL queries over HTTP, a GraphiQL IDE endpoint, and a Nova plugin for injecting request context into GraphQL execution.
{deps, [
{egql_nova, {git, "https://github.com/novaframework/egql_nova.git", {branch, "main"}}}
]}.Create a .graphql schema file and resource modules following the egql documentation.
type Query {
hello(name: String = "World"): String!
}-module(query_resource).
-export([execute/4]).
execute(_Ctx, _Obj, <<"hello">>, #{<<"name">> := Name}) ->
{ok, <<"Hello, ", Name/binary, "!">>}.init_schema() ->
{ok, SchemaData} = file:read_file(schema_path()),
Mapping = #{
scalars => #{default => scalar_resource},
interfaces => #{default => resolve_resource},
objects => #{
'Query' => query_resource,
'Mutation' => mutation_resource
}
},
ok = graphql:load_schema(Mapping, SchemaData),
ok = graphql:insert_schema_definition(
{root, #{query => 'Query', mutation => 'Mutation', interfaces => []}}
),
ok = graphql:validate_schema().routes(_Env) ->
[#{
prefix => "/api",
security => false,
routes => [
{"/graphql", fun egql_nova_controller:graphql/1, #{methods => [post]}},
{"/graphql", fun egql_nova_controller:graphiql/1, #{methods => [get]}}
]
}].curl -X POST http://localhost:8080/api/graphql \
-H "Content-Type: application/json" \
-d '{"query": "{ hello(name: \"Erlang\") }"}'{"data": {"hello": "Hello, Erlang!"}}Use egql_nova_plug to inject request context (auth, session, etc.) into GraphQL execution:
%% sys.config
{nova, [
{plugins, [
{pre_request, nova_request_plugin, #{decode_json_body => true}},
{pre_request, egql_nova_plug, #{
context_fun => fun my_auth:build_context/1
}}
]}
]}-module(my_auth).
-export([build_context/1]).
build_context(Req) ->
Token = cowboy_req:header(<<"authorization">>, Req, undefined),
case verify_token(Token) of
{ok, User} -> #{current_user => User};
_ -> #{}
end.The context is then available in your resource modules:
execute(#{current_user := User}, _Obj, <<"me">>, _Args) ->
{ok, User};
execute(#{current_user := undefined}, _Obj, <<"me">>, _Args) ->
{error, <<"Unauthorized">>}.Visit GET /api/graphql in your browser for the GraphiQL IDE.
MIT