一个使用Golang和PostgreSQL的GraphQL完整例子

340 阅读1分钟

使用Golang的GraphQL

一个使用Golang和PostgreSQL的GraphQL完整例子

安装

安装依赖项

go get github.com/graphql-go/graphql
go get github.com/graphql-go/handler
go get github.com/lib/pq

安装并创建postgres数据库

brew install postgres
createuser graphql --createdb
createdb graphql -U graphql
psql graphql -U graphql

注意:非Mac用户请按照官方文档来安装PostgreSQL

创建表

CREATE TABLE IF NOT EXISTS authors
(
    id serial PRIMARY KEY,
    name varchar(100) NOT NULL,
    email varchar(150) NOT NULL,
    created_at date
);

CREATE TABLE IF NOT EXISTS posts
(
    id serial PRIMARY KEY,
    title varchar(100) NOT NULL,
    content text NOT NULL,
    author_id int,
    created_at date
);

使用方法

查询获得所有作者的信息

query {
  authors {
    id
    name
    email
    created
  }
}

查询获得特定的作者

query {
  author(id: 1) {
    id
    name
    email
  }
}

使用突变法创建新的作者

mutation {
  createAuthor(name: "Sohel Amin", email: "sohelamincse@gmail.com") {
    id
    name
    email
  }
}

使用突变来更新一个作者

mutation {
  updateAuthor(id: 2, name: "Sohel Amin Shah", email: "sohel@sohelamin.com") {
    id
    name
    email
  }
}

使用突变删除一个作者

mutation {
  deleteAuthor(id: 2) {
    id
  }
}

获取与作者有关的帖子的查询

query {
  posts {
    id
    title
    content
    author {
      id
      name
      email
    }
  }
}