GraphQL 是一种用于构建 API 的查询语言和运行时,它是一种比 RESTful API 更具有优势的 API 设计方式,它提供了一个强大的查询语言,让客户端可以查询获取到精确需要的数据,具有强大的灵活性和可扩展性。然而,GraphQL 提供的数据分析能力却不如传统数据库查询语言 SQL 那样强大。
本文将介绍如何结合一个可视化数据分析工具 Metabase,来实现对 GraphQL API 的数据分析,让我们从例子开始。
准备工作
为了演示用例,我们先要构建一个 GraphQL API,并在其上开发一些功能(示例中使用 nodejs)。
首先,我们需要安装依赖包,包括 express 服务器,graphql 库和相关插件:
npm init -y npm install express graphql express-graphql faker
接着,我们需要编写基本的 schema 和 resolvers,为其中的“users”添加一些字段:
// www.javascriptcn.com code example
const {
GraphQLSchema,
GraphQLObjectType,
GraphQLString,
GraphQLList,
GraphQLInt,
} = require('graphql');
const faker = require('faker');
const UserType = new GraphQLObjectType({
name: 'User',
fields: {
id: { type: GraphQLInt },
name: { type: GraphQLString },
email: { type: GraphQLString },
posts: {
type: GraphQLList(PostType),
resolve(parent, args) {
return fetch(`/users/${parent.id}/posts`).then(res => res.json());
},
},
},
});
const PostType = new GraphQLObjectType({
name: 'Post',
fields: {
id: { type: GraphQLInt },
title: { type: GraphQLString },
body: { type: GraphQLString },
},
});
const RootQueryType = new GraphQLObjectType({
name: 'Query',
fields: {
users: {
type: GraphQLList(UserType),
args: {
limit: { type: GraphQLInt, defaultValue: 10 },
},
resolve(parent, args, ctx) {
return fetch(`/users?_limit=${args.limit}`).then(res => res.json());
},
},
},
});
const schema = new GraphQLSchema({
query: RootQueryType,
});到此为止,我们已经准备好一个基本的 GraphQL API,它能够处理从客户端的查询,并返回数据结果。
集成 Metabase
接下来,我们便可以通过 Metabase 来连接 API 数据,进行数据分析。
首先,我们需要安装 Metabase。根据不同的操作系统进行安装,Mac 电脑可以通过以下命令来安装:
brew install metabase
安装完成后,我们可以通过以下命令来启动 Metabase:
$ brew services start metabase Starting `metabase`... (might take a few seconds) ==> Successfully started `metabase` (label: homebrew.mxcl.metabase)
启动 Metabase 后,我们可以通过访问 http://localhost:3000 来访问 Metabase。在首次访问时,需要进行初始化配置,包括数据库配置。这里我们使用数据库 SQLite 进行数据存储。
成功配置后,我们可以在 Metabase 中添加数据源(即 API),并开始进行数据分析。
数据分析
打开 Metabase 中的数据分析面板后,我们可以创建一个查询,查询我们先前所构建的 GraphQL API 的数据。
选择“New Query”,在“Pick a database”中选择“API”,在 URL 处添加我们所构建的 GraphQL API 地址,如 http://localhost:4000/graphql。
接着,我们可以在 SQL 编辑器中构建一个查询,来获取 API 中“users”选项的前 10 个数据。
{
users(limit: 10) {
id
name
email
}
}运行后,我们可以在 Metabase 的可视化面板中看到获取到的数据。

除了展示 API 中的数据,Metabase 还提供了许多统计、汇总、筛选等常用的数据分析功能,例如将上述表格按照 email 字段进行分组、排序,显示总数、平均数、最大值等统计数据。

结语
本文简单地介绍了如何集成 Metabase,将 GraphQL API 数据进行可视化的分析,Metabase 提供了丰富的功能和可扩展性,可以适用于各种数据分析和可视化的需求。
如果你正在开发一个 GraphQL API,希望通过数据分析来获取更多的洞察力,那么 Metabase 也许是一个值得尝试的选择。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67cfcab2e46428fe9ebc83aa