搭建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实践

代码

相关推荐
海梨花5 分钟前
【从零开始学习Redis】项目实战-黑马点评D2
java·数据库·redis·后端·缓存
bug菌8 分钟前
零基础也能做出AI应用?Trae是如何打破编程"高墙"的?
后端·ai编程·trae
Java技术小馆14 分钟前
重构 Controller 的 7 个黄金法则
java·后端·面试
用户40993225021225 分钟前
容器化部署FastAPI应用:如何让你的任务系统代码在云端跳舞?
后端·ai编程·trae
Java水解26 分钟前
MySQL 亿级数据表平滑分表实践:基于时间分片的架构演进
后端·mysql
Neo25533 分钟前
Spring 5.3.x 源码:invokeBeanFactoryPostProcessors()详解
后端
金銀銅鐵34 分钟前
[Java] 以 IntStream 为例,浅析 Stream 的实现
java·后端
Neo25538 分钟前
Spring 5.3.x 源码:refresh()方法
后端
码事漫谈1 小时前
C++面试中的手写快速排序:从基础到最优的完整思考过程
后端