根据后端给定的swagger文档生成对应的ts接口

目录

一、 问题

二、解决方法

三、总结


一、 问题

1.后端给的接口都大同小异,怎么样才能快速转换成前端想要的接口呢

2.每次都自己写太麻烦了。还有时候后端不给到具体的链接地址,找半天都不知道接口在哪里……

二、解决方法

1.针对后端不给到具体的链接地址,找不到具体位置。可以切换到doc.html文档模式,根据接口或者接口中文描述查找对应的接口,具体操作如下图2-1所示

图2-1

2.怎么根据swagger文档生成ts接口呢?使用swagger-typescript-api插件,具体操作如下:

1)找到接口文档并下载保存下来

2)全局安装swagger-typescript-api 插件

pnpm install swagger-typescript-api

3)执行命令 swagger-typescript-api generate -p scm-api.txt -o ./scm-api  --modular  --module-name-first-tag --clean-output

        a.也可以创建 package.json文件,为上述命令指定别名,更方便

swagger-typescript-api generate -p scm-api.txt -o ./scm-api  --modular  --module-name-first-tag --clean-output
-p scm-api.txt :指定swagger文件所在位置
-o ./scm-api  :指定生成目录
--modular --module-name-first-tag:根据 swagger文件中的tag分模块生成 api文件
--clean-output:每次执行时删除已经存在的文件 ./scm-api

        b.目录结构如下图所示:

        c.生成的结果如下图所示:

4.ts接口已经生成成功了,但是整体的接口样式和现在项目里面不一致,每次都要手动改,怎么办呢?

a.自定义生成的接口文件模板。通过 -t 参数,指定生成的接口文件模板

b.命令如下:

swagger-typescript-api generate -p admin-api.json -o ./admin-api  --modular  --module-name-first-tag --clean-output  -t ./templates/modular
-t ./templates/modular: 按照./templates/modular模板生成api文件(可以指定生成的api格式)

c.文件目录如下:

d. 自定义接口输出样式的步骤:

e.最终结果

f.参考templates

 route.docs.ejs

<% const { config, route, utils }=it; const { _, formatDescription, fmtToJSDocLine, pascalCase, require }=utils; const {
    raw, request, routeName }=route; const jsDocDescription='' ; const jsDocLines=_.compact([ _.size(raw.tags) &&
    `*@tags ${raw.tags.join(", ")}`, raw.summary && ` *${raw.summary}`, 
raw.deprecated && ` * @deprecated`, routeName.duplicate && ` * @originalName
${routeName.original}`, routeName.duplicate && ` * @duplicate`, request.security
&& ` * @secure`, ...(config.generateResponses && raw.responsesTypes.length ?
raw.responsesTypes.map( ({ type, status, description, isSuccess }) => ` *
@response \`${status}\` \`${_.replace(_.replace(type, /\/\*/g, " \\*"), /\*\//g, "*\\" )}\` ${description}`, ) : []),
    ]).map(str=> str.trimEnd()).join("\n");
    return { description: jsDocDescription, lines: jsDocLines, } %>

procedure-call.ejs

<%
const { utils, route, config } = it;
const { requestBodyInfo, responseBodyInfo, specificArgNameResolver } = route;
const { _, getInlineParseContent, getParseContent, parseSchema, getComponentByRef, require } = utils;
const { parameters, path, method, payload, query, formData, security, requestParams } = route.request;
const { type, errorType, contentTypes } = route.response;
const { HTTP_CLIENT, RESERVED_REQ_PARAMS_ARG_NAMES } = config.constants;
const routeDocs = includeFile("../base/route-docs", { config, route, utils });
const queryName = (query && query.name) || "query";
const pathParams = _.values(parameters);
const pathParamsNames = _.map(pathParams, "name");

const isFetchTemplate = config.httpClientType === HTTP_CLIENT.FETCH;

const requestConfigParam = {
    name: specificArgNameResolver.resolve(RESERVED_REQ_PARAMS_ARG_NAMES),
    optional: true,
    type: "RequestParams",
    defaultValue: "{}",
}

const argToTmpl = ({ name, optional, type, defaultValue }) => `${name}${!defaultValue && optional ? '?' : ''}: ${type}${defaultValue ? ` = ${defaultValue}` : ''}`;

const rawWrapperArgs = config.extractRequestParams ?
    _.compact([
        requestParams && {
          name: pathParams.length ? `{ ${_.join(pathParamsNames, ", ")}, ...${queryName} }` : queryName,
          optional: false,
          type: getInlineParseContent(requestParams),
        },
        ...(!requestParams ? pathParams : []),
        payload,
        ,
    ]) :
    _.compact([
        ...pathParams,
        query,
        payload,
    ])

const wrapperArgs = _
    // Sort by optionality
    .sortBy(rawWrapperArgs, [o => o.optional])
    .map(argToTmpl)
    .join(', ')

// RequestParams["type"]
const requestContentKind = {
    "JSON": "ContentType.Json",
    "JSON_API": "ContentType.JsonApi",
    "URL_ENCODED": "ContentType.UrlEncoded",
    "FORM_DATA": "ContentType.FormData",
    "TEXT": "ContentType.Text",
}
// RequestParams["format"]
const responseContentKind = {
    "JSON": '"json"',
    "IMAGE": '"blob"',
    "FORM_DATA": isFetchTemplate ? '"formData"' : '"document"'
}

const bodyTmpl = _.get(payload, "name") || null;
const queryTmpl = (query != null && queryName) || null;
const bodyContentKindTmpl = requestContentKind[requestBodyInfo.contentKind] || null;
const responseFormatTmpl = responseContentKind[responseBodyInfo.success && responseBodyInfo.success.schema && responseBodyInfo.success.schema.contentKind] || null;
const securityTmpl = security ? 'true' : null;

const describeReturnType = () => {
    if (!config.toJS) return "";

    switch(config.httpClientType) {
        case HTTP_CLIENT.AXIOS: {
          return `Promise<AxiosResponse<${type}>>`
        }
        default: {
          return `Promise<AxiosResponse<${type}>>`
        }
    }
}

const isValidIdentifier = (name) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name);

%>



/**
 *<% /* Here you can add some other JSDoc tags */ %>

<%~ routeDocs.lines %>

 */
 export function request<%~ route.routeName.usage.split('Using')[0].replace(/^./, match => match.toUpperCase()) %> (<%~ wrapperArgs %>)<%~ config.toJS ? `: ${describeReturnType()}` : "" %>{

  return  <%~ config.singleHttpClient ? 'yRequest' : 'yRequest' %>.<%~ _.lowerCase(method) %><<%~ type %>>({
        url: `<%~ path %>`,
        <%~ queryTmpl ? `params: ${queryTmpl},` : '' %>
        <%~ bodyTmpl ? ` ${bodyTmpl}` : '' %>
        <%~ securityTmpl ? `secure: ${securityTmpl},` : '' %>
        <%~ bodyContentKindTmpl && bodyContentKindTmpl.toString()!=='ContentType.Json' ? `type: ${bodyContentKindTmpl},` : '' %>
    })
}

三、总结

1.目前使用swagger-typescript-api 插件可以实现根据 swagger-api的 tags对接口进行分模块生成文件,并且能够自定义接口生成结构

2.如果能够实现typeScript接口定义的分类存储就更好了。但是目前看源码还没有找到解决方法。后续找到再更新

3.如果能够把文件路径指定为线上地址就更好了,这样就可以实时获取到最新的接口文档,无需每次接口更新时,手动下载swagger-api接口文档了。看了swagger-typescript-api官方文档提供的示例是可以的。但是我现在的url地址是加密的需要登录,swagger-typescript-api访问不了,目前没有找到解决方法,找到了后续再更新。

4.如有大佬知道如何解决2,3,希望不吝赐教,非常感谢!

/*

希望对你有帮助!

如有错误,欢迎指正,谢谢!

*/

在前后端分离架构中,前端开发人员可以借助Swagger生成的API文档进行接口调用和开发,以确保与后端服务的高效对接和协作。Swagger 提供了标准化、可视化的接口文档,使得前端能够清晰地了解接口的输入输出格式、请求方式、参数类型等关键信息,从而提升开发效率并减少沟通成本。 ### 接口调用与开发流程 1. **获取接口定义** 前端开发人员通过访问Swagger UI界面,可以查看后端提供的所有API接口的详细信息。这些信息包括接口路径、HTTP方法(GET、POST、PUT、DELETE等)、请求参数、响应示例等[^1]。通过这些信息,前端可以快速了解每个接口的功能和使用方式。 2. **接口测试与调试** Swagger UI内置了接口测试功能,前端开发人员可以直接在浏览器中对API进行调用测试。例如,可以在Swagger UI中填写请求参数并发送请求,查看返回结果是否符合预期。这种实时调试能力有助于前端在开发初期就验证接口的可用性,减少后期联调时间[^2]。 3. **接口集成与调用** 在实际开发中,前端通常使用如 `axios` 或 `fetch` 等HTTP客户端进行接口调用。基于Swagger文档中提供的接口路径和参数要求,前端可以编写清晰、规范的请求代码。例如: ```javascript axios.get('/api/users', { params: { page: 1, limit: 10 } }) .then(response => { console.log(response.data); }) .catch(error => { console.error('Error fetching users:', error); }); ``` 上述代码示例基于Swagger文档中定义的 `/api/users` 接口进行调用,并传递分页参数。 4. **接口变更与文档同步** 由于Swagger文档是动态生成的,后端接口发生变更时,前端可以第一时间通过Swagger UI获取最新的接口信息。这种自动更新机制确保了文档与接口的一致性,避免了传统文档更新滞后带来的沟通问题[^2]。 5. **Mock数据开发(结合YApi等工具)** 在某些开发阶段,后端接口可能尚未完成,此时可以结合YApi等接口管理平台,基于Swagger文档生成Mock数据,供前端进行页面开发和功能测试。这种做法可以在后端接口未就绪时,确保前端开发工作不被阻塞[^3]。 ### 开发协作优势 - **提升沟通效率**:Swagger文档作为前后端协作的标准接口描述,减少了口头沟通和文档更新不及时带来的误解。 - **并行开发支持**:前后端可以在接口定义完成后并行开发,前端基于Swagger文档进行接口调用,后端则专注于接口实现。 - **降低维护成本**:接口文档的自动化生成和更新机制,使得接口维护成本大幅降低,同时也提升了系统的可维护性[^4]。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值