前边有简单介绍多graphql-mesh 以下是一个简单的试用
环境准备
- 项目初始化
yarn init -y
- 添加依赖
yarn add graphql @graphql-mesh/runtime @graphql-mesh/cli @graphql-mesh/openapi
- pacakge.json 内容
{
"name": "first",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"@graphql-mesh/cli": "^0.0.16",
"@graphql-mesh/openapi": "^0.0.16",
"@graphql-mesh/runtime": "^0.0.16",
"graphql": "^14.6.0"
},
"scripts": {
"start": "graphql-mesh serve"
}
}
简单项目使用
- 配置
.meshrc.yml 文件
sources:
- name: Wiki
source: https://api.apis.guru/v2/specs/wikimedia.org/1.0.0/swagger.yaml
handler:
name: openapi
- 启动
yarn start
- 效果
启动的GraphiQL 界面
- 查询
query wikipediaMetrics {
getMetricsPageviewsAggregateProjectAccessAgentGranularityStartEnd(
access: ALL_ACCESS
agent: USER
start: "20200101"
end: "20200226"
project: "en.wikipedia.org"
granularity: DAILY
) {
items {
views
}
}
}
- 应用使用
const { getMesh, parseConfig } = require('@graphql-mesh/runtime');
const { ApolloServer } = require('apollo-server');
async function test() {
// This will load the config file from the default location (process.cwd)
const meshConfig = await parseConfig();
const { execute, schema, contextBuilder } = await getMesh(meshConfig);
// Use `execute` to run a query directly and fetch data from your APIs
const { data, errors } = await execute(/* GraphQL */ `
query wikipediaMetrics {
getMetricsPageviewsAggregateProjectAccessAgentGranularityStartEnd(
access: ALL_ACCESS
agent: USER
start: "20200101"
end: "20200226"
project: "en.wikipedia.org"
granularity: MONTHLY
) {
items {
views
}
}
}
`);
// Or, if you wish to make this schema publicly available, expose it using any GraphQL server with the correct context, for example:
const server = new ApolloServer({
schema,
context: contextBuilder
});
}
说明
从使用上的基本感受就是graphql-mesh 很方便