GraphQL Directive 项目教程
1. 项目的目录结构及介绍
graphql-directive/
├── src/
│ ├── directives/
│ │ ├── auth.js
│ │ ├── date.js
│ │ └── index.js
│ ├── index.js
│ └── utils/
│ └── logger.js
├── .babelrc
├── .eslintrc.js
├── .gitignore
├── package.json
├── README.md
└── yarn.lock
目录结构说明
- src/: 项目的源代码目录。
- directives/: 存放自定义的 GraphQL 指令文件。
- auth.js: 用于权限验证的指令。
- date.js: 用于日期格式化的指令。
- index.js: 导出所有指令的入口文件。
- index.js: 项目的入口文件。
- utils/: 存放工具函数。
- logger.js: 日志记录工具。
- directives/: 存放自定义的 GraphQL 指令文件。
- .babelrc: Babel 配置文件,用于转换 ES6+ 代码。
- .eslintrc.js: ESLint 配置文件,用于代码风格检查。
- .gitignore: Git 忽略文件配置。
- package.json: 项目的依赖管理文件。
- README.md: 项目的说明文档。
- yarn.lock: Yarn 依赖锁定文件。
2. 项目的启动文件介绍
项目的启动文件是 src/index.js
。该文件主要负责初始化 GraphQL 服务器并加载自定义指令。
// src/index.js
import { ApolloServer } from 'apollo-server';
import { schema } from './directives';
const server = new ApolloServer({
schema,
});
server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});
启动文件说明
- ApolloServer: 使用
apollo-server
创建 GraphQL 服务器。 - schema: 从
directives/index.js
中导入的 GraphQL 模式,包含了自定义的指令。 - server.listen(): 启动服务器并监听端口。
3. 项目的配置文件介绍
.babelrc
{
"presets": ["@babel/preset-env"]
}
.eslintrc.js
module.exports = {
env: {
node: true,
es6: true,
},
extends: 'eslint:recommended',
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
},
rules: {
// 自定义规则
},
};
package.json
{
"name": "graphql-directive",
"version": "1.0.0",
"main": "src/index.js",
"scripts": {
"start": "node src/index.js",
"test": "jest"
},
"dependencies": {
"apollo-server": "^3.0.0",
"graphql": "^15.5.0"
},
"devDependencies": {
"@babel/core": "^7.14.0",
"@babel/preset-env": "^7.14.0",
"eslint": "^7.27.0",
"jest": "^27.0.1"
}
}
配置文件说明
- .babelrc: 配置 Babel 预设,用于转换 ES6+ 代码。
- .eslintrc.js: 配置 ESLint,用于代码风格检查。
- package.json: 项目的依赖管理文件,包含项目的名称、版本、入口文件、脚本命令和依赖包。
通过以上配置,项目可以顺利启动并运行。