Skip to content

Instantly share code, notes, and snippets.

@MBehtemam
Created December 1, 2018 08:46
Show Gist options
  • Save MBehtemam/b16de7fed3396124eaf2ef0b7020fa69 to your computer and use it in GitHub Desktop.
Save MBehtemam/b16de7fed3396124eaf2ef0b7020fa69 to your computer and use it in GitHub Desktop.
GraphQL Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using GraphQL;
using GraphQL.Types;
using TodoAPI.Models;
using TodoAPI.Data;
namespace TodoAPI.Controllers
{
[Route("graphql")]
public class GraphQLController : Controller
{
private readonly IDocumentExecuter _documentExecuter;
private readonly ISchema _schema;
public GraphQLController(IDocumentExecuter documentExecuter, ISchema schema)
{
_documentExecuter = documentExecuter;
_schema = schema;
}
[HttpPost]
public async Task<IActionResult> Post([FromBody]GraphQLQuery query)
{
if (query == null) { throw new ArgumentNullException(nameof(query)); }
var executionOptions = new ExecutionOptions { Schema = _schema, Query = query.Query };
try
{
var result = await _documentExecuter.ExecuteAsync(executionOptions).ConfigureAwait(false);
if (result.Errors?.Count > 0)
{
return BadRequest(result);
}
return Ok(result);
}
catch (Exception ex)
{
return BadRequest(ex);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment