搭建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多平台发布

相关推荐
OC溥哥9992 小时前
Flask论坛与个人中心页面开发教程完整详细版
后端·python·flask·html
迷知悟道3 小时前
java面向对象四大核心特征之抽象---超详细(保姆级)
java·后端
Aurora_NeAr4 小时前
对比Java学习Go——程序结构与变量
后端
AntBlack4 小时前
每周学点 AI:ComfyUI + Modal 的一键部署脚本
人工智能·后端·aigc
5大大大大雄5 小时前
docker容器日志处理
后端
我是哪吒5 小时前
分布式微服务系统架构第170集:Kafka消费者并发-多节点消费-可扩展性
后端·面试·github
Badman6 小时前
分布式系统下的数据一致性-Redis分布式锁
redis·分布式·后端
Java水解6 小时前
盘点那些自带高级算法的SQL
后端
一只叫煤球的猫7 小时前
2025年基于Java21的的秒杀系统要怎么设计?来点干货
后端·面试·性能优化
方圆想当图灵7 小时前
《生产微服务》评估清单 CheckList
后端·微服务