# 请求

# jsonp

jsonp 请求(不支持设置 header)

定义:

interface JSONPOptions {
    url: URLLike;
    callbackFnName?: string; // default: 'callback'
    data?: {
        [key: string]: string | number;
    };
    timeout?: number; // default: 3000(ms)
    context?: any; // 除测试外一般不使用
}
export declare const jsonp: <T>({ url, data, timeout, callbackFnName, context, }: JSONPOptions) => Promise<T>;

# Loader

  1. buildLoader

动态加载(同一 URL 只会加载一次)

定义:

export interface LoaderURLOptions {
    url: URLLike;
    autoHttps?: boolean;
}
export declare type LoaderURL = URLLike | LoaderURLOptions;
export interface LoaderBuildOptions {
    type?: string;
    domBuilder: (url: string) => HTMLElement;
}
export declare const buildLoader: ({ domBuilder, type, }: LoaderBuildOptions) => (opts: LoaderURL | LoaderURL[]) => Promise<void>;
  1. loadScript/loadStyle

动态加载脚本/样式,基于 buildLoader

注意: 由于 buildLoader 同一 URL 只会加载一次的特性, 即使同一 URL 分别使用 loadScript/loadStyle 加载, 依旧只会在先执行的函数中加载,后执行的函数等待加载。

定义:

export declare const loadScript: (opts: LoaderURL | LoaderURL[]) => Promise<void>;
export declare const loadStyle: (opts: LoaderURL | LoaderURL[]) => Promise<void>;

# SWR(stale-while-revalidate)

关于此方法的资料可参考:

后续会基于此方法实现 vue 的 composition-api 版

# dedup

重复数据消除 (throttle 只能节流操作,无法返回数据),本方法会根据 key 缓存请求,在指定时间内的重复请求将被丢弃返回缓存值。

定义:

export interface DedupOptions<Data> {
    key: string;
    fetcher: (key: string) => Promise<Data>;
    dedupingInterval?: number;
}
export declare const dedup: <Data>({ key, fetcher, dedupingInterval, }: DedupOptions<Data>) => Promise<Data>;

用法:

await dedup({ key, async fetcher() { return 1 } })

# createSWR

创建 SWR 实例。创建实例的目的为指定数据存储位置——大多已有的 SWR 实现仅将数据存于内存中,本实现基于 ProxyStorage,支持将数据持久化到 localStorage 等位置,便于多页面应用、Hippy 等场景下的使用。此外,在储存到 localStorage 时,建议开启 ProxyStorage 的 LRU 缓存插件,防止缓存过多过期数据。

定义:

import { ProxyStorage } from '../storage';
export interface DedupOptions<Data> {
    key: string;
    fetcher: (key: string) => Promise<Data>;
    dedupingInterval?: number;
}
export interface CreateSWROptions {
    ns?: string;
    storage?: ProxyStorage<SWRCacheModel, string> | 'RAM';
}
export interface SWROptions<Data = any, Key = string> {
    key: Key;
    fetcher: (key: Key) => Promise<Data>;
    initialData?: Data;
    dedupingInterval?: number;
    focusThrottleInterval?: number;
    onSuccess?: (data: Data | undefined, key: Key) => void;
    onError?: (err: any, key: Key) => void;
    enabled?: boolean;
}
export declare const createSWR: (options?: CreateSWROptions | undefined) => {
    swr: <Data = any, Key = string>({ key, fetcher, initialData, dedupingInterval, focusThrottleInterval, onSuccess, onError, enabled, }: SWROptions<Data, Key>) => {
        refetch: () => Promise<void>;
    };
};

用法:

const { swr } = createSWR()

const key = '/user'
const fetcher = async () => { /* getUserInfo */ }
let userInfo: any = undefined
const onSuccess = (data) => userInfo = data

swr({ key, initialData, fetcher, onSuccess })
更新于: 6/25/2021, 5:28:40 PM