# util **Repository Path**: tb211/util ## Basic Information - **Project Name**: util - **Description**: 函数类工具库 - **Primary Language**: JavaScript - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 1 - **Created**: 2022-08-23 - **Last Updated**: 2024-01-09 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # function utils lib 函数类工具库 ## Install ```shell # npm npm install --save @tangbin/util # pnpm pnpm add @tangbi/util ``` ## API 详细 API 文档请查看 [函数类工具库](./docs/index.html) ## Usage ### sso ```typescript import React, { FC, useEffect } from 'react'; import { sso } from '@tangbin/util'; const Index: FC = () => { useEffect(() => { sso .login() .then((loginInfo) => { console.log('登录成功', loginInfo); }) .catch((err) => { console.log('登录失败', err); }); }, []); }; export default Index; ``` ### request ```typescript import { message } from 'antd'; import { ajax, get, post, upload, download, registerShowErrorMsgFn, registerExtraSuccessCodes, } from '@tangbin/util'; // 注册通用错误回调方法 registerShowErrorMsgFn(message.error); // 注册通用 ajax 请求成功返回码(默认返回码是数字200,传递第二个参数是用来替换默认值) registerExtraSuccessCodes(['200', '0'], true); // function ajax(requestConfig: RequestConfig): Promise // 直接调用 ajax 方法,可以自由设置任何选项,特殊情况下可以调用 ajax({ type: 'GET', url: '/module/fetch', // 如果需要自己处理错误信,可以设置为true customErrorMsg: true, }); // function get(url: string, params?: Record, config?: RequestConfig): Promise get('/module/fetch', { name: 'abc', age: 123 }, { responseType: 'json' }); // function post(url: string, params?: Record, config?: RequestConfig): Promise post('/module/fetch', { name: 'abc', age: 123 }, { responseType: 'json' }); // function upload(url: string, params: Record, config?: RequestConfig): Promise upload('/module/upload', { name: 'abc', age: 123 }, { responseType: 'json' }); // function download({ gateway, prefix, downloadType, customErrorMsg, url, ...config }: RequestConfig): void download({ url: '/module/fetch', downloadType: 'excel', }); interface Student { name: string; age: number; } export function query(id: number): Promise { return get('/student/query', { id }); } query(1).then((student) => { console.log('fetch student success', student); }); ``` ### util ```typescript import { debounce, throttle, flatten, curry, compose } from '@tangbin/util'; const elem = document.getElementById('elem'); // 防抖函数 elem.addEventListener( 'input', debounce(function (event) { console.log(event); }), false, ); // 节流函数 window.addEventListener( 'resize', throttle(function (event) { console.log(event); }), false, ); // 数组扁平化 const arr = [1, 2, ['a', [true, false], 'b'], 3]; flatten(arr); // output: [1, 2, 'a', [true, false], 'b', 3] flatten(arr, true); // output: [1, 2, 'a', true, false, 'b', 3] // 函数柯里化 function add(x: number, y: number, z: number) { return x + y + z; } curry(add)(1)(2)(3); // output: 6 curry(add)(1, 2)(3); // output: 6 // 函数组合 function last(arr: string[]) { return arr[arr.length - 1]; } function upper(str: string) { return str.toUpperCase(); } const letters = ['a', 'b', 'c']; compose([upper, last])(letters); // output: C // 返回 Object.prototype.toString.call(val) = '[object xxx]' 中 xxx 部分的小写形式 typeOf(''); // output: string typeOf(0); // output: number typeOf(true); // output: boolean // 深拷贝 const source = { name: 'aaa', age: 111 }; // 如果确定没有副作用,可以使用这个函数 deepCloneByJSON(source); // 如果有副作用,使用这个函数 deepClone(source); ``` ### hooks - react ```typescript // src/@types/people.d.ts export interface People { id?: number; name: string; age: number; } ``` 查询 ```typescript // pages/people/detail.tsx import { useState } from 'react'; import { useFetch, fetch, query } from '@tangbin/util'; import { People } from 'src/@types/people'; const Index: FC = () => { const [id, setId] = useState(0); const [params, setParams] = useState({ name: '', startTime: '', endTime: '', }); // useFetch 和 useFetchWithLoading 用法相同,后者返回4个值,通过 setLoading 触发查询 // const [info, setInfo, loading, setLoading] = useFetchWithLoading // 根据ID查询数据,value 必填,其他可选 // fetch(url, id, flag) const [info, setInfo] = useFetch({ url: '/a/b/c', // 如果不传 fn,则 url 必填 // fn: fetch, // fn 默认既是 fetch value: { name: '', age: -1 }, deps: [id], onBeforeFetch: () => !!id, onSuccess: (res) => { console.log('查询成功', res.name, res.age); }, onError: (err) => { console.log('查询失败', err); }, onComplete: () => { console.log('我在最后运行'); }, }); // 普通查询 // query(url, params = {}, flag) const [student] = useFetch({ url: '/a/b/c', fn: query, params: [params], value: [], deps: [params], }); return
...
; }; export default Index; ``` 添加/修改/删除 ```typescript // pages/people/update/index.tsx import { useCallback } from 'react'; import { useUpdateWithLoading, update } from '@tangbin/util'; import { People } from 'src/@types/people'; const Index: FC = () => { // useUpdate 和 useUpdateWithLoading 用法相同,后者返回4个值,通过 setLoading 触发查询 // const [info, setInfo, loading, setLoading] = useFetchWithLoading // value 和 onBeforeFetch 必填,其他可选 const [params, setParams, loading, setLoading] = useUpdateWithLoading< People, boolean | null >({ url: '/a/b/c', // 如果不传 fn,则 url 必填 // fn: update, // fn 默认既是 update value: { id: 0, name: '', age: -1 }, onBeforeFetch: (p) => !!p.name, }); // 通过 setLoading(true) 启动 const onAdd = useCallback(() => { setLoading(true); }, [loading]); return
...
; }; export default Index; ``` 分页查询 ```typescript // pages/people/index.tsx import { useCallback } from 'react'; import { Form, Table } from 'antd'; import { usePagination, paging, initPaginationParams } from '@tangbin/util'; import { People } from 'src/@types/people'; const Index: FC = () => { const form = Form.useForm(); // value, params 和 onBeforeFetch 必填,其他可选。 const { loading, setLoading, list, params, setParams, pagination } = usePagination({ url: '/a/b/c', // 如果不传 fn,则 url 必填 // fn: paging, // fn 默认既是 paging value: initPaginationParams({}), // 如果使用了 ant design 的表单,可以提供 form 事例用于获取查询参数 form, // 如果需要手动格式化,可以使用 formatParams 方法 formatParams: (p: FetchParams) => { p.name = '_' + p.name; return p; }, onBeforeFetch: () => true, }); // 通过 setLoading(true) 启动, 或者分页(以及内置) const onSearch = useCallback( (values) => { setParams({ ...params, ...values }); setLoading(true); }, [params, loading], ); return (
); }; export default Index; ```