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

相关推荐
程序员岳焱2 分钟前
16.Java Annotation注解:元数据与代码增强
java·后端·编程语言
瀚海澜生4 分钟前
redis系列(2)——AOF日志和RDB快照
后端
面朝大海,春不暖,花不开1 小时前
Spring Security默认配置覆盖指南
java·后端·spring
Java技术小馆2 小时前
打印高质量日志的10条军规
java·后端·面试
陈随易3 小时前
Element Plus 2.10.0 重磅发布!新增Splitter组件
前端·后端·程序员
陈随易3 小时前
2025年100个产品计划之第11个(哆啦工具箱) - 像哆啦A梦口袋一样丰富的工具箱
前端·后端·程序员
PetterHillWater3 小时前
Automa-RPA实现京东商品自动搜索
后端
肖笙XiaoSheng4 小时前
用Gemini调整我的定时任务代码
后端·aigc·ai编程
WindSearcher4 小时前
OAuth协议
后端
LanLance4 小时前
ES101系列09 | 运维、监控与性能优化
java·运维·后端·elasticsearch·云原生·性能优化·golang