SWAPI GraphQL 项目使用教程
1. 项目的目录结构及介绍
SWAPI GraphQL 项目的目录结构如下:
swapi-graphql/
├── swapi/
│ ├── __tests__/
│ ├── data/
│ ├── index.js
│ ├── resolvers.js
│ └── schema.js
├── server/
│ ├── index.js
│ └── package.json
├── .gitignore
├── LICENSE
├── README.md
├── package.json
└── yarn.lock
目录介绍:
-
swapi/
: 包含 SWAPI 包装器的主要代码。__tests__/
: 测试文件。data/
: 数据文件。index.js
: 入口文件。resolvers.js
: GraphQL 解析器。schema.js
: GraphQL 模式定义。
-
server/
: 包含本地 Express 服务器的代码。index.js
: 服务器入口文件。package.json
: 服务器依赖配置。
-
.gitignore
: Git 忽略文件。 -
LICENSE
: 项目许可证。 -
README.md
: 项目说明文档。 -
package.json
: 项目依赖配置。 -
yarn.lock
: Yarn 依赖锁定文件。
2. 项目的启动文件介绍
本地服务器启动文件
本地服务器的启动文件位于 server/index.js
。该文件使用 Express 和 express-graphql
模块来提供 HTTP 访问 GraphQL 服务。
// server/index.js
const express = require('express');
const graphqlHTTP = require('express-graphql');
const schema = require('../swapi');
const app = express();
app.use('/', graphqlHTTP({
schema,
graphiql: true,
}));
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}/`);
});
SWAPI 包装器启动文件
SWAPI 包装器的启动文件位于 swapi/index.js
。该文件导出 GraphQL 模式和解析器。
// swapi/index.js
const { makeExecutableSchema } = require('graphql-tools');
const resolvers = require('./resolvers');
const typeDefs = require('./schema');
const schema = makeExecutableSchema({
typeDefs,
resolvers,
});
module.exports = schema;
3. 项目的配置文件介绍
package.json
package.json
文件包含了项目的依赖和脚本命令。
{
"name": "swapi-graphql",
"version": "1.0.0",
"description": "A GraphQL schema and server wrapping SWAPI",
"main": "index.js",
"scripts": {
"start": "node server/index.js",
"test": "yarn test"
},
"dependencies": {
"express": "^4.17.1",
"express-graphql": "^0.9.0",
"graphql": "^15.3.0",
"graphql-tools": "^6.0.0"
},
"devDependencies": {
"jest": "^26.4.2"
}
}
server/package.json
server/package.json
文件包含了本地服务器的依赖和脚本命令。
{
"name": "swapi-graphql-server",
"version": "1.0.0",
"description": "Local server for SWAPI GraphQL",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"express": "^4.17.1",
"express-graphql": "^0.9.0"
}
}
通过以上配置文件,可以安装项目依赖并启动本地服务器进行开发和测试。