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.
- Features
- Credits
- Installation
- CLI Options
- Generation Rule
- Usage
- Quickstart
- More Examples
- Sister Projects
- License
- Totally typescript support. Pullcode generates service class, methods, request body and response body object types based on json formatted Swagger2/OpenAPI3 documentation.
- Rich and useful configuration options. Pullcode wrapps axios configuration options and add more options for you to elegantly customize requests.
- 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.
- Framework-agnostic. Pullcode can be used with any frontend frameworks.
- commander.js:nodejs command line tool library
- swagger2openapi:convert swagger 2 to OpenAPI 3
- vue-vben-admin: a modern vue3 admin
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
.
➜ 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.
Pullcode will check if BizService.ts
file exists, if exists, skip. Other files will always be overwritten.
- 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"
},
-
Run
npm run pull
-
Open
BizService.ts
file, fixdefaultOptions
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.
- After above fix, you can import default singleton service instance to components to send http requests.
Please refer to this example app:pullcode-quickstart
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);
},
};
<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>
- 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.
MIT