後端新增內容

後端新增內容

老師可以新增有關swagger相關內容與openapi-typescript-codegen互相搭配上的使用教學嗎?

正在回答 回答被采纳积分+1

登陆购买课程后可参与讨论,去登陆

2回答
Brian 2024-04-27 17:04:30

我明白你的应用场景了,


我给你一个简单的示例:


这个是swagger,下面使用@hey-api/openai-ts为其产生Interface与API: 


这个假设是你们后端产生swagger:

    https://raw.githubusercontent.com/swagger-api/swagger-petstore/master/src/main/resources/openapi.yaml

    

    下面配置项目:

    

    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

形成文件:

https://img1.sycdn.imooc.com/climg/662cbed00909115b08621056.jpg   



    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: 你是台湾还是广东&港澳的小伙伴?习惯用繁体~~ ^_^,看来我的受众很广泛

Brian 2024-04-24 14:33:33

swagger会有,后面会有Nestjs的集成。


openapi-typescript-codegen你的应用场景是什么?创建axios一类基于json的client端吗?

PS: openapi-typescript-codegen这个项目目前不再维护,目前官方仓库上推荐是@hey-api/openai-ts,



  • 是後端產生swagger後,前端可以下更新指令,自動集成api 接口參數的interface檔。

    2024-04-24 14:52:34
问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
前端高级工程师(大前端)
  • 参与学习       303    人
  • 解答问题       391    个

全新打造“技术成长&职业破局”双高体系,深度打通“全栈 + 全流程 +多端+ 提效+AI赋能”,递进式锤炼思维与高阶技能,高效实现能力跃迁,助力成为“驾驭全局,深广兼备,打通多端全栈”的高级工程师

了解课程
请稍等 ...
意见反馈 帮助中心 APP下载
官方微信

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师