Rails 业余程序员,想要找一个完整的 GraphQL 的教程和案例

lukefan · February 09, 2020 · Last by lukefan replied at February 22, 2020 · 3636 hits

我现在只能算是一个业余程序员了。 想要找一些 GraphQL 完整的教程和案例。 网上很多好像都是一些 get start 之类的东西。 详细的,也多是 nodejs 的,不是 rails 的。 我现在可以建立简单的 graphql,但是每次可以返回一个记录。 但是返回多个记录,分页,查询,修改,登陆相关的,还不太会玩儿。 本站的一些相关帖子,使用的版本太旧,参考价值已经降低了。

请多多帮忙。

field :person, PersonType, null: true do
    argument :id, ID, required: true
end

def person(id:)
    Person.find(id)
  end

  field :people, Types::PersonType, null: false

  def people
    ::Person.all
  end

我照着网上的例子,把 query 写成这样。 curl -XPOST -d 'query={person(id:6) {id name age desc}}' http://localhost:3000/graphql 可以工作

curl -XPOST -d 'query={people {person{name}}}' http://localhost:3000/graphql 就出不来了。

案例看 bluedoc,去 github 搜

graphql 不成熟

graphql 非常成熟,我们生产环境使用 1 年多了,非常好 后端使用 graphql 这个 gem (https://graphql-ruby.org/),配合 graphiql-rails 做开发环境的调试,开发起来非常顺畅。 前端如果使用 react 的话,推荐使用 react-apollo

指南的话看 graphql-ruby 的文档基本就够了,推荐 https://www.howtographql.com/graphql-ruby/0-introduction/ 不过也是基于 1.8 的版本,现在最新的版本全面 class 化了,在 type mutation query 的定义上有所差别,不过对阅读和上手 graphql 影响也不大。

非常感谢。准备尝试一下。 遇到个奇怪的问题,我的字段或函数中如果有下划线,就报错。 比如 image_url 字段,定义了,就无法使用。改成 imageurl,就对了。这是为什么啊?

field 会自动转成驼峰形式的,image_url 在前端会返回 imageUrl

Reply to robot_zhang

原来如此,还是比较有趣的。这种小点拨,还是非常有帮助的。

可以用 graphql palayground

询问一下,应该如何查询 DateTIme 格式的字段? 我在网上查了一下,有人说是要用 Types::DateTimeType,我得到了:uninitialized constant Types::DateTimeType 请问应该如何处理?

Reply to lukefan
field :created_at, GraphQL::Types::ISO8601DateTime, null: false
field :updated_at, GraphQL::Types::ISO8601DateTime, null: false

我直接这样

Reply to lidashuang

我现在是直接用 string 类型了,回头用你的方法试试。

You need to Sign in before reply, if you don't have an account, please Sign up first.