後端新增內容
老師可以新增有關swagger相關內容與openapi-typescript-codegen互相搭配上的使用教學嗎?
24
收起
正在回答 回答被采纳积分+1
2回答
Brian
2024-04-27 17:04:30
我明白你的应用场景了,
我给你一个简单的示例:
这个是swagger,下面使用@hey-api/openai-ts为其产生Interface与API:
这个假设是你们后端产生swagger:
下面配置项目:
1. 安装依赖:
pnpm install @hey-api/openapi-ts -D pnpm install axios // 因为后面我们需要使用axios作为客户端
2. 创建配置文件openapi-ts.config.ts:
import { defineConfig } from '@hey-api/openapi-ts'; export default defineConfig({ base: 'https://petstore3.swagger.io/api/v3', client: 'axios', // 修改这里可以使用不同client,可以选择:node,xhr,axios,fetch,angular format: 'prettier', input:'https://raw.githubusercontent.com/swagger-api/swagger-petstore/master/src/main/resources/openapi.yaml', output: './src/client', });
3. 修改package.json的配置:
"scripts": { "openapi-ts": "openapi-ts" },
4. 获取接口
npm run openapi-ts
形成文件:
5. 接口请求示例:
<script setup lang="ts"> import { ref } from 'vue'; import { OpenAPI } from './client/core/OpenAPI'; import { PetService } from './client'; const pet = ref(); const handleClick = async () => { pet.value = await PetService.getPetById({ // random id 1-10 petId: Math.floor(Math.random() * (10 - 1 + 1) + 1), }); }; OpenAPI.interceptors.response.use((response: any) => { if (response.status === 200) { console.log(`request to ${response.url} was successful`); } return response; }); </script> <template> <div> <div>pet: {{ pet }}</div> <button @click="handleClick">Click测试</button> </div> </template>
这个是OpenAPI的配置类型:
export const OpenAPI: OpenAPIConfig = { BASE: 'https://petstore3.swagger.io/api/v3', CREDENTIALS: 'include', ENCODE_PATH: undefined, HEADERS: undefined, PASSWORD: undefined, TOKEN: undefined, USERNAME: undefined, VERSION: '1.0.20-SNAPSHOT', WITH_CREDENTIALS: false, interceptors: { request: new Interceptors(), response: new Interceptors(), }, };
vue项目代码:https://git.imooc.com/class-163/openapi-ts-demo,另react示例代码:https://stackblitz.com/edit/hey-api-example
PS: 你是台湾还是广东&港澳的小伙伴?习惯用繁体~~ ^_^,看来我的受众很广泛
前端高级工程师(大前端)
- 参与学习 303 人
- 解答问题 391 个
全新打造“技术成长&职业破局”双高体系,深度打通“全栈 + 全流程 +多端+ 提效+AI赋能”,递进式锤炼思维与高阶技能,高效实现能力跃迁,助力成为“驾驭全局,深广兼备,打通多端全栈”的高级工程师
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星