3.3.0 • Published 5 months ago

@canlooks/ajax v3.3.0

Weekly downloads
-
License
MIT
Repository
-
Last release
5 months ago

@canlooks/ajax

Install

npm i @canlooks/ajax

A quick example

ajax(config)

import {ajax} from '@canlooks/ajax'

const pending = ajax({
    method: 'get',
    url: 'https://baidu.com'
})

// pending.abort()

pending.then(res => {
    console.log(res)
}).catch(e => {
    console.log(e)
})

Alias

config

type AjaxConfig<T = any> = {
    url?: string
    method?: Method
    headers?: {[p: string]: any}
    params?: {[p: string | number]: any}
    data?: any
    timeout?: number
    abortToken?: AbortToken
    auth?: {
        username: string
        password: string
    }
    responseType?: XMLHttpRequestResponseType
    withCredentials?: boolean
    validateStatus?: ((status: number) => boolean) | boolean
    onSuccess?(data: ResponseBody<T>): void
    onTimeout?(error: TimeoutError): void
    onError?(error: AjaxError): void
    onComplete?(data: ResponseBody<T> | null, error: AjaxError | null): void
    onAbort?(error: AbortError): void
    onUploadProgress?: ProgressCallback
    onDownloadProgress?: ProgressCallback
}

type Method =
    'get' | 'GET' |
    'delete' | 'DELETE' |
    'head' | 'HEAD' |
    'options' | 'OPTIONS' |
    'post' | 'POST' |
    'put' | 'PUT' |
    'patch' | 'PATCH' |
    'purge' | 'PURGE' |
    'link' | 'LINK' |
    'unlink' | 'UNLINK'

Response

type ResponseBody<T = any> = {
    result: T
    config: AjaxConfig<T>
    instance: XMLHttpRequest
    status: number
    statusText: string
    rawHeaders?: string
    headers: {[p: string]: number | string | string[]}
}

Modularization

Configure & Interceptors decorator

  • @Configure(url?: string)
  • @Configure(config?: AjaxConfig)
  • @BeforeRequest((config: AjaxConfig) => AjaxConfig | Promise\)
  • @BeforeResponse((response: any, error: any, config: AjaxConfig) => any)

example

import {AjaxAbort, AjaxConfig, AjaxError, BeforeRequest, BeforeResponse, Configure, OnFailed, OnSuccess, Service} from '@canlooks/ajax'

@Configure({
    url: 'https://baidu.com',
    headers: {
        'User-Agent': '@canlooks/ajax'
    }
})
@BeforeRequest((config: AjaxConfig) => {
    // To modify config before each request
    return config
})
@BeforeResponse((previousResponse: any, previousError: any, config: AjaxConfig) => {
    // Judge your own logic
    if (previousResponse.code === 'ERR') {
        // Make this request throw error
        throw Error('oh no')
    }
    // Change return value
    return res.data
})
class IndexService extends Service {
    @OnSuccess
    onSuccess(data: any, config: AjaxConfig) {
        // Do something when each request success.
    }

    @OnFailed
    OnFailed(error: AjaxError<any>, config: AjaxConfig) {
        // Do something when each request fail.
    }
}
@Configure('/search')
class ExampleService extends IndexService {
    myFn() {
        // Request method will hang on "this", such as "get", "post"...
        // The final request url is "https://baidu.com/search/test"
        return this.post('/test', {
            a: 572
        })
    }
}

Use with React

When componentWillUnmount, every connected services will abort automatically.

Connect decorator

@connect({
    [injectedPropertyName]: ServiceClass
})
import {Component} from 'react'
import {connect} from '@canlooks/ajax/react'
import {ExampleService} from 'somewhere'

@connect({
    myInjectedService: ExampleService
})
export default class Index extends Component {
    // Declaring properties if you use typescript
    declare myInjectedService!: ExampleService

    someMethod = async () => {
        const res = await this.myInjectedService.myFn()
    }

    render() {
        return <></>
    }
}

useService(ServiceClass)

import {useService} from '@canlooks/ajax/react'
import {ExampleService} from 'somewhere'

export default function Index() {
    const exampleService = useService(ExampleService)

    const someMethod = async () => {
        const res = await exampleService.myFn()
    }
    
    return <></>
}

Use with Vue

useService(ServiceClass)

<template>

</template>
<script lang="ts" setup>
import {useService} from '@canlooks/ajax/vue'
import {ExampleService} from 'somewhere'

const exampleService = useService(ExampleService)
</script>

registerAdapter(adapter)

Set your own request adapter in modularization.
Type of adapter

declare function registerAdapter(adapter: (config?: AjaxConfig) => any): void

For example, replace @canlooks/ajax with jquery

import $ from 'jquery'

registerAdapter((config: AjaxConfig = {}) => {
    return new Promise((success, error) => {
        const {headers, method, url, data} = config
        $.ajax({
            headers, method, url, data,
            success,
            error
        })
    })
})

For keeping abort()

import $ from 'jquery'

registerAdapter((config: AjaxConfig = {}) => {
    const instance
    const promise = new Promise((success, error) => {
        const {headers, method, url, data} = config
        instance = $.ajax({
            headers, method, url, data,
            success,
            error
        })
    })
    promise.abort = () => instance.abort()
    return promise
})
3.3.0

5 months ago

3.1.0-alpha1

10 months ago

3.2.8

6 months ago

3.2.7

8 months ago

3.2.2

9 months ago

3.2.1

9 months ago

3.2.0

9 months ago

3.1.1

10 months ago

3.1.0

10 months ago

3.2.6

8 months ago

3.2.5

8 months ago

3.2.4

8 months ago

3.2.3

8 months ago

2.1.3

12 months ago

3.0.3

11 months ago

3.0.2

11 months ago

3.0.1

11 months ago

3.0.0

11 months ago

2.1.2

12 months ago

2.1.1

12 months ago

2.1.0

12 months ago

2.0.1

1 year ago

2.0.0

1 year ago

1.4.4

1 year ago

1.4.3

1 year ago

1.4.2

2 years ago

1.4.1

2 years ago

1.4.0

2 years ago

1.3.1

2 years ago

1.3.0

2 years ago

1.2.1

2 years ago

1.2.0

2 years ago

1.1.2

2 years ago

1.1.1

2 years ago

1.1.0

2 years ago

1.1.0-alpha1

2 years ago

1.0.8

2 years ago

1.0.8-alpha1

2 years ago

1.0.7

2 years ago

1.0.6

2 years ago

1.0.5

2 years ago

1.0.4

2 years ago

1.0.3

2 years ago

1.0.2

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago