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

代码

相关推荐
java1234_小锋16 分钟前
Spring IoC的实现机制是什么?
java·后端·spring
喵个咪26 分钟前
开箱即用的 GoWind Admin|风行,企业级前后端一体中后台框架:JWT 集成指南
后端·go
绝不收费—免费看不了了联系我40 分钟前
Fastapi的单进程响应问题 和 解决方法
开发语言·后端·python·fastapi
喵个咪1 小时前
开箱即用的 GoWind Admin|风行,企业级前后端一体中后台框架:OPA 集成指南:从原理到实践
后端·go
Victor3561 小时前
Netty(11) Netty的心跳机制是什么?为什么需要它?
后端
Victor3561 小时前
Netty(12)Netty支持哪些协议和传输方式?
后端
无限大62 小时前
为什么电脑需要"内存"和"硬盘"?——存储金字塔的秘密
后端
ovensi3 小时前
Docker+NestJS+ELK:从零搭建全链路日志监控系统
后端·nestjs
武子康3 小时前
大数据-184 Elasticsearch Doc Values 机制详解:列式存储如何支撑排序/聚合/脚本
大数据·后端·elasticsearch
四月__3 小时前
http八股
后端