npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

openapi-request

v1.0.6

Published

Swagger 2.0 and OpenAPI 3.x to TypeScript Request Client

Downloads

6

Readme

介绍

npm (scoped)

根据 OpenApi2 | OpenApi3 文档快速生成 request 请求代码,默认生成使用的请求库axios,也可使用自定义请求方法。

使用

  1. 安装

    npm i --save-dev openapi-request openapi-typescript-helpers
  2. 在项目根目录新建 openapi.config.ts

    const { generateRequest } = require('openapi-request')
    
    generateRequest({
        // Swagger 2.0 或 OpenAPI 3.0 的请求地址或本地路径
        schemaPath: 'http://petstore.swagger.io/v2/swagger.json',
        // 生成的文件夹的路径
        serversPath: './servers',
        // 项目名称,如果有将在 serversPath 下创建文件夹,适用于一个项目有多个请求服务
        projectName: "swagger",
        // 自定义导出的接口名称
        exportName: 'api',
        // hook 示例
        hook:{
            // 自定义请求函数名称,目录名称
            customName({path,method,definition},defaultName){
                if(path==="/test/test"){
                    // 返回false,不生成该接口
                    return false;
                }
                if (path === '/system/menu/list') {
                    return {folder:"system",name:"getMenuList"};
                }
                return defaultName;
            }
        }
    })
    
  3. 执行命令生成请求方法 在 package.jsonscript 中添加 api: "openapi":"ts-node openapi.config.ts",

    执行命令生成api

    npm run openapi
    
  4. 示例参考 https://github.com/c2node/openapi-request/tree/main/test

自定义请求方法

当使用axios外的请求库或需要对axios请求方法进行扩展可自定义请求方法进行实现

  1. 请求方法参数说明 请求方法默认接受2个参数,参数2和其他参数可通过requestFnOtherParams进行配置,需要注意的是:除参数1外,都是可选参数

    • 参数1:OpenapiRequestConfig
    export interface OpenapiRequestConfig {
        url: string,
        method: string,
        // 是否允许跨站点提交请求,携带Cookie需要
        withCredentials?:bool,
        // header参数,其中content-type为body编码类型
        headers?: Record<string, string>,
        // 请求查询参数
        params?: Record<string, any>,
        // body参数
        data?: Record<string, any> | FormData,
        // 响应类型
        responseType?: 'arraybuffer' | 'blob' | 'document' | 'json' | 'text' | 'stream',
    }
    • 参数2 option?:Omit<axios.AxiosRequestConfig,"url"|"method">
  2. fetch 请求示例

    1. src/fetch-request.ts
    import {OpenapiRequestConfig} from "openapi-request/types";
    
    
    const baseUrl = 'http://127.0.0.1:8080';
    export type RequestOption = Omit<RequestInit, 'body'>;
    
    export function request<Response>(config: OpenapiRequestConfig, {
        headers: _headers = {},
        ...option
    }: RequestOption = {}) {
        const {
            url,
            method,
            params = {},
            headers = {},
            data,
            responseType,
            withCredentials = false
        } = config;
        const urlData = new URL(url, baseUrl);
        urlData.searchParams
        let body
        switch (headers['content-type']) {
            case 'multipart/form-data': {
                body = new FormData();
                Object.keys(data).forEach(key => {
                    body.append(key, data[key]);
                });
                break;
            }
            case 'application/json': {
                body = JSON.stringify(data);
                break;
            }
            default: {
                // application/x-www-form-urlencoded 或其它格式
                body = new URLSearchParams(Object.entries(data)).toString();
                break;
            }
        }
        Object.keys(params ?? {}).forEach(key => {
            urlData.searchParams.append(key, params[key]);
        });
        return fetch(urlData, {
            method,
            headers: {...headers, ..._headers},
            body,
            ...option,
            credentials: withCredentials ? 'include' : undefined,
        }).then(res => {
            if (responseType === 'json') {
                return res.json() as Response
            }
            return res.text() as Response;
        })
    }
    1. openapi.config.ts
        const { generateService } = require('openapi-request')
        await generateService({
            // 导入自定义请求方法
            requestImport: "import {request,RequestOption} from \"src/fetch-request\"",
            // 自定义请求方法名称
            requestFnName: "request",
            // 自定义请求方法其他可选参数
            requestFnOtherParams: [{name: "option", type: "RequestOption"}],
            // Swagger 2.0 或 OpenAPI 3.0 的请求地址或本地路径
            schemaPath: 'http://petstore.swagger.io/v2/swagger.json',
            // 生成的文件夹的路径
            serversPath: './service-files',
            // 项目名称,如果有将在 serversPath 下创建文件夹,适用于一个项目有多个请求服务
            projectName: "swagger-fetch",
            // hook 示例
            hook: {
                // 自定义请求函数名称,目录名称
                customName({path, method, definition}, defaultName) {
                    if (path === "/store/inventory") {
                        return false;
                    }
                    if (path === '/user/{username}' && method === "get") {
                        return {folder: "system", name: "userInfo"};
                    }
                    return defaultName;
                }
            }
        });
    1. 生成代码参照 https://github.com/c2node/openapi-request/tree/main/test/service-files/swagger-fetch

参数

| 属性 | 必填 | 备注 | 类型 | 默认值 | | ---- | ---- | ---- | ---- | - | | requestImport | 否 | 导入自定义请求方法 | string | import axios from "axios" | | requestFnName | 否 | 自定义请求方法名称 | string | axios.request | | requestParams | 否 | 生产的请求方法Params包含的参数 | Record<'path' | 'query' | 'header' | 'cookie', boolean> | {path:true,query:true,header:true,cookie:true} | | requestFnOtherParams | 否 | 自定义请求方法其它可选参数 | { name: string, type: string }[] | [] | | serversPath | 否 | 生成的文件夹的路径 | string | - | | schemaPath | 是 | Swagger 2.0 或 OpenAPI 3.0 的请求地址或本地路径 | string | - | | projectName | 否 | 项目名称,如果有将在 serversPath 下创建文件夹 | string | - | | exportName | 否 | 导出的api名称 | string | -- | | exportJson | 否 | 导出JSON文件 | boolean | {openapi:boolean,service:boolean } | -- | | templatesFolder | 否 | 自定义模板文件的文件路径 | string | - | | hook.customName | 否 | 自定义请求函数名称,目录名称 | {name:"函数名称",folder:"目录名称"} | - | | hook.customRequestParams | 否 | 自定义请求方法params参数,参数中如需排除该参数请返回 false | boolean | -- |