在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文檔。