搭建GraphQL服务

js版

GraphQL在 NodeJS 服务端中使用最多

安装graphql-yoga:

npm install graphql-yoga

新建index.js:

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:

sql 复制代码
query{
  hello(name:"dashen")
}

参考自 5分钟快速搭建一个Graphql服务器


Golang版

入门教程

Go常用的GraphQL服务端库

graphql-go/graphql项目的demo:

(文档点此)

go 复制代码
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实践

代码

相关推荐
稚辉君.MCA_P8_Java3 小时前
JVM第二课:一文讲透运行时数据区
jvm·数据库·后端·容器
Elsa️7465 小时前
个人项目开发(1):使用Spring Secruity实现用户登录
java·后端·spring
麦芽糖02196 小时前
springboot集成ZeroMQ
java·spring boot·后端
大鱼七成饱6 小时前
Rust 多线程编程入门:从 thread::spawn 步入 Rust 并发世界
后端·rust
码事漫谈6 小时前
深入剖析:C++、C 和 C# 中的 static
后端
码事漫谈6 小时前
AI智能体全球应用调查报告:从“对话”到“做事”的变革
后端
绝无仅有7 小时前
某大厂跳动Java面试真题之问题与解答总结(二)
后端·面试·github
绝无仅有7 小时前
某大厂跳动Java面试真题之问题与解答总结(三)
后端·面试·架构
野犬寒鸦7 小时前
从零起步学习Redis || 第十章:主从复制的实现流程与常见问题处理方案深层解析
java·服务器·数据库·redis·后端·缓存
江上月51310 小时前
django与vue3的对接流程详解(上)
后端·python·django