absinthe elixir 的graphql 框架简单试用

发布时间 2024-01-03 19:20:37作者: 荣锋亮

absinthe elixir 的graphql 框架

包含的特性

  • graphql 草案的完整实现
  • 插件化设计
  • 异步字段解析以及批量解析,同时支持插件化的解析支持
  • 安全
  • 包含了基于GraphiQL 的playground

项目测试

基于了phoenix 框架

  • 创建phoenix 项目
mix phx.new absinthe_phx
  • 添加sqlite ecto依赖
    默认phoenix 使用了pg,对于本地测试不是很方便(如果基于docker 就比较方便了),所以调整为了基于sqlite 的
 
{:ecto_sqlite3, "~> 0.14.0"},

调整repo adapter 配置

defmodule AbsinthePhx.Repo do
  use Ecto.Repo,
    otp_app: :absinthe_phx,
    adapter: Ecto.Adapters.SQLite3
  • 添加graphql 实体&解析器&以及查询定义&endpoint 定义
    实体
 
defmodule AbsinthePhxWeb.Schema.ContentTypes do
  use Absinthe.Schema.Notation
 
  object :post do
    field :id, :id
    field :title, :string
    field :body, :string
  end
end

解析

defmodule AbsinthePhxWeb.Resolvers.Content do
  def list_posts(_parent, _args, _resolution) do
    {:ok, [%{id: 1, title: "Hello", body: "World"}]}
  end
 
end

查询

defmodule AbsinthePhxWeb.Schema do
  use Absinthe.Schema
  import_types AbsinthePhxWeb.Schema.ContentTypes
 
  alias AbsinthePhxWeb.Resolvers
 
  query do
 
    @desc "Get all posts"
    field :posts, list_of(:post) do
      resolve &Resolvers.Content.list_posts/3
    end
 
  end
 
end

endpoint 定义(在router 中添加)

scope "/api" do
  pipe_through :api
 
  forward "/graphiql", Absinthe.Plug.GraphiQL,
    schema: AbsinthePhxWeb.Schema
 
  forward "/", Absinthe.Plug,
    schema: AbsinthePhxWeb.Schema
 
end

访问&测试

  • 启动
mix phx.server

访问
http://localhost:4000/api/graphiql
效果

说明

absinthe star 还是很多的,比较强大,同时还提供了类似 facebook dataloader 的工具 ,对于选择elixir做为开发框架的项目值得学习下

参考资料

https://github.com/absinthe-graphql/absinthe
http://absinthe-graphql.org/
https://hexdocs.pm/absinthe/dataloader.html
https://www.phoenixframework.org/
https://hexdocs.pm/absinthe/our-first-query.html
https://hexdocs.pm/absinthe/subscriptions.html