常用工具及库函数总结

83 阅读1分钟

正则

email: '^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$'

bankCardNum: '^([1-9]{1})(\d{12}|\d{18})'

sshkey: '^(?:ssh-rsa\s).+'

ips: '^((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))))(?:(?:\/(?:3[0-2]|2\d|1\d|\d)(?!.))|(?!.))'

domain: '^(?!www\.)([a-zA-Z0-9-]+\.){0,5}[a-zA-Z0-9-][a-zA-Z0-9-]+\.[a-zA-Z]{2,64}?$'

phone: ^[1][3,4,5,6,7,8,9][0-9]{9}$

复制到剪切板

export function copyToClipboard (text) {
  var x = document.createElement('input')
  x.defaultValue = x.value = text
  document.body.appendChild(x)
  x.select()

  document.execCommand('copy')

  if (document.selection) {
    document.selection.empty()
  } else if (window.getSelection) {
    window.getSelection().removeAllRanges()
  }

  document.body.removeChild(x)
}

请求拦截处理

常规错误拦截

import { extend } from 'umi-request';
import { notification } from 'antd'

const errorHandler = (error) => {
  throw new Error('error');
};

const request = extend({
  errorHandler, // 默认错误处理
  credentials: 'include', // 默认请求是否带上cookie
});

const handleJson = (res) => {
  console.log('handleJson', res)
  if (res.errno === 0) {
    return res
  } else {
    console.log('notification.error')
    notification.error({
      message: res.errmsg
    })
    return res
  }
}

const responseInterceptor = (response) => {
  const { status, statusText } = response
  const contentType = response.headers.get('content-type')
  const isPlainText = contentType?.indexOf('text/plain; charset=utf-8') !== -1
  let responsePromise
  if (status === 200 || status === 201 || status === 202) {
    if (isPlainText) {
      responsePromise = response.clone().text()
    } else {
      responsePromise = response.clone().json()
    }
    return responsePromise.then((res) => {
      return isPlainText ? res : handleJson(res)
    })
  }
  return response
    .clone()
    .json()
    .then((res) => {
      if (res.error) {
        notification.error({
          message: res.error.code,
          description: res.error.message
          // duration: null
        })
      }
      return res
    })
}

request.interceptors.response.use(responseInterceptor, { global: false })

export default request;

下载时响应拦截处理:

request.interceptors.response.use(
  (request) => {
    const { status, statusText } = request;
    let errorMsg;
    if (status === 200) {
      const contentType = request.headers.get('content-type');
      const contentDisposition = request.headers.get('content-disposition');
      const filename = contentDisposition?.substring(contentDisposition.indexOf('filename') + 'filename='.length)
      // console.log('contentDisposition', contentDisposition)
      const isJsonType =
        contentType?.indexOf('application/json; charset=utf-8') !== -1;
      const isXlsxSheet = contentType === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      const jsonTypeRequestHandler = () =>
        request
          .clone()
          .json()
          .then((data) => {
            if (data.error?.message) {
              data.err = data.error.message || '未知错误!';
            }
            if (data.err === 'unauthorized') {
              location.href = `/login${
                location.pathname != '/' ? '?redirect=' + location.pathname : ''
              }`;
            } else if (data.err === '' || data.err === undefined) {
              if (data.data || data.dat) {
                if (
                  data.dat &&
                  Object.prototype.toString.call(data.dat.list) ===
                    '[object Null]'
                ) {
                  data.dat.list = [];
                }
              }
              return { ...data, success: true };
            } else {
              throw new InterfaceError(data.err, data);
            }
          });
      const blobTypeRequestHandler = (customFilename) =>
        request
          .clone()
          .blob()
          .then((res) => {
            const blobUrl = window.URL.createObjectURL(res);
            const link = document.createElement('a');
            link.href = blobUrl;
            console.log('blobUrl', blobUrl)
            const fileName = blobUrl.substring(blobUrl.lastIndexOf('/') + 1)
            link.download = customFilename || fileName;
            document.body.appendChild(link);
            link.dispatchEvent(
              new MouseEvent('click', {
                bubbles: true,
                cancelable: true,
                view: window,
              }),
            );
            document.body.removeChild(link);
          });
      return isJsonType ? jsonTypeRequestHandler() : (contentDisposition || isXlsxSheet) ? blobTypeRequestHandler(filename) : request.clone();
    }
    if (status === 401 || status === 452) {
      location.href = `/login${
        location.pathname != '/' ? '?redirect=' + location.pathname : ''
      }`;
    }
    if (status === 403 || status === 404) {
      return request
        .clone()
        .json()
        .then((data) => {
          errorMsg = data?.err || data?.error?.message || '您的网络发生异常,无法连接服务器';
          notification.error({
            message: errorMsg,
          });
        });
    }
    throw new Error(errorMsg || '未知错误');
  },
  {
    global: false,
  },
);