Coder Social home page Coder Social logo

ts-axios's Introduction

introduction

Author:Gorit Date:2022年3月16日 Refer: Refactor axios using TypeScript

ts-axios

use TypeScript implement axios,so called ts-axios

devlopment

  1. typescript libary starter

😄new features

base usage

axios.request(config)

axios.get(url[,config])

axios.delete(url[, config])

axios.head(url[, config])

axios.options(url[, config])

axios.post(url[, data[, config]])

axios.put(url[, data[, config]])

axios.patch(url[, data[, config]])

// overide
axios({
    url: '/extend/post',
    method: "post",
    data: {
        msg: 'Hello'
    }
})

axios('/extend/post', {
    method: 'post',
    data: {
        msg: 'hello'
    }
})

return value with generic

// For example, the same datastructure return value as the backend
interface ResponseData<T=any> {
    code: number,
    message: string,
    data: T
}

// the same pojo、vo、entity and so on
interface User {
    name: string,
    age: number
}

function getUser<T>() {
    return axios<ResponseData<T>>('/extend/user')
        .then(res => res.data)
        .catch(err => console.log(err));
}

async function test() {
    const user = await getUser<User>();
    if (user) {
        console.log(user.data.name);    
    }
}

test();

you can use interceptor and axios.create()

import axios, { AxiosError, AxiosRequestConfig, AxiosResponse } from '../../src/index';


const http = axios.create({
    headers: {
        "Content-Type": "application/json,charset=UTF-8"
    }
})

http.interceptors.request.use(function (config: AxiosRequestConfig) {
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

http.interceptors.response.use(function (response) {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    return response;
  }, function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    return Promise.reject(error);
  });

you can use cancelToken like this

import axios, { Canceler } from '../../src/index';

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios.get("/cancel/get", {
    cancelToken: source.token
}).catch(function(e) {
    if (axios.isCancel(e)) {
        console.log("Request Canceled", e.message);
    }
});

setTimeout(() => {

}, 100);

let cancel: Canceler;

axios.get("/cancel/get", {
    cancelToken: new CancelToken(c => {
        cancel = c;
    })
}).catch(function(e) {
    if (axios.isCancel(e)) {
        console.log("Request canceled");
    }
})

branch version

  • main

The most complete functionality

v1.1

just implement params process

v1.2

base on v1.1, here are implement features

  1. body params process
  2. handle exception

v1.3

base on v1.2, here are implement features

  1. ts-axios interface extension
  2. response generic
  3. implement request and response interceptor

v1.4

base v1.3, here are implement features

  1. rewrite config
  2. implement request interceptors and response interceptors
  3. static method of axios.create() and refine transform

v1.5

base v1.4

  1. implement CancelToken

v1.6

base v1.5

  1. add withCredential support
  2. add XSRF support

🤔update log

  • implement two features for v1.6 2022/7/5
  • implement with cancelToken 2022/4/3
  • implement transformRequest, transformReponse and axios.crate() 2022/3/30
  • implement interceptors 2022/3/27
  • use mixed-type object to extend axios's interface, response generic 2022/3/19
  • finish base axios function whitch including handleing params and body params. handle exceptions 2022/3/18
  • implement buildURL function, and handle params process 2022/3/17
  • init project on 2022/3/16

ts-axios's People

Contributors

codinggorit avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.