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

相关推荐
计算机毕设指导621 分钟前
基于Springboot学生宿舍水电信息管理系统【附源码】
java·spring boot·后端·mysql·spring·tomcat·maven
计算机-秋大田29 分钟前
基于Spring Boot的兴顺物流管理系统设计与实现(LW+源码+讲解)
java·vue.js·spring boot·后端·spring·课程设计
羊小猪~~2 小时前
MYSQL学习笔记(九):MYSQL表的“增删改查”
数据库·笔记·后端·sql·学习·mysql·考研
豌豆花下猫2 小时前
Python 潮流周刊#90:uv 一周岁了,优缺点分析(摘要)
后端·python·ai
橘猫云计算机设计3 小时前
基于SSM的《计算机网络》题库管理系统(源码+lw+部署文档+讲解),源码可白嫖!
java·数据库·spring boot·后端·python·计算机网络·毕设
熬夜苦读学习3 小时前
Linux文件系统
linux·运维·服务器·开发语言·后端
坚定信念,勇往无前4 小时前
Spring Boot 如何保证接口安全
spring boot·后端·安全
程序员侠客行5 小时前
Spring事务原理详解 三
java·后端·spring·架构
Hello.Reader6 小时前
深入理解 Rust 的 `Rc<T>`:实现多所有权的智能指针
开发语言·后端·rust
yoona10206 小时前
Rust编程语言入门教程(八)所有权 Stack vs Heap
开发语言·后端·rust·区块链·学习方法