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

pullcode

v1.2.3

Published

Pullcode is OpenAPI (aka Swagger) specification compatible typescript http client code generation tool relying on axios. You can configure it to npm scripts to directly generate client code to specified path to easily use. Support Swagger 2 and OpenAPI 3

Downloads

15

Readme

pullcode

Pullcode is OpenAPI (aka Swagger) specification compatible typescript http client code generation tool relying on axios. You can configure it to npm scripts to directly generate client code to specified path to easily use. Support Swagger 2 and OpenAPI 3 (aka Swagger 3) in json format.

TOC

Features

  1. Totally typescript support. Pullcode generates service class, methods, request body and response body object types based on json formatted Swagger2/OpenAPI3 documentation.
  2. Rich and useful configuration options. Pullcode wrapps axios configuration options and add more options for you to elegantly customize requests.
  3. Built-in axios request and response interceptors. Request interceptor handles request url rewrite and adds Authorization header. Response interceptor extracts data attribute from raw response. Users can configure additional custom interceptors to do further process. There is no built-in request error and response error interceptors, users should pass their own implementations if necessary.
  4. Framework-agnostic. Pullcode can be used with any frontend frameworks.

Credits

Installation

npm install --save pullcode

NOTE: generated code imports code from pullcode, so pullcode is not only a CLI, but also a npm package, you should use --save instead of --save-dev.

CLI Options

➜  pullcode git:(master) ✗ pullcode -h                                           
Usage: pullcode [options]

Options:
  -o, --output <value>  code output path
  -u, --url <value>     swagger 2.0 or openapi 3.0 json api document download url
  -h, --help            display help for command
  • output: directories will be recursively created if not exists.

Generation Rule

Pullcode will check if BizService.ts file exists, if exists, skip. Other files will always be overwritten.

Usage

  1. Configure pullcode command into scripts attribute in package.json. For example:
"scripts": {
  "pull": "pullcode -u https://petstore3.swagger.io/api/v3/openapi.json -o src/api"
},
  1. Run npm run pull

  2. Open BizService.ts file, fix defaultOptions parameters to fit your need.

const defaultOptions: CreateAxiosOptions = {
  requestOptions: {
    apiUrl: '', // same as baseUrl
    urlPrefix: '',
  } as RequestOptions,
}
  • apiUrl: if configured proxy, apiUrl should be set to a prefix for matching the proxy.
  • urlPrefix: should be confirmed with your backend colleagues if there is url prefix to match service name (if the service is behind a gateway) or servlet contxt path (if the service is based on spring boot framework).
  • transform: set your custom axios interceptors. Normally, you just need to customize response error interceptor.
  • tokenGetter: set auth token getter function. The function will be called in built-in request interceptor to put token into header.

For example:

import { merge } from 'lodash-es';
import { CreateAxiosOptions, VAxios } from '@/httputil/Axios';
import { useGlobSetting } from '/@/hooks/setting';
import { transform } from '/@/api/interceptor'
import { getToken } from '/@/utils/auth';
import { RequestOptions } from '@/types/axios';

const globSetting = useGlobSetting();

const defaultOptions: CreateAxiosOptions = {
  transform,
  requestOptions: {
    apiUrl: globSetting.apiUrl, // same as baseUrl
    urlPrefix: '/myservice',
  } as RequestOptions,
  tokenGetter: getToken as () => string
}

export class BizService extends VAxios {
  constructor(options?: Partial<CreateAxiosOptions>) {
    super(merge(defaultOptions, options || {}));
  }
}

export default BizService;

For other options, please read CreateAxiosOptions definition from source code.

  1. After above fix, you can import default singleton service instance to components to send http requests.

Quickstart

Please refer to this example app:pullcode-quickstart

petstore

More Examples

Response Error Interceptor

import type { AxiosResponse } from 'axios';
import type { AxiosTransform } from '@/httputil/axiosTransform';
import { checkStatus } from './checkStatus';
import { useMessage } from '/@/hooks/web/useMessage';
import { useErrorLogStoreWithOut } from '/@/store/modules/errorLog';
import { useI18n } from '/@/hooks/web/useI18n';

const { createMessage, createErrorModal } = useMessage();

export const transform: AxiosTransform = {
  /**
   * @description: Response Error Interceptor
   */
  responseInterceptorsCatch: (_: AxiosResponse, error: any) => {
    const { t } = useI18n();
    const errorLogStore = useErrorLogStoreWithOut();
    errorLogStore.addAjaxErrorInfo(error);
    const { response, code, message, config } = error || {};
    const errorMessageMode = config?.requestOptions?.errorMessageMode || 'none';
    const msg: string = response?.data?.error?.message ?? '';
    const err: string = error?.toString?.() ?? '';
    let errMessage = '';

    try {
      if (code === 'ECONNABORTED' && message.indexOf('timeout') !== -1) {
        errMessage = t('sys.api.apiTimeoutMessage');
      }
      if (err?.includes('Network Error')) {
        errMessage = t('sys.api.networkExceptionMsg');
      }

      if (errMessage) {
        if (errorMessageMode === 'modal') {
          createErrorModal({ title: t('sys.api.errorTip'), content: errMessage });
        } else if (errorMessageMode === 'message') {
          createMessage.error(errMessage);
        }
        return Promise.reject(error);
      }
    } catch (error) {
      throw new Error(error as unknown as string);
    }

    checkStatus(error?.response?.status, msg, errorMessageMode);
    return Promise.reject(error);
  },
};

Send Requests

<script setup lang="ts">
import { petService } from '@/api/PetService';
import { Pet, PetStatusEnum } from '@/api/types';
import { ref } from 'vue';

let loading = ref(true);
let dataSource = ref([] as Pet[]);

petService.getPetFindByStatus({
  status: PetStatusEnum.AVAILABLE,
}).then((resp: Pet[]) => {
  dataSource.value = resp
  loading.value = false
})
</script>

Sister Projects

  • go-doudou: OpenAPI 3.0 spec based lightweight microservice framework written in Go. It supports monolith service application as well. Currently, it supports RESTful service only.

License

MIT