Created
December 1, 2018 08:46
-
-
Save MBehtemam/b16de7fed3396124eaf2ef0b7020fa69 to your computer and use it in GitHub Desktop.
GraphQL Controller
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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