关于后端:搭建GraphQL服务

42次阅读

共计 1313 个字符,预计需要花费 4 分钟才能阅读完成。

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 服务器


Golang 版

入门教程

Go 罕用的 GraphQL 服务端库

graphql-go/graphql 我的项目的 demo:

(文档点此)

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 实际

代码

本文由 mdnice 多平台公布

正文完
 0