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

相关推荐
Rexi几秒前
go如何写单元测试1
后端
Harry技术30 分钟前
Spring Boot 4.0 发布总结:新特性、依赖变更与升级指南
spring boot·后端
武子康41 分钟前
大数据-159 Apache Kylin Cube 实战:Hive 装载与预计算加速(含 Cuboid/实时 OLAP,Kylin 4.x)
大数据·后端·apache kylin
疯狂的程序猴1 小时前
Mac 抓包软件怎么选?从 HTTPS 调试、TCP 数据流分析到多工具协同的完整抓包方案
后端
BingoGo1 小时前
使用 PHP 和 Raylib 也可以开发贪吃蛇游戏
后端·php
爱分享的鱼鱼1 小时前
Spring Boot如何整合Redis
后端
知其然亦知其所以然1 小时前
别再被问住!Redis Cluster 一文彻底讲透(Java 面试必背)
redis·后端·面试
codercwh1 小时前
3 分钟上手 Claude Code!API 中转站让 AI 编程效率翻倍
后端
SimonKing1 小时前
OCR告别付费!分享两款可部署的开源工具
后端
爱叫啥叫啥2 小时前
STM32从零实战:深入理解RCC时钟与按键控制LED的底层原理
后端