☰
PokeAPI GraphQL v1beta2 的 Node.js 实战:用 node-fetch 查询宝可梦全套数据
2026/10/2 8:16:38 网站建设 项目流程
  • 后端

【免费下载链接】pokeapi

The Pokémon API

项目地址:https://gitcode.com/GitHub_Trending/po/pokeapi
点击查看免费下载

本文以仓库中 graphql/v1beta2/examples/node/README.md 及其配套示例 pokemon.js 为主体,讲解如何使用 Node.js 与node-fetch调用 PokeAPI 的 GraphQL v1beta2 接口,一次查询即可拿到某只宝可梦的性格值、传说/幻兽属性、世代、栖息地、身高体重、特性、种族值、属性、升级招式、遭遇地点数、特定版本携带道具与英文图鉴描述。读完本文,你将掌握 PokeAPI GraphQL 客户端的封装方法、聚合查询(aggregate)与嵌套关系的写法,以及如何用命令行参数动态查询任意宝可梦。

示例定位:最小可运行的 GraphQL 客户端

在graphql/v1beta2/examples/目录下,官方按语言组织了多种实现:node、go各有独立文件夹,并共享一批.gql查询文件(如 pokemon_stats.gql、gen3_species.gql)。其中 Node 示例的 README 非常精简,核心就两条命令:

npm i node pokemon.js

按照 examples/README.md 的说明,所有.gql查询都可以直接在官方 GraphQL 控制台(https://beta.pokeapi.co/graphql/console/)中运行,而各语言文件夹则展示同样的查询如何在真实代码中被调用。Node 版本给出的方案是:npm i安装依赖后直接运行脚本,无需任何配置即可在终端看到 JSON 输出。

依赖与项目结构

示例的依赖清单在 package.json 中:

{ "name": "examples", "version": "1.0.0", "main": "''", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "dependencies": { "node-fetch": "^2.6.1" } }

要点:

  • 唯一运行时依赖是node-fetch@^2.6.1,即 CommonJS 版本的 fetch 实现,因此 pokemon.js 顶部直接使用const fetch = require("node-fetch")引入。
  • 版本号带^前缀,安装时会解析到 2.x 的最新兼容版本。
  • 脚本未定义test脚本(test只是占位),也没有 TypeScript、babel 等构建步骤——这是一个开箱即跑的最小示例。

GraphQL 客户端封装:fetchGraphQL

pokemon.js 的核心是一个通用请求函数:

const fetch = require("node-fetch") async function fetchGraphQL(query, variables, operationName) { const result = await fetch( "https://beta.pokeapi.co/graphql/v1beta", { method: "POST", body: JSON.stringify({ query: query, variables: variables, operationName: operationName }) } ) return await result.json() }

这段代码揭示了 GraphQL over HTTP 的标准调用方式:

  1. 端点(endpoint):写死为https://beta.pokeapi.co/graphql/v1beta,即 PokeAPI 公开的 GraphQL 网关地址。
  2. HTTP 方法:使用POST,因为 GraphQL 查询体可能很大,且 POST 便于传递变量。
  3. 请求体:包含query(查询字符串)、variables(变量对象)、operationName(操作名)三个字段,这是 GraphQL 服务器约定的标准 POST 载荷格式。
  4. 响应处理:await result.json()直接把响应解析为 JSON 对象返回,调用方再从{ errors, data }中取出结果或错误。

补充:仓库中 graphql/v1beta2/config.yaml 显示本地部署配置为endpoint: http://localhost:8080、metadata_directory: metadata、version: 3。也就是说,示例面向公网 beta 端点,而自托管部署时只需把 URL 换成你自己的 Hasura 实例地址即可复用同一套代码。

查询设计拆解:一条查询拿遍全套数据

fetchPokemon_details函数内嵌了本示例的核心 GraphQL 查询pokemon_details,它通过参数化变量$name: String精确定位宝可梦,并一次性抓取 12 类信息。下面逐段拆解(代码取自 pokemon.js):

1. 物种级信息(species)

species: pokemonspecies(where: {name: {_eq: $name}}) { name base_happiness is_legendary is_mythical generation: generation { name } habitat: pokemonhabitat { name }
  • 用where: {name: {_eq: $name}}做等值过滤,_eq是 GraphQL 后端(Hasura)风格的比较运算符。
  • base_happiness(基础亲密度)、is_legendary(传说宝可梦)、is_mythical(幻之宝可梦)都是物种表 public_pokemon_v2_pokemonspecies.yaml 中的字段。
  • 通过字段别名(alias)把关联对象重命名为generation、habitat,外层查询可以直接用这些别名引用返回结果。

2. 个体级信息(pokemon)

pokemon: pokemons_aggregate(limit: 1) { nodes { height name id weight

pokemons_aggregate是聚合查询,limit: 1取首个节点。每个宝可梦物种通常有默认形态记录,这里取一条即可获得身高(height)、体重(weight)和数据库主键id。

3. 特性(abilities)与种族值(stats)

abilities: pokemonabilities_aggregate { nodes { ability: ability { name } } } stats: pokemonstats { base_stat stat: stat { name } }
  • 特性通过pokemonabilities_aggregate聚合后嵌套展开ability的名称。
  • 种族值直接展开pokemonstats列表,每条含base_stat与关联的stat.name(如 hp、attack、defense 等)。这与数据文件 pokemon_stats.csv 的字段结构一致。

4. 升级可学招式(levelUpMoves)

levelUpMoves: pokemonmoves_aggregate( where: {movelearnmethod: {name: {_eq: "level-up"}}}, distinct_on: move_id ) { nodes { move: move { name } level } }
  • where过滤学习方式为level-up(招式学习方式对应表 pokemon_move_methods.csv)。
  • distinct_on: move_id按招式去重,避免同一招式在多版本中重复出现。
  • 返回每个招式的名称与习得等级level。

5. 遭遇地点数量(foundInAsManyPlaces)

foundInAsManyPlaces: encounters_aggregate { aggregate { count } }

用聚合函数count统计该宝可梦在多少条遭遇记录中出现。图鉴描述数据对应 encounters.csv。

6. 特定版本携带道具(fireRedItems)

fireRedItems: pokemonitems(where: {version: {name: {_eq: "firered"}}}) { item { name } rarity }

限定版本为firered(火红),返回该版本中宝可梦可携带的道具名称与稀有度rarity。对应关联表 public_pokemon_v2_pokemonitem.yaml。

7. 图鉴描述(flavorText)

flavorText: pokemonspeciesflavortexts( where: {language: {name: {_eq: "en"}}, version: {name: {_eq: "firered"}}} ) { flavor_text }

同时按语言(en)与版本(firered)过滤,取火红版本的英文图鉴描述,数据源为 pokemon_species_flavor_text.csv。

整个查询充分展示了 GraphQL 的优势:一次往返即可拿到关联了物种、个体、特性、种族值、招式、遭遇、道具、图鉴文本的多层嵌套数据,无需像 REST API 那样发起十几次请求。

命令行入口与默认参数

async function main() { const pokemon = process.argv.slice(2)[0]; const { errors, data } = await fetchPokemon_details(pokemon) if (errors) { console.error(errors) } console.log(JSON.stringify(data, null, 2)) } main()

运行逻辑非常简单:

  • process.argv.slice(2)[0]取出第一个命令行参数作为宝可梦名称;不传参数时为undefined,函数默认参数name="starmie"生效——因此脚本默认查询「宝石海星」。
  • 解构响应中的errors与data,有错误则打印到stderr,否则用JSON.stringify(data, null, 2)输出带缩进的美化 JSON。
  • 值得一提的是,README 的描述写的是 "Fetches info about Staryu"(海星星),而代码注释与默认参数均为starmie,实际运行以代码为准:不传参时查询的是 starmie。

运行示例

在 graphql/v1beta2/examples/node 目录下执行:

npm i node pokemon.js

输出为 starmie(宝石海星)的全套 JSON 数据。也可以传入任意宝可梦名称:

node pokemon.js pikachu node pokemon.js mewtwo

若名称不存在,GraphQL 会返回errors,脚本将错误输出到控制台(console.error(errors))。

命名演进:v1beta 与 v1beta2 的表名差异

仓库同时保留了 GraphQL 的两套示例目录:graphql/v1beta 与 graphql/v1beta2。对比两版 node/pokemon.js 可发现关键差异在表命名风格:

  • v1beta:使用pokemon_v2_前缀,如pokemon_v2_pokemonspecies、pokemon_v2_pokemonhabitat、pokemon_v2_pokemonmoves;
  • v1beta2:去掉前缀,直接使用pokemonspecies、pokemonhabitat、pokemonmoves,字段名同样简化,如pokemon_v2_movelearnmethod变为movelearnmethod、pokemon_v2_version变为version。

其余查询结构(where 过滤、aggregate、distinct_on、字段别名)完全一致。这也说明:只要掌握了本文讲解的查询写法,在 v1beta 与 v1beta2 之间迁移只需替换表名与字段名。对应的底层元数据分别位于 graphql/v1beta2/metadata 与 graphql/v1beta/metadata,每个表都有一份独立 YAML 定义可供查阅字段细节。

更多实战入口

如果想把同样的查询应用到其他场景,仓库还提供了以下资源:

  • 官方控制台:所有.gql文件(如 pokemon_stats.gql、item_translations.gql、weakestPokemonAbleToBeatFireRedAlone.gql)都可在 GraphQL 控制台直接运行,适合先验证查询再接入代码。
  • Go 版本对照:go/README.md 展示了go run pokemon.go的等价实现,其输出同样为 JSON(可用| jq美化),可用来对照不同语言的客户端写法。
  • 本地部署:若需自托管,参考 graphql/v1beta2/config.yaml(endpoint 为http://localhost:8080)与仓库 Resources 下的 Docker/K8s 编排文件,将示例中的请求 URL 替换为本地端点即可复用全部查询逻辑。

小结

本文以graphql/v1beta2/examples/node/为入口,完整还原了 PokeAPI GraphQL v1beta2 的 Node.js 客户端写法:一条fetchGraphQL封装函数承载所有请求,一个参数化的pokemon_details查询在单次请求中拿到物种、个体、特性、种族值、招式、遭遇统计、道具与图鉴文本,命令行入口支持任意宝可梦名称的动态查询。无论你是想快速在终端探索数据,还是计划把 PokeAPI 接入自己的 Node 服务,这份示例都是可直接复制改造的起点。

  • 后端

【免费下载链接】pokeapi

The Pokémon API

项目地址:https://gitcode.com/GitHub_Trending/po/pokeapi
点击查看免费下载
上一篇:AShareData 教程:3 步搭建你自己的 A 股数据本地 MySQL 库
下一篇:浏览器里的免费开源 EPUB 阅读器:Epub.js Reader,三行代码打开一本书

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询