Coder Social home page Coder Social logo

meir017 / graphqlinq Goto Github PK

View Code? Open in Web Editor NEW

This project forked from giorgi/graphqlinq

0.0 2.0 0.0 326 KB

LINQ to GraphQL - Strongly typed GraphQL queries with LINQ query syntax. No more magic strings and runtime errors.

Home Page: https://www.giorgi.dev/dotnet/introducing-graphqlinq-strongly-typed-graphql-queries-with-linq-to-graphql/

License: Other

C# 96.68% Batchfile 0.13% PowerShell 1.80% Shell 1.40%

graphqlinq's Introduction

GraphQLinq

LINQ to GraphQL - Strongly typed GraphQL queries with LINQ query syntax.

License AppVeyor Coverage Status Ko-Fi

Project Icon

About The Project

GraphQLinq is a .NET tool for generating C# classes from a GraphQL endpoint and a .Net Standard library for writing strongly typed GraphQL queries with LINQ.

With GraphQLinq you will:

  • Write strongly typed queries with LINQ.
  • Have your queries checked by the compiler.
  • Run queries and deserialize JSON response into strongly typed classes in a single method call.
  • View queries generated by LINQ to GraphQL.

Getting Started

Install Scaffolding Tool

Before you starting writing queries, you need to generate classes from GraphQL types. This is done by GraphQLinq.Scaffolding, a .NET tool that is part of this project.

To get the tool, open your favourite command shell and run

dotnet tool install --global --version 1.0.0-beta GraphQLinq.Scaffolding

Running this command will install the GraphQLinq.Scaffolding tool and make it available globally for all projects.

Scaffolding Client Code

Next, navigate to the project where you want to add the classes and scaffold the client code. In this example, I will use the SpaceX GraphQL Api so run the following command:

graphqlinq-scaffold https://api.spacex.land/graphql -o SpaceX -n SpaceX

The o option specifies the output directory for generated classes, and n specifies the namespace of the classes.

Scaffolding

Install GraphQLinq NuGet Package

Before writing the queries, you need to install the LINQ to GraphQL client library from NuGet. Run the following command to install it in the current project:

dotnet add package GraphQLinq.Client --version 1.0.0-beta

Running GraphQL Queries with LINQ

The scaffolding tool generates classes for types available in the GraphQL type system and a QueryContext class that serves as an entry point for running the queries. GraphQLinq supports running different kinds of queries.

Query all Primitive Properties of a Type

To query all properties of a type, simply run a query like this:

var spaceXContext = new QueryContext();

var company = spaceXContext.Company().ToItem();

RenderCompanyDetails(company);

This will query all primitive and string properties of Company, but it won't query nested properties or collection type properties. Here is the output of the code snippet:

┌───────────┬──────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ Property  │ Value                                                                                                    │
├───────────┼──────────────────────────────────────────────────────────────────────────────────────────────────────────┤
│ Name      │ SpaceX                                                                                                   │
│ Ceo       │ Elon Musk                                                                                                │
│ Summary   │ SpaceX designs, manufactures and launches advanced rockets and spacecraft. The company was founded in    │
│           │ 2002 to revolutionize space technology, with the ultimate goal of enabling people to live on other       │
│           │ planets.                                                                                                 │
│ Founded   │ 2002                                                                                                     │
│ Founder   │ Elon Musk                                                                                                │
│ Employees │ 7000                                                                                                     │
└───────────┴──────────────────────────────────────────────────────────────────────────────────────────────────────────┘

Query Specific Properties

If you want to query specific properties, including a navigation property, you can specify it with the Select method. You either map the projection to an existing type or an anonymous object (Headquarters is a nested property):

var companySummaryAnonymous = spaceXContext.Company().Select(c => new { c.Ceo, c.Name, c.Headquarters }).ToItem();

//Use data class to select specific properties
var companySummary = spaceXContext.Company().Select(c => new CompanySummary
{
    Ceo = c.Ceo,
    Name = c.Name,
    Headquarters = c.Headquarters
}).ToItem();

RenderCompanySummary(companySummary);

This will result in the following output:

┌──────────────┬─────────────────┐
│ Property     │ Value           │
├──────────────┼─────────────────┤
│ Name         │ SpaceX          │
│ Ceo          │ Elon Musk       │
│ Headquarters │ ┌─────────────┐ │
│              │ │ California  │ │
│              │ │ Hawthorne   │ │
│              │ │ Rocket Road │ │
│              │ └─────────────┘ │
└──────────────┴─────────────────┘

Include Navigation Properties

You can also query navigation properties using the Include method. You can include several properties if you need, and you can also Include nested navigation properties:

var companyWithHeadquartersAndLinks = spaceXContext.Company()
                                            .Include(info => info.Headquarters)
                                            .Include(info => info.Links).ToItem();

RenderCompanyDetailsAndLinks(companyWithHeadquartersAndLinks);

Pass Parameters to Queries and Compose Queries

If the query has parameters, the generated method will have a parameter for each query parameter.

This code will query for all Missions that included Orbital ATK as a manufacturer. It also builds a new query over the existing one that includes Payloads in the result.

var missionsQuery = spaceXContext.Missions(new MissionsFind { Manufacturer = "Orbital ATK" }, null, null)
                                 .Include(mission => mission.Manufacturers);
var missions = missionsQuery.ToList();

RenderMissions(missions);

var missionsWithPayloads = missionsQuery.Include(mission => mission.Payloads).ToList();

RenderMissions(missionsWithPayloads, true);

Include Multiple Levels of Navigation Properties

The Include method allows quering for multi-level nested properties too. For example, here is how to query for Launches and include Rocket's second stage payload manufacturer:

//Launch_date_unix and Static_fire_date_unix need custom converter
spaceXContext.ContractResolver = new SpaceXContractResolver();

var launches = spaceXContext.Launches(null, 10, 0, null, null)
                            .Include(launch => launch.Links)
                            .Include(launch => launch.Rocket)
                            .Include(launch => launch.Rocket.Second_stage.Payloads.Select(payload => payload.Manufacturer))
                            .ToList();

RenderLaunches(launches);

View Generated Query

You can view the GraphQL query and variables by using the Query and Variables property of the GraphQuery class. The ToString() method of the GraphQuery class returns the query and the variables combined:

var missionsQuery = spaceXContext.Missions(new MissionsFind { Manufacturer = "Orbital ATK" }, null, null)
                                 .Include(mission => mission.Manufacturers);

var query = missionsQuery.Query;
var fullQuery = missionsQuery.ToString();

If you run the above code query will be equal to

query ($find: MissionsFind) { result: missions (find: $find) { 
  description
  id
  name
  twitter
  website
  wikipedia
  manufacturers
 }}

and the content of fullQuery will be:

{"query":"query ($find: MissionsFind) { result: missions (find: $find) { 
  description
  id
  name
  twitter
  website
  wikipedia
  manufacturers
 }}","variables":{"find":{"manufacturer":"Orbital ATK"}}}

Roadmap

See the open issues for a list of proposed features and known issues.

Contributing

If you encounter a bug or have a feature request, please use the Issue Tracker. The project is also open to contributions, so feel free to fork the project and open pull requests.

License

Copyright © Giorgi Dalakishvili

Distributed under the Apache License. See License for more information.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.