使用 GraphQL
语言支持
排序方式:
hello world GraphQL 结构和使用 sangria
的查询的示例:
英:An example of a hello world GraphQL schema and query with sangria
:
import sangria.schema._import sangria.execution._import sangria.macros._
val QueryType = ObjectType("Query", fields[Unit, Unit]( Field("hello", StringType, resolve = _ ⇒ "Hello world!")))
val schema = Schema(QueryType)
val query = graphql"{ hello }"
Executor.execute(schema, query) map println
使用 caliban
的简单 GraphQL 结构和查询的示例:
英:An example of a simple GraphQL schema and query with caliban
:
import caliban._import caliban.schema.Schema.auto._
// schemacase class Query(hello: String)
// resolverval resolver = RootResolver(Query("Hello world!"))
val api = graphQL(resolver)
for { interpreter <- api.interpreter result <- interpreter.execute("{ hello }")} yield result
定义 GraphQL 查询并使用 caliban
运行它的示例:
英:An example of defining a GraphQL query and running it with caliban
:
// define your query using Scalaval query: SelectionBuilder[RootQuery, List[CharacterView]] = Query.characters { (Character.name ~ Character.nicknames ~ Character.origin) .mapN(CharacterView) }
import sttp.client3._// run the query and get the result already parsed into a case classval result = query.toRequest(uri"http://someUrl").send(HttpClientSyncBackend()).body
用于快速、安全、轻松地构建 GraphQL 结构/类型的 Swift 库。
用于使用零样板编写声明式、类型安全的 GraphQL API 的 Swift 库。
使用 GraphQL 和 Apollo 在 SwiftUI 中编写声明式、类型安全和数据驱动应用的工具
SwiftGraphQL 是一个 Swift 代码生成器和一个轻量级 GraphQL 客户端。它允许你使用 Swift 创建查询,并保证你创建的每个查询都是有效的。
英:SwiftGraphQL is a Swift code generator and a lightweight GraphQL client. It lets you create queries using Swift, and guarantees that every query you create is valid.
该库围绕三个核心原则:
英:The library is centered around three core principles:
🚀 如果你的项目可以编译,你的查询就可以工作。🦉 尽可能使用 Swift,而不是 GraphQL。🌳 你的应用模型应该独立于你的结构。
英:🚀 If your project compiles, your queries work. 🦉 Use Swift in favour of GraphQL wherever possible. 🌳 Your application model should be independent of your schema.
以下是 SwiftGraphQL 代码的简短预览
英:Here's a short preview of the SwiftGraphQL code
import SwiftGraphQL
// Define a Swift model.struct Human: Identifiable { let id: String let name: String let homePlanet: String?}
// Create a selection.let human = Selection.Human { Human( id: try $0.id(), name: try $0.name(), homePlanet: try $0.homePlanet() )}
// Construct a query.let query = Selection.Query { try $0.humans(human.list)}
// Perform the query.send(query, to: "http://swift-graphql.heroku.com") { result in if let data = try? result.get() { print(data) // [Human] }}
GraphQLite iOS SDK 是一个可以轻松使用 GraphQL 服务器的工具包。它还提供了其他一些功能,使 iOS 应用开发过程更加轻松。
适用于 iOS 的 GraphQL 客户端,以特定于查询的 Swift 类型返回结果,并与 Xcode 集成以并排显示 Swift 源和 GraphQL,并带有内联验证错误。
适用于 iOS 的 Objective-C GraphQL 客户端。
Rust 的 GraphQL 服务器库
use async_graphql::*; struct Query; #[Object] impl Query { /// Returns the sum of a and b async fn add(&self, a: i32, b: i32) -> i32 { a + b } }
一个 Rust 客户端库,它根据你提供的类型生成查询,验证类型是否与你的结构的形状匹配。
英:A client library for rust that generates queries from types you provide, verifying that the types match the shape of your schema.
它提供 生成器 来从现有 GraphQL 查询引导类型。
英:It provides a generator to bootstrap types from existing GraphQL queries.
使用示例:
英:Usage example:
#[derive(cynic::QueryFragment, Debug)]#[cynic( schema_path = "../schemas/starwars.schema.graphql", query_module = "query_dsl", graphql_type = "Root", argument_struct = "FilmArguments")]struct FilmDirectorQuery { #[arguments(id = &args.id)] film: Option<Film>,}
#[derive(cynic::QueryFragment, Debug)]#[cynic( schema_path = "../schemas/starwars.schema.graphql", query_module = "query_dsl", graphql_type = "Film")]struct Film { title: Option<String>, director: Option<String>,}
#[derive(cynic::FragmentArguments)]struct FilmArguments { id: Option<cynic::Id>,}
fn main() { use cynic::{QueryBuilder, http::ReqwestBlockingExt};
let query = FilmDirectorQuery::build(&FilmArguments { id: Some("ZmlsbXM6MQ==".into()), })
reqwest::blocking::Client::new() .post("https://swapi-graphql.netlify.com/.netlify/functions/index") .run_graphql(query) .unwrap()}
mod query_dsl { cynic::query_dsl!("../schemas/starwars.schema.graphql");}
使用示例
英:Usage example
use gql_client::Client;
#[tokio::main]async fn main() -> Result<(), Box<dyn std::error::Error>> { let endpoint = "https://graphqlzero.almansi.me/api"; let query = r#" query AllPostsQuery { posts { data { id } } } "#;
let client = Client::new(endpoint); let data: AllPosts = client.query::<AllPosts>(query).await.unwrap();
println!("{:?}" data);
Ok(())}
通用 GraphQL R 客户端
运行 tartiflette hello world 脚本:
英:To run a tartiflette hello world script:
pip install tartiflette
然后在 hello.py
中使用以下代码运行 python hello.py
:
英:Then run python hello.py
with this code in hello.py
:
import asynciofrom tartiflette import Engine, Resolver@Resolver("Query.hello")async def resolver_hello(parent, args, ctx, info): return "hello " + args["name"]async def run(): tftt_engine = Engine(""" type Query { hello(name: String): String } """) result = await tftt_engine.execute( query='query { hello(name: "Chuck") }' ) print(result) # {'data': {'hello': 'hello Chuck'}}if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(run())
还有一个不错的 HTTP 封装器。
英:There is also a nice HTTP wrapper.
Strawberry
0Strawberry 是一个 Python 库,用于使用类型提示等现代 Python 功能来实现代码优先 GraphQL 服务器。
这是一个 Strawberry hello world 的示例,首先安装库:
英:Here's an example of a Strawberry hello world, first install the library:
pip install strawberry-graphql
创建一个包含以下内容的 app.py
文件:
英:Create an app.py
file with this content:
import strawberry
@strawberry.typeclass Query: @strawberry.field def hello(self, name: str = "World") -> str: return f"Hello {name}"
schema = strawberry.Schema(query=Query)
然后运行 strawberry server app
,你将在 http://localhost:8000/
上运行一个基本结构服务器。
英:Then run strawberry server app
and you will have a basic schema server
running on http://localhost:8000/
.
Strawberry 还具有 ASGI、Flask 和 Django 视图,并提供数据加载器和跟踪等实用程序。
英:Strawberry also has views for ASGI, Flask and Django and provides utilities like dataloaders and tracing.
Ariadne
Ariadne 是一个 Python 库,用于使用模式优先方法实现 GraphQL 服务器。它支持同步和异步查询执行,附带电池,可解决查询成本验证或性能跟踪等常见 GraphQL 服务器问题,并具有易于扩展或替换的简单 API。
Ariadne 可以使用 pip 安装:
英:Ariadne can be installed with pip:
$ pip install ariadne
最小 "Hello world" 服务器示例:
英:Minimal "Hello world" server example:
from ariadne import ObjectType, gql, make_executable_schemafrom ariadne.asgi import GraphQL
type_defs = gql( """ type Query { hello: String! } """)
query_type = ObjectType("Query")
@query_type.field("hello")def resolve_hello(*_): return "Hello world!"
schema = make_executable_schema(type_defs, query_type)
app = GraphQL(schema, debug=True)
使用 uvicorn 运行服务器:
英:Run the server with uvicorn:
$ pip install uvicorn$ uvicorn example:app
Django Graphbox 快速入门:
英:A Quickstart for Django Graphbox:
安装包:
英:Install the package:
pip install django-graphbox
创建一个新的 Django 项目:
英:Create a new Django project:
django-admin startproject myproject
创建一个新的 Django 应用:
英:Create a new Django app:
cd myprojectpython manage.py startapp myapp
在 myapp/models.py
中定义 Django 模型:
英:Define your Django models in myapp/models.py
:
from django.db import models
class MyModel(models.Model): name = models.CharField(max_length=100)
创建并运行迁移:
英:Create and run migrations:
python manage.py makemigrationspython manage.py migrate
在 myapp/schema.py
中配置和构建你的 GraphQL 结构:
英:Configure and Build your GraphQL Schema in myapp/schema.py
:
from django_graphbox.builder import SchemaBuilderfrom myapp.models import MyModel
builder = SchemaBuilder()builder.add_model(MyModel)
query_class = builder.build_schema_query()mutation_class = builder.build_schema_mutation()
在 myproject/schema.py
中创建一个主结构(在这个主结构中你可以添加自己的查询和变更):
英:Create a main Schema in myproject/schema.py
(In this main schema you can add your own queries and mutations):
import graphenefrom myapp.schema import query_class, mutation_class
class Query(query_class, graphene.ObjectType): pass
class Mutation(mutation_class, graphene.ObjectType): pass
schema = graphene.Schema(query=Query, mutation=Mutation)
将 GraphQL 视图添加到你的 myproject/urls.py
:
英:Add the GraphQL view to your myproject/urls.py
:
from django.urls import pathfrom graphene_file_upload.django import FileUploadGraphQLViewfrom django.views.decorators.csrf import csrf_exemptfrom myproject.schema import schema
urlpatterns = [ path('graphql/', csrf_exempt(FileUploadGraphQLView.as_view(graphiql=True, schema=schema))),]
运行服务器:
英:Run the server:
python manage.py runserver
打开 http://localhost:8000/graphql/
处的 GraphiQL 接口并开始查询你的 API!
英:Open the GraphiQL interface at http://localhost:8000/graphql/
and start querying your API!
你可以在 github 或 pypi 上找到有关身份验证、过滤器、验证等的高级示例。
英:You can find advanced examples with authentication, filters, validations and more on github or pypi.
运行 Graphene hello world 脚本:
英:To run a Graphene hello world script:
pip install graphene
然后在 hello.py
中使用以下代码运行 python hello.py
:
英:Then run python hello.py
with this code in hello.py
:
import graphene
class Query(graphene.ObjectType): hello = graphene.String(name=graphene.String(default_value="World"))
def resolve_hello(self, info, name): return 'Hello ' + name
schema = graphene.Schema(query=Query)result = schema.execute('{ hello }')print(result.data['hello']) # "Hello World"
还有针对 Relay、Django、SQLAlchemy 和 Google App Engine 的良好绑定。
英:There are also nice bindings for Relay, Django, SQLAlchemy, and Google App Engine.
一个简单的 Python GraphQL 客户端。支持为 GraphQL 模式中定义的类型生成代码。
graphql_query 是 Python 的完整 GraphQL 查询字符串生成器。使用 graphql_query,你可以在 https://denisart.github.io/graphql-query/ 找到 graphql_query 的文档。
英:graphql_query is complete GraphQL query string builder for python. With graphql_query you can The documentation for graphql_query can be found at https://denisart.github.io/graphql-query/.
$ pip install graphql_query
简单查询的代码
英:Code for the simple query
{ hero { name }}
这是
英:it is
from graphql_query import Operation, Query
hero = Query(name="hero", fields=["name"])operation = Operation(type="query", queries=[hero])
print(operation.render())"""query { hero { name }}"""
用于生成以下查询
英:For generation of the following query
query Hero($episode: Episode, $withFriends: Boolean!) { hero(episode: $episode) { name friends @include(if: $withFriends) { name } }}
我们有
英:we have
from graphql_query import Argument, Directive, Field, Operation, Query, Variable
episode = Variable(name="episode", type="Episode")withFriends = Variable(name="withFriends", type="Boolean!")
arg_episode = Argument(name="episode", value=episode)arg_if = Argument(name="if", value=withFriends)
hero = Query( name="hero", arguments=[arg_episode], fields=[ "name", Field( name="friends", fields=["name"], directives=[Directive(name="include", arguments=[arg_if])] ) ])operation = Operation( type="query", name="Hero", variables=[episode, withFriends], queries=[hero])print(operation.render())"""query Hero( $episode: Episode $withFriends: Boolean!) { hero( episode: $episode ) { name friends @include( if: $withFriends ) { name } }}"""
适用于 Python 2.7+ 的简单 GraphQL 客户端。
这是 qlient hello world 的示例。
英:Here's an example of a qlient hello world.
首先安装库:
英:first install the library:
pip install qlient
创建一个包含以下内容的 swapi_client_example.py
文件:
英:Create a swapi_client_example.py
file with this content:
from qlient.http import HTTPClient, GraphQLResponse
client = HTTPClient("https://swapi-graphql.netlify.app/.netlify/functions/index")
res: GraphQLResponse = client.query.film( # swapi graphql input fields id="ZmlsbXM6MQ==",
# qlient specific _fields=["id", "title", "episodeID"])
print(res.request.query) # query film($id: ID) { film(id: $id) { id title episodeID } }print(res.request.variables) # {'id': 'ZmlsbXM6MQ=='}print(res.data) # {'film': {'id': 'ZmlsbXM6MQ==', 'title': 'A New Hope', 'episodeID': 4}}
关闭文件并使用 python 运行它:
英:Close the file and run it using python:
python swapi_client_example.py
Python 中的 GraphQL 客户端。
安装 Ariadne Codegen:
英:Install Ariadne Codegen:
$ pip install ariadne-codegen
创建 queries.graphql
文件:
英:Create queries.graphql
file:
mutation CreateToken($username: String!, $password: String!) { createToken(username: $username, password: $password) { token errors { field message } }}
将 [ariadne-codegen]
部分添加到 pyproject.toml
中:
英:Add [ariadne-codegen]
section to your pyproject.toml
:
[ariadne-codegen]queries_path = "queries.graphql"remote_schema_url = "http://example.com/graphql/"
生成客户端:
英:Generate client:
$ ariadne-codegen
并在你的 Python 项目中使用它:
英:And use it in your Python projects:
from graphql_client import Client
with Client("http://example.com/graphql/") as client: result = client.create_token(username="Admin", password="Example123)
if result.errors: error = result.errors[0] raise ValidationError({error.field: error.message})
auth_token = result.token
一个免费的开源 WordPress 插件,为任何 WordPress 网站提供可扩展的 GraphQL 结构和 API
PHP GraphQL 框架。
运行 Siler hello world 脚本:
英:To run a Siler hello world script:
type Query { hello: String}
<?phpdeclare(strict_types=1);require_once '/path/to/vendor/autoload.php';
use SilerDiactoros;use SilerGraphql;use SilerHttp;
$typeDefs = file_get_contents(__DIR__.'/schema.graphql');$resolvers = [ 'Query' => [ 'hello' => 'world', ],];$schema = Graphqlschema($typeDefs, $resolvers);
echo "Server running at http://127.0.0.1:8080";
Httpserver(Graphqlpsr7($schema), function (Throwable $err) { var_dump($err); return Diactorosjson([ 'error' => true, 'message' => $err->getMessage(), ]);})()->run();
它还提供了基于 Apollo 工作方式构建 WebSocket 订阅服务器的功能。
英:It also provides functionality for the construction of a WebSocket Subscriptions Server based on how Apollo works.
它与框架无关,可用于 Symfony 和 Laravel 的绑定。此代码声明 "product" 查询和 "产品" 类型:
英:It is framework agnostic with bindings available for Symfony and Laravel. This code declares a "product" query and a "Product" Type:
class ProductController{ /**
* @Query() */ public function product(string $id): Product { // Some code that looks for a product and returns it. }}
/**
* @Type() */class Product{ /**
* @Field() */ public function getName(): string { return $this->name; } // ...}
其他 GraphQLite 功能包括验证、安全性、错误处理、通过数据加载器结构加载......
英:Other GraphQLite features include validation, security, error handling, loading via data-loader pattern...
Laravel 的 GraphQL 服务器
Symfony 的 GraphQL 服务器
一个帮助构建支持 react-relay 的 graphql-php 服务器的库。
GraphQL 参考实现的 PHP 移植
GraPHPinator 是 GraphQL 服务器的功能完整的 PHP 实现。它的工作是将查询字符串转换为给定 Schema 的解析 Json 结果。
英:GraPHPinator is feature complete PHP implementation of GraphQL server. Its job is transformation of query string into resolved Json result for a given Schema.
旨在符合 GraphQL 规范的最新草案。
英:Aims to be compliant with the latest draft of GraphQL specification.
完全类型安全,因此最低要求的 PHP 版本是 8.0。为了极大的清晰度和安全性而牺牲一点点便利 - 没有随机配置 array
,没有混合类型,没有可变函数参数 - 这个库并不试图让你避免冗长的内容,而是确保你始终知道你拥有什么。
英:Fully typesafe, and therefore minimum required PHP version is 8.0. Sacrafices a tiny bit of convenience for huge amount of clarity and safety - no random configuration array
s, no mixed types, no variable function arguments - this library doesnt try to save you from verbosity, but makes sure you always know what you've got.
先写代码。
英:Code first.
灵活的。使用模块或中间件指令轻松扩展额外功能。
英:Flexible. Easy to extend with extra functionality using Modules or middleware Directives.
包括一些超出官方规范范围的可选扩展:
英:Includes some opt-in extensions which are out of scope of official specs:
打印机 - GraPHPinator 类型系统的结构打印。
英:Printer - Schema printing for GraPHPinator typesystem.
额外类型 - 一些有用且常用的类型,包括标量类型或复合类型。
英:Extra types - Some useful and commonly used types, both scalar or composite.
约束指令 - 在 GraphQL 类型系统之上声明额外验证的类型系统指令。
英:Constraint directives - Typesystem directives to declare additional validation on top of GraphQL typesystem.
其中指令 - 用于过滤列表中的值的可执行指令。
英:Where directives - Executable directives to filter values in lists.
使用 multipart-formdata 规范(当前打包)上传文件。
英:File upload using multipart-formdata specs (currently bundled).
查询费用限额模块 - 通过限制最大深度或节点数量来限制查询成本的模块。
英:Query cost limit module - Modules to limit query cost by restricting maximum depth or number of nodes.
项目由多个较小的包组成,可以独立使用:
英:Project is composed from multiple smaller packages, which may be used standalone:
与 WordPress 中的所有数据进行交互
以下类足以创建与 Relay 兼容的 GraphQL 服务器和支持现代 REST 格式(JSON-LD、JSONAPI ...)的超媒体 API:
英:The following class is enough to create both a Relay-compatible GraphQL server and a hypermedia API supporting modern REST formats (JSON-LD, JSONAPI...):
<?php
namespace AppEntity;
use ApiPlatformCoreAnnotationApiResource;use DoctrineORMMapping as ORM;
/**
* Greet someone!
* * @ApiResource
* @ORMEntity */class Greeting{ /**
* @ORMId
* @ORMColumn(type="guid") */ public $id;
/**
* @var string Your nice message
* * @ORMColumn */ public $hello;}
其他 API 平台功能包括数据验证、身份验证、授权、弃用、缓存和 GraphiQL 集成。
英:Other API Platform features include data validation, authentication, authorization, deprecations, cache and GraphiQL integration.
使用 GraphQL 为 CQRS/ES 定义域模型,并让 serge 生成代码来处理 GraphQL 请求。
Mojolicious-Plugin-GraphQL - 将你的 GraphQL 服务连接到 Mojolicious 应用
英:Mojolicious-Plugin-GraphQL - connect your GraphQL service to a Mojolicious app
GraphQL-Plugin-Convert-DBIC - 自动将你的 DBIx::Class 模式连接到 GraphQL
英:GraphQL-Plugin-Convert-DBIC - automatically connect your DBIx::Class schema to GraphQL
GraphQL-Plugin-Convert-OpenAPI - 自动将任何 OpenAPI 服务(本地 Mojolicious 服务或远程服务)连接到 GraphQL
英:GraphQL-Plugin-Convert-OpenAPI - automatically connect any OpenAPI service (either local Mojolicious one, or remote) to GraphQL
用于 OCaml 和 Reason 的 GraphQL 服务器库
Julia GraphQL 服务器实现。
查询、变异和订阅,无需手动编写查询字符串(除非你愿意!)
英:Querying, mutating and subscribing without manual writing of query strings (unless you want to!)
将响应直接反序列化为 Julia 类型
英:Deserializing responses directly into Julia types
从 GraphQL 对象构造 Julia 类型
英:Construction of Julia types from GraphQL objects
使用内省来帮助查询
英:Using introspection to help with querying
英:Quickstart
使用 Julia 的包管理器安装
英:Install with Julia's package manager
using Pkg; Pkg.add("GraphQLClient")using GraphQLClient
连接到服务器
英:Connect to a server
client = Client("https://countries.trevorblades.com")
从 GraphQL 对象构建 Julia 类型
英:Build a Julia type from a GraphQL object
Country = GraphQLClient.introspect_object(client, "Country")
并查询服务器,将响应反序列化为这种新类型
英:And query the server, deserializing the response into this new type
response = query(client, "countries", Vector{Country}, output_fields="name")
或者手动编写查询字符串
英:Alternatively write the query string manually
query_string = """ { countries{ name }}"""
response = GraphQLClient.execute(client, query_string)
Mercurius
Mercurius 是 Fastify 的灵活且可扩展的 GraphQL 适配器,Fastify 是一个速度极快的 Web 框架,具有最少的开销和强大的插件结构。
要使用 mercurius
运行 hello world 脚本:
英:To run an hello world script with mercurius
:
npm install fastify mercurius
然后在 app.js
中使用以下代码运行 node app.js
:
英:Then run node app.js
with this code in app.js
:
const Fastify = require("fastify")const mercurius = require("mercurius")
const schema = ` type Query { hello(name: String): String! }`
const resolvers = { Query: { hello: async (_, { name }) => `hello ${name || "world"}`, },}
const app = Fastify()app.register(mercurius, { schema, resolvers,})
app.listen(3000)
// Call IT!// curl 'http://localhost:3000/graphql' \// -H 'content-type: application/json' \// --data-raw '{"query":"{ hello(name:\"Marcurius\") }" }'
graphql-yoga
GraphQL Yoga 是一个包含适配器的跨平台 GraphQL over HTTP 规范兼容的 GraphQL 服务器,使用 Envelop 和 GraphQL 工具。
围绕 Fetch API Request
和 Response
对象构建
英:Built around the Fetch API Request
& Response
objects
符合 HTTP 上的 GraphQL
英:GraphQL over HTTP compliant
由 Envelop 提供支持的可扩展 GraphQL 引擎
英:Extensible GraphQL Engine powered by Envelop
通过 HTTP 的 GraphQL 订阅
英:GraphQL Subscriptions over HTTP
使用 GraphQL 处理文件上传
英:Handle file uploads with GraphQL
与 AWS Lambda、Cloudflare Workers、Deno、Express、Next.js、SvelteKit 等集成。
英:Integrates with AWS Lambda, Cloudflare Workers, Deno, Express, Next.js, SvelteKit, and more.
要使用 graphql-yoga 运行 hello world 服务器:
英:To run a hello world server with graphql-yoga:
npm install graphql-yoga graphql
然后使用 createServer
导入创建服务器:
英:Then create a server using the createServer
import:
import { createServer } from "http"import { createSchema, createYoga } from "graphql-yoga"
createServer( createYoga({ schema: createSchema({ typeDefs: /* GraphQL */ ` type Query { hello: String } `, resolvers: { Query: { hello: () => "Hello Hello Hello", }, }, }), })).listen(4000, () => { console.info("GraphQL Yoga is listening on http://localhost:4000/graphql")})
根据你的部署目标,你可能需要使用其他库。有关更多详细信息,请参阅 documentation。
英:Depending on your deployment target, you may need to use an additional library. See the documentation for further details.
零依赖、HTTP/1 安全、简单、基于服务器发送事件协议的 GraphQL 服务器和客户端。
连贯、零依赖、惰性、简单、基于 WebSocket 协议的 GraphQL 兼容服务器和客户端。
下面的示例安装并初始化 GraphQLBox 服务器,并启用持久缓存和调试。
英:The example below installs and initializes the GraphQLBox server with a persisted cache and debugging enabled.
npm install @graphql-box/core @graphql-box/server @graphql-box/client @graphql-box/request-parser @graphql-box/cache-manager @graphql-box/debug-manager @graphql-box/execute @graphql-box/helpers @cachemap/core @cachemap/reaper @cachemap/redis @cachemap/constants @cachemap/types
import Cachemap from "@cachemap/core"import redis from "@cachemap/redis"import reaper from "@cachemap/reaper"import CacheManager from "@graphql-box/cache-manager"import Client from "@graphql-box/client"import DebugManager from "@graphql-box/debug-manager"import Execute from "@graphql-box/execute"import RequestParser from "@graphql-box/request-parser"import Server from "@graphql-box/server"import { makeExecutableSchema } from "@graphql-tools/schema"import { performance } from "perf_hooks"import { schemaResolvers, schemaTypeDefs } from "./schema"import logger from "./logger"
const schema = makeExecutableSchema({ typeDefs: schemaTypeDefs, resolvers: schemaResolvers,})
const server = new Server({ client: new Client({ cacheManager: new CacheManager({ cache: new Cachemap({ name: "server-cache", reaper: reaper({ interval: 300000 }), store: redis(/* configure */), }), cascadeCacheControl: true, typeCacheDirectives: { // Add any type specific cache control directives in the format: // TypeName: "public, max-age=3", }, }), debugManager: new DebugManager({ environment: "server", log: (...args) => { logger.log(...args) }, name: "SERVER", performance, }), requestManager: new Execute({ schema }), requestParser: new RequestParser({ schema }), }),})
// Meanwhile... somewhere else in your code
app.use("api/graphql", graphqlServer.request())
Apollo Server
0来自 Apollo 的 GraphQL 服务器,可与任何 Node.js HTTP 框架配合使用
要使用 Apollo Server 运行 hello world 服务器:
英:To run a hello world server with Apollo Server:
npm install @apollo/server graphql
然后在 server.js
中使用以下代码运行 node server.js
:
英:Then run node server.js
with this code in server.js
:
import { ApolloServer } from "@apollo/server"import { startStandaloneServer } from "@apollo/server/standalone"
const server = new ApolloServer({ typeDefs, resolvers,})
const { url } = await startStandaloneServer(server)
console.log(`🚀 Server ready at ${url}`)
Apollo Server 具有内置的独立 HTTP 服务器和 Express 中间件,并具有通过社区集成支持所有 Node.js HTTP 服务器框架和无服务器环境 的框架集成 API。
英:Apollo Server has a built in standalone HTTP server and middleware for Express, and has an framework integration API that supports all Node.js HTTP server frameworks and serverless environments via community integrations.
Apollo Server 具有 插件 API、与 Apollo Studio 集成以及性能和安全功能,例如 caching、自动持久查询 和 CSRF 预防。
英:Apollo Server has a plugin API, integration with Apollo Studio, and performance and security features such as caching, automatic persisted queries, and CSRF prevention.
要从命令行运行 GraphQL.js
hello world 脚本:
英:To run a GraphQL.js
hello world script from the command line:
npm install graphql
然后在 hello.js
中使用以下代码运行 node hello.js
:
英:Then run node hello.js
with this code in hello.js
:
var { graphql, buildSchema } = require("graphql")
var schema = buildSchema(` type Query { hello: String }`)
var rootValue = { hello: () => "Hello world!" }
var source = "{ hello }"
graphql({ schema, source, rootValue }).then(response => { console.log(response)})
简单、插件化、零依赖、GraphQL over HTTP 规范兼容的服务器、客户端和审计套件。
urql
是一个 GraphQL 客户端,它为多个框架公开了一组辅助程序。它具有高度可定制性和多功能性,因此你可以从第一个 GraphQL 项目开始一直到构建复杂的应用并尝试 GraphQL 客户端。
英:urql
is a GraphQL client that exposes a set of helpers for several frameworks.
It's built to be highly customisable and versatile so you can take it from getting started with your first GraphQL project
all the way to building complex apps and experimenting with GraphQL clients.
目前支持 React、React Native、Preact、Svelte 和 Vue,并受 GraphQL 代码生成器支持。
英:Currently supports React, React Native, Preact, Svelte, and Vue, and is supported by GraphQL Code Generator.
逻辑而简单的默认行为和文档缓存,以及通过 @urql/exchange-graphcache
的规范化缓存
英:Logical yet simple default behaviour and document caching, and normalized caching via @urql/exchange-graphcache
通过 "exchanges"(插件包)完全可定制的行为
英:Fully customizable behaviour via "exchanges" (addon packages)
Relay 是一个用于构建数据驱动的 React 应用的 JavaScript 框架。
英:Relay is a JavaScript framework for building data-driven React applications.
声明式:永远不要再使用命令式 API 与你的数据存储进行通信。只需使用 GraphQL 声明你的数据要求,然后让 Relay 确定如何以及何时获取你的数据。
英:Declarative: Never again communicate with your data store using an imperative API. Simply declare your data requirements using GraphQL and let Relay figure out how and when to fetch your data.
主机托管:查询位于依赖它们的视图旁边,因此你可以轻松推断你的应用。Relay 将查询聚合为高效的网络请求,以仅获取你需要的内容。
英:Colocation: Queries live next to the views that rely on them, so you can easily reason about your app. Relay aggregates queries into efficient network requests to fetch only what you need.
突变:Relay 允许你使用 GraphQL 变更来改变客户端和服务器上的数据,并提供自动数据一致性、乐观更新和错误处理。
英:Mutations: Relay lets you mutate data on the client and server using GraphQL mutations, and offers automatic data consistency, optimistic updates, and error handling.
使用模板字符串的小型 GraphQL 客户端库。
一个简单的 JavaScript GraphQL 客户端,适用于所有 JavaScript 环境(浏览器、Node.js 和 React Native)。
用于 GraphQL 的 curl,具有自动补齐、订阅和 GraphiQL 功能。也是一个极其简单的通用 JavaScript GraphQL 客户端。
连贯、零依赖、惰性、简单、基于 WebSocket 协议的 GraphQL 兼容服务器和客户端。
TypeScript 的 GraphQL 客户端,根据强类型查询请求自动推断返回数据的类型
零依赖、HTTP/1 安全、简单、基于服务器发送事件协议的 GraphQL 服务器和客户端。
一个简单而灵活的 JavaScript GraphQL 客户端,适用于所有 JavaScript 环境(浏览器、Node.js 和 React Native) - 基本上是 fetch
的轻量级封装。
简单、插件化、零依赖、GraphQL over HTTP 规范兼容的服务器、客户端和审计套件。
🥇 一流的钩子 API
英:🥇 First-class hooks API
⚖️ 小打包:仅 7.6kB(2.8 gzip 压缩)
英:⚖️ Tiny bundle: only 7.6kB (2.8 gzipped)
📄 完整的 SSR 支持:参见 graphql-hooks-ssr
英:📄 Full SSR support: see graphql-hooks-ssr
🔌 插件缓存:参见 graphql-hooks-memcache
英:🔌 Plugin Caching: see graphql-hooks-memcache
🔥 不再有渲染属性地狱
英:🔥 No more render props hell
⏳ 轻松处理加载和错误状态
英:⏳ Handle loading and error states with ease
英:Quickstart
npm install graphql-hooks
首先,你需要创建一个客户端并使用提供程序封装你的应用:
英:First you'll need to create a client and wrap your app with the provider:
import { GraphQLClient, ClientContext } from "graphql-hooks"
const client = new GraphQLClient({ url: "/graphql",})
function App() { return ( <ClientContext.Provider value={client}> {/* children */} </ClientContext.Provider> )}
现在,在你的子组件中,你可以使用 useQuery
:
英 :Now in your child components you can make use of useQuery
:
import { useQuery } from "graphql-hooks"
const HOMEPAGE_QUERY = `query HomePage($limit: Int) { users(limit: $limit) { id name }}`
function MyComponent() { const { loading, error, data } = useQuery(HOMEPAGE_QUERY, { variables: { limit: 10, }, })
if (loading) return "Loading..." if (error) return "Something Bad Happened"
return ( <ul> {data.users.map(({ id, name }) => ( <li key={id}>{name}</li> ))} </ul> )}
GraphQLBox client
一个可扩展的 GraphQL 客户端,带有用于反应、缓存、请求解析、Web Workers、Websockets 等模块...
下面的示例安装并初始化 GraphQLBox 客户端,并启用持久缓存和调试。
英:The example below installs and initializes the GraphQLBox client with a persisted cache and debugging enabled.
npm install @graphql-box/core @graphql-box/client @graphql-box/request-parser @graphql-box/cache-manager @graphql-box/debug-manager @graphql-box/fetch-manager @graphql-box/helpers @cachemap/core @cachemap/reaper @cachemap/indexed-db @cachemap/constants @cachemap/types
import Cachemap from "@cachemap/core"import indexedDB from "@cachemap/indexed-db"import reaper from "@cachemap/reaper"import CacheManager from "@graphql-box/cache-manager"import Client from "@graphql-box/client"import DebugManager from "@graphql-box/debug-manager"import FetchManager from "@graphql-box/fetch-manager"import RequestParser from "@graphql-box/request-parser"import introspection from "./introspection-query"
const requestManager = new FetchManager({ apiUrl: "/api/graphql", batchRequests: true, logUrl: "/log/graphql",})
const client = new Client({ cacheManager: new CacheManager({ cache: new Cachemap({ name: "client-cache", reaper: reaper({ interval: 300000 }), store: indexedDB(/* configure */), }), cascadeCacheControl: true, typeCacheDirectives: { // Add any type specific cache control directives in the format: // TypeName: "public, max-age=3", }, }), debugManager: new DebugManager({ environment: "client", log: (message, data, logLevel) => { requestManager.log(message, data, logLevel) }, name: "CLIENT", performance: self.performance, }), requestManager, requestParser: new RequestParser({ introspection }),})
// Meanwhile... somewhere else in your code
const { data, errors } = await client.request(queryOrMutation)
一个通用 GraphQL 客户端,具有多个框架的视图层集成,仅 1.6kb。
一个简单的 JavaScript GraphQL 客户端,让 *.gql 文件通过 webpack loader 作为模块使用。
用于使用云服务开发应用的 JavaScript 库,它支持 GraphQL 后端和 React 组件来处理 GraphQL 数据。
一个强大的 JavaScript GraphQL 客户端,旨在与 React、React Native、Angular 2 或纯 JavaScript 良好配合。
SpectaQL 是一个 Node.js 库,它使用各种选项为 GraphQL 结构生成静态文档:
英:SpectaQL is a Node.js library that generates static documentation for a GraphQL schema using a variety of options:
使用内省查询从实时端点。
英:From a live endpoint using the introspection query.
来自包含内省查询结果的文件。
英:From a file containing an introspection query result.
从一个、多个文件或 glob 通向 SDL 中的结构定义。
英:From a file, files or glob leading to the schema definitions in SDL.
SpectaQL 开箱即用,生成一个 3 列 HTML 页面,并允许你在几个内置主题之间进行选择。该项目的主要目标是轻松且高度可定制 - 它是可主题化的,几乎所有内容都可以覆盖或定制。
英:Out of the box, SpectaQL generates a single 3-column HTML page and lets you choose between a couple built-in themes. A main goal of the project is to be easily and extremely customizable--it is themeable and just about everything can be overridden or customized.
npm install --dev spectaql# ORyarn add -D spectaql
# Then generate your docsnpm run spectaql my-config.yml# ORyarn spectaql my-config.yml
在几秒钟内从 PostgreSQL 模式构建强大、可扩展且高性能的 GraphQL API;为你节省数周甚至数月的开发时间。
从 GraphQL API 生成 REST API。
Micro Fiber 是一个 JavaScript 库,它允许:
英:Microfiber is a JavaScript library that allows:
挖掘特定查询、变更、类型、字段、参数或订阅的内省查询结果。
英:Digging through your Introspection Query Results for a specific Query, Mutation, Type, Field, Argument or Subscription.
从内省查询结果中删除特定的查询、变更、类型、字段/输入字段、参数或订阅。
英:Removing a specific Query, Mutation, Type, Field/InputField, Argument or Subscription from your Introspection Query Results.
删除引用不存在的类型的查询、突变、字段/输入字段或参数 - 或已被删除 - 你的内省查询结果。
英:Removing Queries, Mutations, Fields/InputFields or Arguments that refer to Type that does not exist in - or has been removed from - your Introspection Query Results.
npm install microfiber# ORyarn add microfiber
然后在 JS 中:
英:Then in JS:
import { Microfiber } from 'microfiber'
const introspectionQueryResults = {...}
const microfiber = new Microfiber(introspectionQueryResults)
// ...do some things to your schema with `microfiber`
const cleanedIntrospectonQueryResults = microfiber.getResponse()
一组用于更快开发 GraphQL 工具的实用程序(结构和文档加载、结构合并等)。
GraphQL Shield 可帮助你为应用创建权限层。使用直观的规则 API,你将在每个请求上获得屏蔽引擎的强大功能,并通过智能缓存减少每个请求的加载时间。这样你就可以确保你的应用保持快速,并且不会暴露任何内部数据。
英:GraphQL Shield helps you create a permission layer for your application. Using an intuitive rule-API, you'll gain the power of the shield engine on every request and reduce the load time of every request with smart caching. This way you can make sure your application will remain quick, and no internal data will be exposed.
import { rule, shield, and, or, not } from "graphql-shield"
// Rules
const isAuthenticated = rule({ cache: "contextual" })( async (parent, args, ctx, info) => { return ctx.user !== null })
const isAdmin = rule({ cache: "contextual" })( async (parent, args, ctx, info) => { return ctx.user.role === "admin" })
const isEditor = rule({ cache: "contextual" })( async (parent, args, ctx, info) => { return ctx.user.role === "editor" })
// Permissions
const permissions = shield({ Query: { frontPage: not(isAuthenticated), fruits: and(isAuthenticated, or(isAdmin, isEditor)), customers: and(isAuthenticated, isAdmin), }, Mutation: { addFruitToBasket: isAuthenticated, }, Fruit: isAuthenticated, Customer: isAdmin,})
// Server
const server = new GraphQLServer({ typeDefs, resolvers, middlewares: [permissions], context: req => ({ ...req, user: getUser(req), }),})
自定义 GraphQL 标量类型库,用于创建精确、类型安全的 GraphQL 结构。
GraphQL 模块可让你将后端实现分离为小型、可重用、易于实现和易于测试的部分。
GraphQL 中间件是一个结构封装器,它允许你跨多个解析器有效管理附加功能。
英:GraphQL Middleware is a schema wrapper which allows you to manage additional functionality across multiple resolvers efficiently.
英:Features
💡 便于使用:一个直观但熟悉的 API,你很快就会掌握。💪 强大的:允许完全控制你的解析器(之前、之后)。🌈 兼容的:适用于任何 GraphQL 结构。
英:💡 Easy to use: An intuitive, yet familiar API that you will pick up in a second. 💪 Powerful: Allows complete control over your resolvers (Before, After). 🌈 Compatible: Works with any GraphQL Schema.
英:Example
const { ApolloServer } = require("apollo-server")const { makeExecutableSchema } = require("@graphql-tools/schema")
const typeDefs = `type Query { hello(name: String): String bye(name: String): String}`const resolvers = { Query: { hello: (root, args, context, info) => { console.log(`3. resolver: hello`) return `Hello ${args.name ? args.name : "world"}!` }, bye: (root, args, context, info) => { console.log(`3. resolver: bye`) return `Bye ${args.name ? args.name : "world"}!` }, },}
const logInput = async (resolve, root, args, context, info) => { console.log(`1. logInput: ${JSON.stringify(args)}`) const result = await resolve(root, args, context, info) console.log(`5. logInput`) return result}
const logResult = async (resolve, root, args, context, info) => { console.log(`2. logResult`) const result = await resolve(root, args, context, info) console.log(`4. logResult: ${JSON.stringify(result)}`) return result}
const schema = makeExecutableSchema({ typeDefs, resolvers })
const schemaWithMiddleware = applyMiddleware(schema, logInput, logResult)
const server = new ApolloServer({ schema: schemaWithMiddleware,})
await server.listen({ port: 8008 })
GraphQL Mesh 允许你使用 GraphQL 查询语言访问不运行 GraphQL 的远程 API(以及运行 GraphQL 的远程 API)中的数据。它可以用作其他服务的网关,或者作为聚合来自远程 API 的数据的本地 GraphQL 模式运行。
使用 GraphQL 实时处理任何 GraphQL 结构或传输。
用于为 IDE 构建 GraphQL 语言服务(诊断、自动补齐等)的接口。
比较结构、验证文档、查找重大更改、查找相似类型、结构覆盖率等等。
简单、插件化、零依赖、GraphQL over HTTP 规范兼容的服务器、客户端和审计套件。
GraphQL-ESLint 将 GraphQL AST 集成到 ESLint 核心中(作为解析器)。
适用于所有 GraphQL 工具的一种配置(大多数工具、编辑器和 IDE 支持)。
GraphQL 代码生成器,灵活支持自定义插件和模板,如 Typescript(前端和后端)、React Hooks、解析器签名等。
用于常见 GraphQL 开发工作流程的命令行工具。
浏览器内的交互式 GraphQL IDE。
布兰格 - 浏览任何图表
英:Brangr - Browse Any Graph
Brangr 是一个简单、独特的工具,任何 Web 服务器都可以托管它,为任何 GraphQL 服务(或许多服务)提供用户友好的浏览器/查看器。
英:Brangr is a simple, unique tool that any web server can host to provide a user-friendly browser/viewer for any GraphQL service (or many).
Brangr 通过选择用户可配置的布局,以有吸引力的方式格式化 GraphQL 结果。它允许用户提取生成的 HTML 及其源 JSON。它提供了一个聪明的结构浏览器。它有内置文档。
英:Brangr formats GraphQL results attractively, via a selection of user-configurable layouts. It lets users extract the generated HTML, and its source JSON. It provides a clever schema browser. It has built-in docs.
Brangr 使托管它的网站能够向用户呈现一组预制 GraphQL 请求,他们可以根据需要对其进行编辑,并让他们创建自己的请求。它允许网站为格式化结果的各个方面定义自定义 CSS 样式。
英:Brangr enables sites hosting it to present users with a collection of pre-fab GraphQL requests, which they can edit if desired, and let them create their own requests. And it allows sites to define custom CSS styling for all aspects of the formatted results.
在 公共 Brangr 站点 尝试一下。
英:Try it at the public Brangr site.
示例
英:Example
query { heroes(_layout:{type:table}) { # _layout arg not sent to service first last }}
Brangr 将上述查询渲染如下(尽管不在引号块中):
英:Brangr renders the above query as follows (though not in a quote block):
heroes...
第一的 最后的 亚瑟 凹痕 福特 长官 赞福德 比伯布鲁克斯
GiraphQL 使编写类型安全结构变得简单,并且无需代码生成器、构建过程或大量手动类型定义。
英:GiraphQL makes writing type-safe schemas simple, and works without a code generator, build process, or extensive manual type definitions.
import { ApolloServer } from "apollo-server"import SchemaBuilder from "@giraphql/core"
const builder = new SchemaBuilder({})
builder.queryType({ fields: t => ({ hello: t.string({ args: { name: t.arg.string({}), }, resolve: (parent, { name }) => `hello, ${name || "World"}`, }), }),})
new ApolloServer({ schema: builder.toSchema({}),}).listen(3000)
Spring for GraphQL
0Spring for GraphQL 为基于 GraphQL Java 构建的 Spring 应用提供支持。
Spring for GraphQL 为基于 GraphQL Java 构建的 Spring 应用提供支持。请参阅官方 Spring 指南 了解如何在 15 分钟内构建一个 GraphQL 服务。
英:Spring for GraphQL provides support for Spring applications built on GraphQL Java. See the official Spring guide for how to build a GraphQL service in 15 minutes.
它是 GraphQL Java 团队和 Spring 工程团队的共同协作。
英:It is a joint collaboration between the GraphQL Java team and Spring engineering.
我们共同的理念是提供尽可能少的意见,同时专注于对广泛用例的全面支持。
英:Our shared philosophy is to provide as little opinion as we can while focusing on comprehensive support for a wide range of use cases.
它旨在成为所有 Spring、GraphQL 应用的基础。
英:It aims to be the foundation for all Spring, GraphQL applications.
特性:
英:Features:
服务器通过 HTTP、WebSocket 和 RSocket 处理 GraphQL 请求。
英:Server handling of GraphQL requests over HTTP, WebSocket, and RSocket.
基于注释的编程模型,其中 @Controller 组件使用注释来声明具有灵活方法签名的处理程序方法,以获取特定 GraphQL 字段的数据。例如:
英:An annotation-based programming model where @Controller components use annotations to declare handler methods with flexible method signatures to fetch the data for specific GraphQL fields. For example:
@Controllerpublic class GreetingController {
@QueryMapping public String hello() { return "Hello, world!"; }
}
客户端支持通过 HTTP、WebSocket 和 RSocket 执行 GraphQL 请求。
英:Client support for executing GraphQL requests over HTTP, WebSocket, and RSocket.
专门支持通过 HTTP、WebSocket 和 RSocket 测试 GraphQL 请求,以及直接针对服务器进行测试。
英:Dedicated support for testing GraphQL requests over HTTP, WebSocket, and RSocket, as well as for testing directly against a server.
要开始使用,请检查此存储库中 https://start.spring.io 和 samples 上的 Spring GraphQL 启动器。
英:To get started, check the Spring GraphQL starter on https://start.spring.io and the samples in this repository.
Domain Graph Service (DGS) Framework
DGS Framework(Domain Graph Service)是由 Netflix 开发的 Spring Boot 的 GraphQL 服务器框架。
DGS Framework(Domain Graph Service)是由 Netflix 开发的 Spring Boot 的 GraphQL 服务器框架。
英:The DGS Framework (Domain Graph Service) is a GraphQL server framework for Spring Boot, developed by Netflix.
特点包括:
英:Features include:
基于注解的 Spring Boot 编程模型
英:Annotation based Spring Boot programming model
用于将查询测试编写为单元测试的测试框架
英:Test framework for writing query tests as unit tests
Gradle 代码生成插件用于从结构创建类型
英:Gradle Code Generation plugin to create types from schema
与 GraphQL Federation 轻松集成
英:Easy integration with GraphQL Federation
与 Spring Security 集成
英:Integration with Spring Security
GraphQL 订阅(WebSocket 和 SSE)
英:GraphQL subscriptions (WebSockets and SSE)
文件上传
英:File uploads
错误处理
英:Error handling
许多扩展点
英:Many extension points
请参阅 DGS 框架入门 了解如何开始。
英:See DGS Framework Getting Started for how to get started.
MicroProfile GraphQL
0MP GraphQL 是用于构建 GraphQL 应用的代码优先规范。它使用类似于 JAX-RS 的注释和设计模式来实现快速开发。
MicroProfile GraphQL 是用于构建 GraphQL 应用的 GraphQL 服务器和客户端规范。其独特的基于注释的 API 方法可实现快速应用开发。编码为 MP GraphQL API 的应用是可移植的,并且可以部署到 Java 服务器运行时中,例如 Open Liberty、Quarkus、Helidon 和 Wildfly。这意味着你的应用可以利用其他 Jakarta 和 MicroProfile 技术。
英:MicroProfile GraphQL is a GraphQL server and client specification for building GraphQL applications. It's unique annotation-based API approach enables rapid application development. Applications coded to the MP GraphQL APIs are portable, and can be deployed into Java server runtimes such as Open Liberty, Quarkus, Helidon and Wildfly. This means that your applications can make use of other Jakarta and MicroProfile technologies.
MP GraphQL 功能包括:
英:MP GraphQL features include:
基于注释的 API
英:Annotation-based APIs
与雅加达 CDI 集成
英:Integration with Jakarta CDI
类型安全和动态客户端 API
英:Type-safe and dynamic client APIs
异常处理
英:Exception handling
与 Jakarta 和 MicroProfile 技术轻松集成
英:Easy integration with Jakarta and MicroProfile technologies
想开始吗?查看这些资源:
英:Want to get started? Check out these resouces:
了解如何 在 Open Liberty 中创建并部署服务器端应用。
英:Learn how to create and deploy a server side app in Open Liberty.
了解如何 在 Open Liberty 中创建客户端应用。
英:Learn how to create a client application in Open Liberty.
了解如何 在 Quarkus 中创建并部署服务器端应用。
英:Learn how to create and deploy a server side app in Quarkus.
构建一个简单的示例天气应用 快速教程。
英:Quick tutorial to build a simple sample weather application.
或者这些视频:
英:Or these videos:
下面是一个示例,介绍如何基于 kotlin 数据类以及应用于你的类的属性解析器创建简单结构。
英:Here's an example on how to create a simple schema based on a kotlin data class plus a property resolver that gets applied onto your class.
data class Article(val id: Int, val text: String)
fun main() { val schema = KGraphQL.schema { query("article") { resolver { id: Int?, text: String -> Article(id ?: -1, text) } } type<Article> { property<String>("fullText") { resolver { article: Article -> "${article.id}: ${article.text}" } } } }
schema.execute(""" { article(id: 5, text: "Hello World") { id fullText } } """).let(::println)}
KGraphQL 在幕后使用协程来提供出色的异步性能。
英:KGraphQL is using coroutines behind the scenes to provide great asynchronous performance.
有关更深入的用法,请参阅 KGraphQL 文档。
英:See KGraphQL docs for more in depth usage.
英:Ktor Plugin
KGraphQL 有一个 Ktor 插件,它可以通过单个 install 函数调用为你提供功能齐全的 GraphQL 服务器。下面的示例展示了如何在 Ktor 中设置 GraphQL 服务器,输入 localhost:8080/graphql
即可为你提供开箱即用的 GraphQL 在线运行。
英:KGraphQL has a Ktor plugin which gives you a fully functional GraphQL server with a single install function call. Example below shows how to set up a GraphQL server within Ktor and it will give you a GraphQL Playground out of the box by entering localhost:8080/graphql
.
fun Application.module() { install(GraphQL) { playground = true schema { query("hello") { resolver { -> "World!" } } } }}
你可以按照 Ktor 教程 从头开始使用 ktor 设置 KGraphQL 服务器。
英:You can follow the Ktor tutorial to set up a KGraphQL server with ktor from scratch up.
Jimmer
一个适用于 java 和 kotlin 的革命性 ORM 框架,它还提供专门的 API,用于快速开发基于 Spring GraphQL 的应用。
英:Introduce
SpringBoot 从 2.7 开始引入了 Spring GraphQL。Jimmer 提供专门的 API,用于快速开发基于 Spring GraphQL 的应用。
英:SpringBoot has introduced Spring GraphQL since 2.7. Jimmer provides specialized API for rapid development of Spring GraphQL-based applications.
支持两个 API:Java API 和 kotlin API。
英:Support two APIs: Java API & kotlin API.
强大且 GraphQL 友好的缓存支持。
英:Powerful and GraphQL friendly caching support.
比其他流行的 ORM 解决方案更快,请参阅基准测试:https://babyfish-ct.github.io/jimmer/docs/benchmark/
英:Faster than other popular ORM solutions, please see the bechmark: https://babyfish-ct.github.io/jimmer/docs/benchmark/
比其他流行的 ORM 解决方案更强大。
英:More powerful than other popular ORM solutions.
ORM 设计要考虑三个方面:
英:Three aspects should be considered in ORM design:
A。 询问。b. 更新。C。 缓存。
英:a. Query. b. Update. c. Cache.
每个方面都针对任意深度的对象树而不是简单的对象。这种独特的设计带来了其他流行解决方案无法比拟的便利性。
英:Each aspect is aimed at object trees with arbitrary depth rather than simple objects. This distinctive design brings convenience unmatched by other popular solutions.
英:Links
Youtube 视频:https://www.youtube.com/watch?v=Rt5zNv0YR2E
英:Youtube video: https://www.youtube.com/watch?v=Rt5zNv0YR2E
文档:https://babyfish-ct.github.io/jimmer/
英:Documentation: https://babyfish-ct.github.io/jimmer/
项目主页:https://github.com/babyfish-ct/jimmer
英:Project Home: https://github.com/babyfish-ct/jimmer
Java 的 GraphQL 示例:https://github.com/babyfish-ct/jimmer/tree/main/example/java/jimmer-sql-graphql
英:GraphQL example for Java: https://github.com/babyfish-ct/jimmer/tree/main/example/java/jimmer-sql-graphql
Kotlin 的 GraphQL 示例:https://github.com/babyfish-ct/jimmer/tree/main/example/kotlin/jimmer-sql-graphql-kt
英:GraphQL example for Kotlin: https://github.com/babyfish-ct/jimmer/tree/main/example/kotlin/jimmer-sql-graphql-kt
GraphQL Kotlin 遵循代码优先的 方法来生成 GraphQL 结构。鉴于 Kotlin 和 GraphQL 之间的相似之处(例如定义可为空/不可为空类型的能力),可以从 Kotlin 代码生成结构,而无需任何单独的结构规范。要创建反应式 GraphQL Web 服务器,请将以下依赖添加到你的 Gradle 构建文件中:
英:GraphQL Kotlin follows a code first approach for generating your GraphQL schemas. Given the similarities between Kotlin and GraphQL, such as the ability to define nullable/non-nullable types, a schema can be generated from Kotlin code without any separate schema specification. To create a reactive GraphQL web server add following dependency to your Gradle build file:
// build.gradle.ktsimplementation("com.expediagroup", "graphql-kotlin-spring-server", latestVersion)
我们还需要提供受支持的包列表,可以扫描这些包以通过反射公开你的结构对象。将以下配置添加到你的 application.yml
文件中:
英:We also need to provide a list of supported packages that can be scanned for exposing your schema objects through reflections. Add following configuration to your application.yml
file:
graphql: packages: - "com.your.package"
通过上述配置,我们现在可以创建我们的结构。为了在 GraphQL 结构中公开你的查询、变更和/或订阅,你只需实现相应的标记接口,它们将被 graphql-kotlin-spring-server
自动配置库自动选取。
英:With the above configuration we can now create our schema. In order to expose your queries, mutations and/or subscriptions in the GraphQL schema you simply need to implement corresponding marker interface and they will be automatically picked up by graphql-kotlin-spring-server
auto-configuration library.
@Componentclass HelloWorldQuery : Query { fun helloWorld() = "Hello World!!!"}
这将生成具有以下结构的反应式 GraphQL Web 应用:
英:This will result in a reactive GraphQL web application with following schema:
type Query { helloWorld: String!}
有关更多详细信息,请参阅 graphql-kotlin 文档。
英:See graphql-kotlin docs for additial details.
请参阅 GraphQL Java 网站上的 入门教程。
英:See the Getting Started tutorial on the GraphQL Java website.
使用 graphql-java
执行 hello world GraphQL 查询的代码:
英:Code that executes a hello world GraphQL query with graphql-java
:
import graphql.ExecutionResult;import graphql.GraphQL;import graphql.schema.GraphQLSchema;import graphql.schema.StaticDataFetcher;import graphql.schema.idl.RuntimeWiring;import graphql.schema.idl.SchemaGenerator;import graphql.schema.idl.SchemaParser;import graphql.schema.idl.TypeDefinitionRegistry;
import static graphql.schema.idl.RuntimeWiring.newRuntimeWiring;
public class HelloWorld {
public static void main(String[] args) { String schema = "type Query{hello: String}";
SchemaParser schemaParser = new SchemaParser(); TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse(schema);
RuntimeWiring runtimeWiring = newRuntimeWiring() .type("Query", builder -> builder.dataFetcher("hello", new StaticDataFetcher("world"))) .build();
SchemaGenerator schemaGenerator = new SchemaGenerator(); GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);
GraphQL build = GraphQL.newGraphQL(graphQLSchema).build(); ExecutionResult executionResult = build.execute("{hello}");
System.out.println(executionResult.getData().toString()); // Prints: {hello=world} }}
请参阅 graphql-java 文档 了解更多信息。
英:See the graphql-java docs for further information.
GraphQL Spring Boot
0来自 GraphQL Java Kickstart 的 GraphQL Spring Boot
GraphQL Spring Boot 将任何 Spring Boot 应用转变为 GraphQL Server
英:The GraphQL Spring Boot turns any Spring Boot application into a GraphQL Server
Started 包括以下功能:
英:Started includes features such as:
在 GraphQL Java 工具 的帮助下使用结构驱动的 API
英:Use a schema-driven API with the help of GraphQL Java Tools
可以选择在 GraphQL-Java 注释 的帮助下使用注释驱动结构
英:Optionally choose to use an annotation driven schema with the help of GraphQL-Java Annotations
用于结构自省和查询调试的嵌入式 GraphiQL 工具
英:Embedded GraphiQL tool for schema introspection and query debugging
用于结构自省和查询调试的嵌入式 GraphQL 在线运行 工具
英:Embedded GraphQL Playground tool for schema introspection and query debugging
嵌入 GraphQL 航行者 工具将你的 GraphQL API 表示为交互式图表
英:Embedded the GraphQL Voyager tool to represent your GraphQL API as an interactive graph
请参阅 GraphQL Java Kickstart 入门 了解如何开始。
英:See GraphQL Java Kickstart Getting Started for how to get started.
GraphQL Calculator 是一个轻量级的 graphql 计算引擎,用于改变 graphql 查询的执行行为。
英:GraphQL Calculator is a lightweight graphql calculation engine, which is used to alter execution behavior of graphql query.
以下是一些有关如何在 graphql 查询上使用 GraphQL 计算器的示例。
英:Here are some examples on how to use GraphQL Calculator on graphql query.
query basicMapValue($userIds: [Int]) { userInfoList(userIds: $userIds) { id age firstName lastName fullName: stringHolder @map(mapper: "firstName + lastName") }}
query filterUserByAge($userId: [Int]) { userInfoList(userIds: $userId) @filter(predicate: "age>=18") { userId age firstName lastName }}
query parseFetchedValueToAnotherFieldArgumentMap($itemIds: [Int]) { itemList(itemIds: $itemIds) { # save sellerId as List<Long> with unique name "sellerIdList" sellerId @fetchSource(name: "sellerIdList") name saleAmount salePrice }
userInfoList(userIds: 1) # transform the argument of "userInfoList" named "userIds" according to expression "sellerIdList" and expression argument, # which mean replace userIds value by source named "sellerIdList" @argumentTransform( argumentName: "userIds" operateType: MAP expression: "sellerIdList" dependencySources: ["sellerIdList"] ) { userId name age }}
请参阅 graphql 计算器自述文件 了解更多信息。
英:See graphql-calculator README for more information.
GraphQL Kotlin 提供了一组轻量级类型安全的 GraphQL HTTP 客户端。该库提供基于 Ktor HTTP 客户端和 Spring WebClient 的参考实现,并允许使用其他引擎进行自定义实现。Jackson 和 kotlinx 序列化类型安全数据模型是在构建时由提供的 Gradle 和 Maven 插件生成的。
英:GraphQL Kotlin provides a set of lightweight type-safe GraphQL HTTP clients. The library provides Ktor HTTP client and Spring WebClient based reference implementations as well as allows for custom implementations using other engines. Jackson and kotlinx-serialization type-safe data models are generated at build time by the provided Gradle and Maven plugins.
要生成将与 GraphQL Kotlin Spring WebClient 一起使用的 Jackson 模型,请将以下内容添加到 Gradle 构建文件中:
英:To generate Jackson models that will be used with GraphQL Kotlin Spring WebClient, add following to your Gradle build file:
// build.gradle.ktsimport com.expediagroup.graphql.plugin.gradle.graphql
plugins { id("com.expediagroup.graphql") version $latestGraphQLKotlinVersion}
dependencies { implementation("com.expediagroup:graphql-kotlin-spring-client:$latestGraphQLKotlinVersion")}
graphql { client { // target GraphQL endpoint endpoint = "http://localhost:8080/graphql" // package for generated client code packageName = "com.example.generated" }}
默认情况下,GraphQL Kotlin 插件将查找 src/main/resources
下的查询文件。给定 HelloWorldQuery.graphql
示例查询:
英:By default, GraphQL Kotlin plugins will look for query files under src/main/resources
. Given HelloWorldQuery.graphql
sample query:
query HelloWorldQuery { helloWorld}
插件将生成类,这些类是实现 GraphQLClientRequest 接口的简单 POJO,并表示 GraphQL 请求。
英:Plugin will generate classes that are simple POJOs implementing GraphQLClientRequest interface and represent a GraphQL request.
package com.example.generated
import com.expediagroup.graphql.client.types.GraphQLClientRequestimport kotlin.Stringimport kotlin.reflect.KClass
const val HELLO_WORLD_QUERY: String = "query HelloWorldQuery {\n helloWorld\n}"
class HelloWorldQuery: GraphQLClientRequest<HelloWorldQuery.Result> { override val query: String = HELLO_WORLD_QUERY
override val operationName: String = "HelloWorldQuery"
override fun responseType(): KClass<HelloWorldQuery.Result> = HelloWorldQuery.Result::class
data class Result( val helloWorld: String }}
然后我们可以使用目标客户端执行查询。
英:We can then execute our queries using target client.
package com.example.client
import com.expediagroup.graphql.client.spring.GraphQLWebClientimport com.expediagroup.graphql.generated.HelloWorldQueryimport kotlinx.coroutines.runBlocking
fun main() { val client = GraphQLWebClient(url = "http://localhost:8080/graphql") runBlocking { val helloWorldQuery = HelloWorldQuery() val result = client.execute(helloWorldQuery) println("hello world query result: ${result.data?.helloWorld}") }}
有关更多详细信息,请参阅 graphql-kotlin 客户端文档。
英:See graphql-kotlin client docs for additional details.
GraphQL JVM 客户端,旨在根据标准模型定义构建查询。通过美国运通。
Apollo Kotlin(以前称为 Apollo Android)是一个 GraphQL 客户端,一般支持 Android、Java8+、iOS 和 Kotlin 多平台。其特点:
英:Apollo Kotlin (formerly known as Apollo Android) is a GraphQL client with support for Android, Java8+, iOS and Kotlin multiplatform in general. It features:
Java 和 Kotlin 多平台代码生成
英:Java and Kotlin Multiplatform code generation
查询、变更和订阅
英:Queries, Mutations and Subscriptions
无反射解析
英:Reflection-free parsing
标准化缓存
英:Normalized cache
自定义标量类型
英:Custom scalar types
HTTP 缓存
英:HTTP cache
自动保留查询
英:Auto Persisted Queries
查询批处理
英:Query batching
文件上传
英:File uploads
Espresso 闲置资源
英:Espresso IdlingResource
用于测试的假模型
英:Fake models for tests
AppSync 和 graphql-ws websocket
英:AppSync and graphql-ws websockets
GraphQL AST 解析器
英:GraphQL AST parser
GraphQL Java Generator
0GraphQL Java Generator 是一个生成 Java 代码的工具,用于加速 GraphQL API 客户端和服务器的开发
GraphQL Java 客户端:它生成调用 GraphQL 端点的 Java 类,以及包含服务器返回的数据的 POJO。然后可以通过使用对 Java 方法的简单调用来查询 GraphQL 端点(请参阅下面的示例)
英:GraphQL Java client: it generates the Java classes that call the GraphQL endpoint, and the POJO that will contain the data returned by the server. The GraphQL endpoint can then be queried by using a simple call to a Java method (see sample below)
GraphQL Java 服务器:它基于 graphql-java(上面列出)。它生成所有样板代码。你只需实现服务器特有的功能,即 GraphQL 类型之间的连接。GraphQL Java 生成器以 Maven 插件 形式提供。Gradle 插件即将推出。请注意,GraphQL Java Generator 是一个加速器:生成的代码不依赖于任何特定于 GraphQL Java Generator 的库。因此,它可以帮助你开始构建基于 graphql-java 的应用。生成代码后,你可以决定像任何标准 java 应用一样手动编辑它,并摆脱 GraphQL Java 生成器。当然,根据我们的说法,你可以而且应该在你的项目发展时继续使用 GraphQL Java Generator。
英:GraphQL Java server: it is based on graphql-java (listed here above). It generates all the boilerplate code. You'll only have to implement what's specific to your server, which are the joins between the GraphQL types. GraphQL Java Generator is available as a Maven Plugin. A Gradle plugin is coming soon. Please note that GraphQL Java Generator is an accelerator: the generated code doesn’t depend on any library specific to GraphQL Java Generator. So, it helps you to start building application based on graphql-java. Once the code is generated, you can decide to manually edit it as any standard java application, and get rid of GraphQL Java Generator. Of course you can, and should, according to us :), continue using GraphQL Java Generator when your projet evolves.
Mu-Haskell with Mu-GraphQL
0用于构建微服务(gRPC、HTTP)和 GraphQL API 的 Haskell 库。
具有自动生成结构的类型级表示的 GraphQL 服务器的示例实现:
英:Example implementation of a GraphQL server with type-level representation of the schema auto-generated:
{-# LANGUAGE DataKinds #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PartialTypeSignatures #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-}
-- imports omitted for brevity...
graphql "Library" "library.graphql" -- all the magic happens here! 🪄🎩
-- ... a bit more code...
libraryServer :: SqlBackend -> ServerT ObjectMapping i Library ServerErrorIO libraryServer conn = resolver ( object @"Book" ( field @"id" bookId, field @"title" bookTitle, field @"author" bookAuthor, field @"imageUrl" bookImage ), object @"Author" ( field @"id" authorId, field @"name" authorName, field @"books" authorBooks ), object @"Query" ( method @"authors" allAuthors, method @"books" allBooks ), object @"Mutation" ( method @"newAuthor" newAuthor, method @"newBook" newBook ), object @"Subscription" (method @"allBooks" allBooksConduit) ) where bookId :: Entity Book -> ServerErrorIO Integer bookId (Entity (BookKey k) ) = pure $ toInteger k -- ... more resolvers...
请参阅 我们的文档 了解有关如何构建自己的 GraphQL 服务器的更多信息,请参阅 库的例子 了解更多端到端示例,其中包括用 Elm 编写的客户端!
英:See our docs for more information about how to build your own GraphQL server and the library example for a more end-to-end example that includes a client written in Elm!
Hello world 以 morpheus-graphql
为例:
英:Hello world example with morpheus-graphql
:
# schema.gql"""A supernatural being considered divine and sacred"""type Deity { name: String! power: String @deprecated(reason: "no more supported")}type Query { deity(name: String! = "Morpheus"): Deity!}
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DuplicateRecordFields #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} module API (api) where import Data.ByteString.Lazy.Char8 (ByteString) import Data.Morpheus (interpreter) import Data.Morpheus.Document (importGQLDocument) import Data.Morpheus.Types (RootResolver (..), Undefined (..)) import Data.Text (Text) importGQLDocument "schema.gql" rootResolver :: RootResolver IO () Query Undefined Undefined rootResolver = RootResolver { queryResolver = Query {deity}, mutationResolver = Undefined, subscriptionResolver = Undefined } where deity DeityArgs {name} = pure Deity { name = pure name, power = pure (Just "Shapeshifting") } api :: ByteString -> IO ByteString api = interpreter rootResolver
有关更复杂的 API,请参阅 morpheus-graphql-examples。
英:See morpheus-graphql-examples for more sophisticated APIs.
graphql-w-persistent
0完整的库工具集,用于使用 SQL 抽象关系数据库结构、使用 GraphQL 查询并返回 GraphQL 结果
一次性设置:构建结构、部署为微服务或在服务器内、使用 GraphQL 查询 SQL 数据库!
英:One time setup: build schema, deploy as microservice or within server, query SQL database with GraphQL!
Haksell 中的强类型 GraphQL 客户端实现。
GQL 是 GraphQL 的 Groove 库
核心库 - GORM GraphQL 库提供了根据 GORM 实体生成 GraphQL 架构的功能。除了将域类映射到 GraphQL 结构之外,核心库还提供 "数据获取器" 的默认实现,以通过执行结构来查询、更新和删除数据。
英:Core Library - The GORM GraphQL library provides functionality to generate a GraphQL schema based on your GORM entities. In addition to mapping domain classes to a GraphQL schema, the core library also provides default implementations of "data fetchers" to query, update, and delete data through executions of the schema.
Grails 插件 - 除了核心库之外,GORM GraphQL Grails 插件:
英:Grails Plugin - In a addition to the Core Library, the GORM GraphQL Grails Plugin:
根据其指南,提供一个控制器来通过 HTTP 接收和响应 GraphQL 请求。
英:Provides a controller to receive and respond to GraphQL requests through HTTP, based on their guidelines.
在启动时使用 spring bean 配置生成结构,以使其易于扩展。
英:Generates the schema at startup with spring bean configuration to make it easy to extend.
包括开发中默认启用的 GraphiQL 浏览器。可以通过 /graphql/browser 访问浏览器。
英:Includes a GraphiQL browser enabled by default in development. The browser is accessible at /graphql/browser.
覆盖默认数据绑定以使用 Grails 提供的数据绑定
英:Overrides the default data binder to use the data binding provided by Grails
提供 trait 使 GraphQL 端点的集成测试更容易
英:Provides a trait to make integration testing of your GraphQL endpoints easier
请参阅 文档 了解更多信息。
英:See the documentation for more information.
graphql-go-tools 实现了构建 GraphQL 服务器、网关和代理服务器的所有基本块。从词法分析、解析、验证、规范化,一直到查询规划和执行。
英:graphql-go-tools implements all basic blocks for building GraphQL Servers, Gateways and Proxy Servers. From lexing, parsing, validation, normalization, all the way up to query planning and execution.
它也可以理解为一个 GraphQL 编译器,能够添加自己的后端。只需实现一些接口,你就可以教编译器如何与任何后端进行 GraphQL 对话。
英:It can also be understood as a GraphQL Compiler, with the ability to add your own backends. Just by implementing a few interfaces, you're able to teach the compiler how to talk GraphQL to any backend.
以下后端已经实现:GraphQL,支持 Apollo Federation / Supergraph。数据库:PostgreSQL、MySQL、SQLite、CockroachDB、MongoDB、SQLServer、开放 API / 剩余 和 Kafka。
英:The following backends are already implemented: GraphQL, with support for Apollo Federation / Supergraph. Databases: PostgreSQL, MySQL, SQLite, CockroachDB, MongoDB, SQLServer, OpenAPI / REST and Kafka.
要了解如何实现新的后端,请查看 静态数据源,因为它是最简单的。
英:To get a sense on how to implement a new backend, check out the Static Data Source, as it's the simplest one.
它已被许多企业在生产中使用多年,经过实际测试并积极维护。
英:It's used in production by many enterprises for multiple years now, battle tested and actively maintained.
具有简单结构构建、实时查询和批处理功能的 GraphQL 实现。
一个 Go/Golang 库,可帮助构建支持 React-relay 的 graphql-go 服务器。
Go / Golang 的 GraphQL 实现。
注重易用性的 GraphQL 服务器。
使用 Go 开发符合规范的 GraphQL 服务器。
Eggql 的目的是让创建 GraphQL 服务器尽可能简单。你不需要创建 GraphQL 结构(尽管你可以根据兴趣查看创建的结构)。它目前处于测试版本,但除了订阅之外,它是 GraphQL 服务器的完整实现。
英:The purpose of Eggql is to make it as simple as possible to create a GraphQL server. You don't need to create GraphQL schema (though you can view the schema that is created if interested). It is currently in beta release but is a complete implementation of a GraphQL server apart from subscriptions.
需要明确的是,它支持所有这些 GraphQL 功能:参数(包括默认值)、对象/列表/枚举/输入/接口/联合类型、别名、片段、变量、指令、变更、内联片段、描述、内省和自定义标量。
英:Just to be clear it supports all of these GraphQL features: arguments (including defaults), objects/lists/enums/input/interface/union types, aliases, fragments, variables, directives, mutations, inline fragments, descriptions, introspection and custom scalars.
测试(jMeter)表明,对于简单查询,它与其他 Go 实现一样快或更快。我们正在致力于增强性能,包括缓存、数据加载器、复杂性限制等。
英:Tests (jMeter) show that it is as fast or faster than other Go implementations for simple queries. We're working on enhancements for performance including caching, data-loader, complexity-limits, etc.
要运行 eggql
hello world 服务器,只需构建并运行此 Go 程序:
英:To run an eggql
hello world server just build and run this Go program:
package main
import "github.com/andrewwphillips/eggql"
func main() { http.Handle("/graphql", eggql.New(struct{ Message string }{Message: "hello, world"})) http.ListenAndServe(":80", nil)}
这将创建一个具有单个 message
字段的根查询对象。要测试它,请使用 curl 发送查询:
英:This creates a root Query object with a single message
field. To test it send a query with curl:
$ curl -XPOST -d '{"query": "{ message }"}' localhost:80/graphql
你会得到这样的回应:
英:and you will get this response:
{ "data": { "message": "hello, world" }}
Go 生成基于 graphql 服务器库。
一个优雅的 GraphQL 底层 HTTP 客户端。
Go 中的 GraphQL 客户端实现。
具有修改、查询和订阅支持的 GraphQL Go 客户端。
genqlient 是一个 Go 库,可以轻松生成类型安全的代码来查询 GraphQL API。它利用 GraphQL 和 Go 都是类型化语言这一事实来确保你的代码在编译时进行有效的 GraphQL 查询并正确使用结果,所有这些都使用最少的样板文件。
英:genqlient is a Go library to easily generate type-safe code to query a GraphQL API. It takes advantage of the fact that both GraphQL and Go are typed languages to ensure at compile-time that your code is making a valid GraphQL query and using the result correctly, all with a minimum of boilerplate.
genqient 提供:
英:genqlient provides:
GraphQL 查询的编译时验证:再也不会发送无效的 GraphQL 查询!
英:Compile-time validation of GraphQL queries: never ship an invalid GraphQL query again!
类型安全的响应对象:genqlient 为每个查询生成正确的类型,因此你知道响应将正确解组并且永远不需要使用 interface{}
。
英:Type-safe response objects: genqlient generates the right type for each query, so you know the response will unmarshal correctly and never need to use interface{}
.
生产准备情况:genqlient 用于可汗学院的生产,为世界各地数百万学习者和教师提供支持。
英:Production-readiness: genqlient is used in production at Khan Academy, where it supports millions of learners and teachers around the world.
即时 GraphQL 到 SQL 编译器。用作独立服务或 Go 库。以前是超级图。
Flutter 中的 GraphQL 客户端实现。
Ferry 是一个简单、强大的 Flutter 和 Dart GraphQL 客户端。
Erlang 中的 GraphQL 实现。
用于为 GraphQL 端点创建类型安全的 Elm 代码的库和命令行代码生成器。
Facebook GraphQL 的 Elixir 实现。
Elixir 的 GraphQL 实现。
Elixir 的 GraphQL 客户端
支持 HTTP 和 WebSocket 的 Elixir GraphQL 客户端
D 编程语言的 GraphQL 实现。
GraphQL 规范的完整实现,旨在保持外部对规范的合规性。
使用 graphql-clj
执行 hello world GraphQL 查询的代码:
英:Code that executes a hello world GraphQL query with graphql-clj
:
(def schema "type QueryRoot { hello: String }")
(defn resolver-fn [type-name field-name] (get-in {"QueryRoot" {"hello" (fn [context parent & rest] "Hello world!")}} [type-name field-name]))
(require '[graphql-clj.executor :as executor])
(executor/execute nil schema resolver-fn "{ hello }")
(require '[alumbra.core :as alumbra] '[claro.data :as data])
(def schema "type Person { name: String!, friends: [Person!]! } type QueryRoot { person(id: ID!): Person, me: Person! } schema { query: QueryRoot }")
(defrecord Person [id] data/Resolvable (resolve! [_ _] {:name (str "Person #" id) :friends (map ->Person (range (inc id) (+ id 3)))}))
(def QueryRoot {:person (map->Person {}) :me (map->Person {:id 0})})
(def app (alumbra/handler {:schema schema :query QueryRoot}))
(defonce my-graphql-server (aleph.http/start-server #'app {:port 3000}))
$ curl -XPOST "http://0:3000" -H'Content-Type: application/json' -d'{ "query": "{ me { name, friends { name } } }"}'{"data":{"me":{"name":"Person #0","friends":[{"name":"Person #1"},{"name":"Person #2"}]}}}
用 Clojurescript 实现的 GraphQL 客户端,支持 Websocket。
一组用于在 .NET 中实现高性能 GraphQL 服务器的包。忠实执行 2018 年官方规范。具有批量执行支持(又名数据加载器);支持自定义标量;基于 ASP.NET Core 的 HTTP 服务器;解析查询缓存;模块化 API 构建(相当于模式拼接);全面的内省支持;运行时指标和配额。
Hot Chocolate 消除了构建成熟的 GraphQL 服务器的复杂性,让你专注于交付下一个重大成果。
英:Hot Chocolate takes the complexity away from building a fully-fledged GraphQL server and lets you focus on delivering the next big thing.
using Microsoft.AspNetCore;using Microsoft.AspNetCore.Hosting;using Microsoft.AspNetCore.Builder;using Microsoft.Extensions.DependencyInjection;
WebHost .CreateDefaultBuilder(args) .ConfigureServices(services => services .AddGraphQLServer() .AddQueryType<Query>()) .Configure(builder => builder .UseRouting() .UseEndpoints(e => e.MapGraphQL())) .Build() .Run();
public class Query{ public Hero GetHero() => new Hero();}
public class Hero{ public string Name => "Luke Skywalker";}
将 GraphQL 转换为 IQueryable
using System;using System.Threading.Tasks;using GraphQL;using GraphQL.Types;using GraphQL.SystemTextJson; // First add PackageReference to GraphQL.SystemTextJson
public class Program{ public static async Task Main(string[] args) { var schema = Schema.For(@" type Query { hello: String } ");
var json = await schema.ExecuteAsync(_ => { _.Query = "{ hello }"; _.Root = new { Hello = "Hello World!" }; });
Console.WriteLine(json); }}
Entity GraphQL
0适用于 .NET Core 的 GraphQL 库。轻松将数据模型公开为 GraphQL API,或将多个数据源整合到单个 GraphQL 模式中。
// expose an exisiting data model with ASP.NET & EF Corepublic class Startup { public void ConfigureServices(IServiceCollection services) { services.AddDbContext<DemoContext>(); // Auto build a schema from DemoContext. Alternatively you can build one from scratch services.AddGraphQLSchema<DemoContext>(options => { // modify the schema (add/remove fields or types), add other services }); }
public void Configure(IApplicationBuilder app, DemoContext db) { app.UseRouting(); app.UseEndpoints(endpoints => { // defaults to /graphql endpoint endpoints.MapGraphQL<DemoContext>(); }); }}
ZeroQL 是一个高性能 C# 友好的 GraphQL 客户端。它支持类似 Linq 的语法,并且不需要 Reflection.Emit 或表达式。因此,运行时提供的性能非常接近原始 HTTP 调用。
英:The ZeroQL is a high-performance C#-friendly GraphQL client. It supports Linq-like syntax, and doesn't require Reflection.Emit or expressions. As a result, at runtime provides performance very close to a raw HTTP call.
你可以使用 ZeroQL 来:
英:You can use ZeroQL to:
从 GraphQL 结构生成 C# 客户端。
英:Generate a C# client from GraphQL schema.
从 C# 代码生成并执行 graphql 查询。
英:Generate and execute graphql queries from your C# code.
不需要手动编写 GraphQL。
英:Don't require writing GraphQL manually.
支持.Net Core、.Net Framework、Xamarin、Unity 应用。
英:Supports .Net Core, .Net Framework, Xamarin, Unity apps.
var userId = 10;var response = await qlClient.Query(q => q .User(userId, o => new { o.Id, o.FirstName, o.LastName }));
Strawberry Shake 消除了状态管理的复杂性,并允许你通过 GraphQL 与本地和远程数据进行交互。
英:Strawberry Shake removes the complexity of state management and lets you interact with local and remote data through GraphQL.
你可以使用草莓奶昔来:
英:You can use Strawberry Shake to:
从 GraphQL 查询生成 C# 客户端。
英:Generate a C# client from your GraphQL queries.
通过 GraphQL 与本地和远程数据交互。
英:Interact with local and remote data through GraphQL.
使用响应式 API 与你的状态进行交互。
英:Use reactive APIs to interact with your state.
client.GetHero .Watch(ExecutionStrategy.CacheFirst) .Subscribe(result => { Console.WriteLine(result.Data.Name); })
支持从 C# 类生成查询的 GraphQL 客户端
.NET 的基本示例 GraphQL 客户端。
适用于 .NET 的 GraphQL 客户端。
具有 C 和 C++ API 的 C++ GraphQL 查询语言解析器。
要运行 ballerina-graphql
hello world 服务器:
英:To run a ballerina-graphql
hello world server:
下载并安装 Ballerina 语言
英:Download and install Ballerina Language
然后运行 bal run graphql_service.bal
来运行服务,graphql_service.bal
文件中包含以下代码:
英:Then run bal run graphql_service.bal
to run the service, with this code in the graphql_service.bal
file:
import ballerina/graphql;
service /graphql on new graphql:Listener(9090) { resource function get hello() returns string { return "Hello, world!"; }}
英:Features
采用 Ballerina service
和 listener
型号打造,为 Ballerina 中的一等公民
英:Built with Ballerina service
and listener
model, which are first-class citizens in Ballerina
支持通过 websocket 订阅(无需额外的库)
英:Supports subscriptions over websocket (No additional libraries needed)
支持文件上传
英:Supports file upload
内置 GraphiQL 客户端
英:Built-in GraphiQL client
要运行 ballerina-graphql
客户端:
英:To run a ballerina-graphql
client:
下载并安装 Ballerina 语言
英:Download and install Ballerina Language
然后运行 bal run graphql_client.bal
来运行服务,graphql_client.bal
文件中包含以下代码:
英:Then run bal run graphql_client.bal
to run the service, with this code in the graphql_client.bal
file:
import ballerina/graphql;import ballerina/io;
type Response record { record { string hello; } data;};
public function main() returns error? { graphql:Client helloClient = check new ("localhost:9090/graphql"); string document = "{ hello }"; Response response = check helloClient->execute(document); io:println(response.data.hello);}
英:Features