GraphQL Query Complexity 项目教程
1. 项目的目录结构及介绍
GraphQL Query Complexity 项目的目录结构如下:
graphql-query-complexity/
├── src/
│ ├── estimators/
│ │ ├── fieldExtensionsEstimator.ts
│ │ ├── simpleEstimator.ts
│ ├── index.ts
├── examples/
│ ├── apollo-server/
│ │ ├── index.ts
│ ├── express-graphql/
│ │ ├── index.ts
├── package.json
├── README.md
目录结构介绍
- src/: 包含项目的主要源代码。
- estimators/: 包含用于计算查询复杂度的估算器。
- fieldExtensionsEstimator.ts: 用于从字段扩展中获取复杂度。
- simpleEstimator.ts: 简单的复杂度估算器。
- index.ts: 项目的主入口文件。
- estimators/: 包含用于计算查询复杂度的估算器。
- examples/: 包含不同框架的示例代码。
- apollo-server/: 使用 Apollo Server 的示例。
- express-graphql/: 使用 Express-GraphQL 的示例。
- package.json: 项目的依赖和脚本配置文件。
- README.md: 项目的介绍和使用说明。
2. 项目的启动文件介绍
项目的启动文件位于 examples/
目录下,分别有 apollo-server/index.ts
和 express-graphql/index.ts
。
Apollo Server 示例启动文件
// examples/apollo-server/index.ts
import { ApolloServer } from 'apollo-server';
import { getComplexity, fieldExtensionsEstimator, simpleEstimator } from 'graphql-query-complexity';
import { schema } from '../schema';
async function bootstrap() {
const server = new ApolloServer({
schema,
plugins: [
{
requestDidStart: async () => ({
async didResolveOperation({ request, document }) {
const complexity = getComplexity({
schema,
operationName: request.operationName,
query: document,
variables: request.variables,
estimators: [
fieldExtensionsEstimator(),
simpleEstimator({ defaultComplexity: 1 }),
],
});
if (complexity > 20) {
throw new Error(`Sorry, too complicated query! ${complexity} is over 20 that is the max allowed complexity.`);
}
console.log("Used query complexity points:", complexity);
},
}),
},
],
});
const { url } = await server.listen({ port: 4000 });
console.log(`GraphQL server ready at ${url}`);
}
bootstrap();
Express-GraphQL 示例启动文件
// examples/express-graphql/index.ts
import express from 'express';
import { graphqlHTTP } from 'express-graphql';
import { getComplexity, fieldExtensionsEstimator, simpleEstimator } from 'graphql-query-complexity';
import { schema } from '../schema';
const app = express();
app.use('/graphql', graphqlHTTP({
schema,
graphiql: true,
customFormatErrorFn: (error) => ({
message: error.message,
locations: error.locations,
stack: error.stack ? error.stack.split('\n') : [],
path: error.path,
}),
extensions: ({ document, variables, operationName }) => {
const complexity = getComplexity({
schema,
operationName,
query: document,
variables,
estimators: [
fieldExtensionsEstimator(),
simpleEstimator({ defaultComplexity: 1 }),
],
});
if (complexity > 20) {
throw new Error(`Sorry, too complicated query! ${complexity} is over 20 that is the max allowed complexity.`);
}
console.log("Used query complexity points:", complexity);
return { complexity };
},
}));
app.listen(4000, () => {
console.log('GraphQL server ready at http://localhost:4000/graphql');
});