搭建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 小时前
【养虾日记】Openclaw操作浏览器自动化发文
人工智能·后端·算法
江湖十年6 小时前
Go 并发控制:sync.Pool 详解
后端·面试·go
jwn9997 小时前
Spring Boot 整合 Keycloak
java·spring boot·后端
mldlds7 小时前
SpringBoot详解
java·spring boot·后端
kang_jin7 小时前
Spring Boot 自动配置
java·spring boot·后端
yuweiade7 小时前
Spring Boot中使用Server-Sent Events (SSE) 实现实时数据推送教程
java·spring boot·后端
小箌8 小时前
springboot_03
spring boot·后端·状态模式
冬奇Lab8 小时前
一天一个开源项目(第54篇):Supabase - 开源的 Postgres 开发平台,Firebase 替代方案
后端·开源·资讯
中年程序员一枚9 小时前
spring-cloud-starter-openfeign现实中的运行逻辑
java·spring boot·后端
why技术9 小时前
我拿到了腾讯QClaw的内测码,然后沉默了。
前端·后端