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

相关推荐
言慢行善7 分钟前
SpringBoot中的注解介绍
java·spring boot·后端
小村儿11 分钟前
连载05-Claude Skill 不是抄模板:真正管用的 Skill,都是从实战里提炼出来的
前端·后端·ai编程
光电大美美-见合八方中国芯34 分钟前
用于无色波分复用光网络的 10.7 Gb/s 反射式电吸收调制器与半导体光放大器单片集成
网络·后端·ai·云计算·wpf·信息与通信·模块测试
MX_93591 小时前
Spring MVC拦截器
java·后端·spring·mvc
MgArcher1 小时前
Python高级特性:高阶函数完全指南
后端·面试
databook1 小时前
逃离SQL丛林:实用主义的数据救赎
后端·sql·数据分析
舒一笑2 小时前
AI 系统落地难的,从来不只是模型:一次企业级部署实施复盘
运维·后端·程序员
心勤则明2 小时前
Spring AI Alibaba Skills 的渐进式披露与热更新实战
java·后端·spring
金融数据出海3 小时前
java对接美股股票api涵盖实时行情、K 线、指数等核心接口。
后端
认真的小羽❅3 小时前
从入门到精通:Spring Boot 整合 MyBatis 全攻略
spring boot·后端·mybatis