在Debian环境下,要将Swagger与GraphQL结合使用,你需要遵循以下步骤:
安装Node.js和npm:首先,确保你已经在Debian系统上安装了Node.js和npm。如果没有,请访问Node.js官方网站并按照说明进行安装。
安装GraphQL:接下来,你需要安装GraphQL。在终端中运行以下命令:
npm install graphql
npm install apollo-server
npm install swagger-ui-express
index.js
的文件,并添加以下代码以创建一个简单的GraphQL API:const { ApolloServer, gql } = require('apollo-server');
// 构建一个简单的GraphQL schema
const typeDefs = gql`
type Query {
hello(name: String): String
}
`;
// 提供schema的解析器
const resolvers = {
Query: {
hello: (_, { name }) => `Hello, ${name || 'World'}`,
},
};
// 创建一个Apollo Server实例
const server = new ApolloServer({ typeDefs, resolvers });
// 启动服务器
server.listen().then(({ url }) => {
console.log(`Server is running at ${url}`);
});
index.js
文件中,添加以下代码以集成Swagger UI:const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');
// 读取Swagger文档
const swaggerDocument = YAML.load('./swagger.yaml');
// 将Swagger UI添加到Express应用中
server.express.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
swagger.yaml
的文件,并添加以下内容:swagger: '2.0'
info:
title: GraphQL API
description: A simple GraphQL API with Swagger documentation
version: '1.0.0'
host: localhost:4000
basePath: /
schemes:
- http
paths:
/:
get:
summary: Returns a hello message
parameters:
- name: name
in: query
type: string
required: false
responses:
'200':
description: A hello message
schema:
type: object
properties:
hello:
type: string
node index.js
现在,你的应用程序已经在Debian环境下运行,并且Swagger UI已经集成到GraphQL API中。你可以通过访问http://localhost:4000/api-docs
来查看Swagger文档。