搭建GraphQL服务

js版

GraphQL在 NodeJS 服务端中使用最多

安装graphql-yoga:

npm install graphql-yoga

新建index.js:

复制代码
const {GraphQLServer} = require("graphql-yoga")


const server = new GraphQLServer({
    typeDefs: `
    type Query {
        hello(name:String):String!
        } 
    `,

    resolvers: {
        Query: {
            hello: (parent, {name}, ctx) => {
                return `${name},你好!`;
            }
        }
    }
})


server.start({
    port: 4600
}, ({port}) => {
    console.log(`服务器已启动,请访问: http://localhost:${port}`);
})

node index.js 运行

点击链接 进入playground:

复制代码
query{
  hello(name:"dashen")
}

参考自 5分钟快速搭建一个Graphql服务器[1]


Golang版

入门教程[2]

Go常用的GraphQL服务端库[3]

graphql-go/graphql[4]项目的demo:

(文档点此[5])

复制代码
package main

import (
 "encoding/json"
 "fmt"
 "log"

 "github.com/graphql-go/graphql"
)

func main() {
 // Schema
 fields := graphql.Fields{
  "hello": &graphql.Field{
   Type: graphql.String,
   Resolve: func(p graphql.ResolveParams) (interface{}, error) {
    return "world", nil
   },
  },
 }
 rootQuery := graphql.ObjectConfig{Name: "RootQuery", Fields: fields}
 schemaConfig := graphql.SchemaConfig{Query: graphql.NewObject(rootQuery)}
 schema, err := graphql.NewSchema(schemaConfig)
 if err != nil {
  log.Fatalf("failed to create new schema, error: %v", err)
 }

 // Query
 query := `
  {
   hello
  }
 `
 params := graphql.Params{Schema: schema, RequestString: query}
 r := graphql.Do(params)
 if len(r.Errors) > 0 {
  log.Fatalf("failed to execute graphql operation, errors: %+v", r.Errors)
 }
 rJSON, _ := json.Marshal(r)
 fmt.Printf("%s \n", rJSON) // {"data":{"hello":"world"}}
}

执行输出

{"data":{"hello":"world"}}

基于此项目的实践,参考

Graphql Go 基于Golang实践[6]

代码[7]

参考资料

1

5分钟快速搭建一个Graphql服务器: https://www.bilibili.com/video/BV1db41137BT

2

入门教程: https://graphql.cn/learn/

3

Go常用的GraphQL服务端库: https://graphql.cn/code/#go

4

graphql-go/graphql: https://github.com/graphql-go/graphql

5

文档点此: https://pkg.go.dev/github.com/graphql-go/graphql

6

Graphql Go 基于Golang实践: https://www.jianshu.com/p/16719baa1713

7

代码: https://github.com/gopherteam/graphql-server-go

本文由mdnice多平台发布

相关推荐
北风toto6 小时前
Spring Boot / Spring Cloud 配置文件加密详解:使用 jasypt-spring-boot 实现 ENC() 加密
spring boot·后端·spring cloud
代码羊羊6 小时前
Rust 格式化输出完全攻略:从入门到精通
开发语言·后端·rust
Rust研习社7 小时前
Rust + PostgreSQL 极简技术栈应用开发
开发语言·数据库·后端·http·postgresql·rust
geovindu7 小时前
go:Template Method Pattern
开发语言·后端·设计模式·golang·模板方法模式
白晨并不是很能熬夜7 小时前
【RPC】第 4 篇:服务发现 — Zookeeper + 缓存容错
java·后端·程序人生·缓存·zookeeper·rpc·服务发现
我这一拳20年的功力7 小时前
深入解析 XXL-JOB 核心原理:从 Quartz 到自研时间轮
后端
MgArcher7 小时前
一个下划线表示“别动”,两个下划线表示“真别动”!Python属性访问控制,看懂这篇就够了
后端
ltl7 小时前
【大模型基础设施工程】19:Agent 框架工程
后端
Leinwin7 小时前
Claude 四月宕机七次:从一次事故看企业级 AI 部署的容灾设计
后端·python·flask
是希燃亚7 小时前
hermes迁移手册,将hermes迁移到不同服务器~
后端·github