提交 132f94e0 authored 作者: 钟是志's avatar 钟是志

公共方法添加

上级 d9bf47e9
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
.svn
.idea
yarn.lock
# misc
.DS_Store
npm-debug.log*
// use localStorage to store the authority info, which might be sent from server in actual project.
export function getAuthority() {
return localStorage.getItem('antd-pro-authority') || 'admin';
}
export function setAuthority(authority) {
return localStorage.setItem('antd-pro-authority', authority);
}
export function clearToken() {
localStorage.removeItem('antd-username');
return localStorage.removeItem('antd-pro-oauth2')
}
export function setUsername(usename) {
localStorage.setItem('antd-username', usename);
}
export function getUsername(usename) {
return localStorage.getItem('antd-username');
}
export function setToken(token) {
return localStorage.setItem('antd-pro-oauth2', token);
}
export function getToken() {
return localStorage.getItem('antd-pro-oauth2');
}
export function isJSON(str) {
if (typeof str === 'string') {
try {
JSON.parse(str);
if(typeof JSON.parse(str) === 'number'){
return false;
}
return true;
} catch (e) {
return false;
}
}
}
/**
* 深拷贝函数
* */
export function deepCopy(obj, parent = null) {
if(['boolean','string','number',].indexOf(typeof obj) > -1 || !obj){
return obj;
}
let result;
if (obj.constructor === Array) {
result = [];
} else {
result = {};
}
let keys = Object.keys(obj),
key = null,
temp= null,
_parent = parent;
// 该字段有父级则需要追溯该字段的父级
while (_parent) {
// 如果该字段引用了它的父级则为循环引用
if (_parent.originalParent === obj) {
// 循环引用直接返回同级的新对象
return _parent.currentParent;
}
_parent = _parent.parent;
}
for (let i = 0; i < keys.length; i++) {
key = keys[i];
temp= obj[key];
// 如果字段的值也是一个对象
if (temp && typeof temp=== 'object') {
// 递归执行深拷贝 将同级的待拷贝对象与新对象传递给 parent 方便追溯循环引用
result[key] = deepCopy(temp, {
originalParent: obj,
currentParent: result,
parent: parent
});
} else {
result[key] = temp;
}
}
return result;
}
export default function financial(x) {
if (typeof x === undefined || x == null) {
x = 0;
}
return '¥' + Number.parseFloat(x).toFixed(2);
}
export function setLocalStorage(key, vaule) {
return localStorage.setItem(key, JSON.stringify(vaule));
}
export function getLocalStorage(key) {
const value = JSON.parse(localStorage.getItem(key));
return value;
}
\ No newline at end of file
'use strict'
function isObject (value) {
return value === Object(value)
}
function isArray (value) {
return Array.isArray(value)
}
function isFile (value) {
return value instanceof File
}
function makeArrayKey (key) {
return key
}
function objectToFormData (obj, fd, pre) {
fd = fd || new FormData()
Object.keys(obj).forEach(function (prop) {
var key = pre ? (pre + '[' + prop + ']') : prop
if (isObject(obj[prop]) && !isArray(obj[prop]) && !isFile(obj[prop])) {
objectToFormData(obj[prop], fd, key)
} else if (isArray(obj[prop])) {
obj[prop].forEach(function (value) {
var arrayKey = makeArrayKey(key)
if (isObject(value) && !isFile(value)) {
objectToFormData(value, fd, arrayKey)
} else {
fd.append(arrayKey, value)
}
})
} else {
fd.append(key, obj[prop])
}
})
return fd
}
export default objectToFormData
import request from './request';
import qs, { parse } from 'qs';
import FormdataWrapper from './object-to-formdata-custom';
import merge from 'merge-object';
import config from '../../config/config'
import { getLocalStorage, setLocalStorage } from './helper';
import fetch from 'dva/fetch';
const cookieTrue = {
credentials: 'include'
};
const jsonConf = {
headers: {
'Content-Type': 'application/json'
}
}
function getUser() {
return getLocalStorage("user")
}
function getUrl(smarturl, flag) {
if (flag) {
return config.rapHost + '/' + smarturl;
} else {
return config.onlinePath + smarturl;
}
}
function getImgUrl(smarturl) {
if (smarturl == null) {
return '';
}
if (config.rapFlag) {
return config.rapImagePath + smarturl;
} else {
return config.onlinePath + smarturl;
}
}
async function POST(url, params, isJson) {
let user = getUser()
if (user != null) {
params.token = user.token
}
params.v = Date.parse(new Date())
params.domain = document.domain
if (isJson == undefined) { isJson = false };
return request(getUrl(url, config.rapFlag), merge({
method: 'POST',
body: isJson ? JSON.stringify(params) : FormdataWrapper(params),
}, isJson ? merge(jsonConf, cookieTrue) : cookieTrue), config.rapFlag);
}
async function GET(url, params) {
let user = getUser()
if (user != null) {
params.token = user.token
}
params.v = Date.parse(new Date())
params.domain = document.domain
return request(getUrl(url, config.rapFlag) + `?${qs.stringify(params)}`, merge({
method: 'GET', mode: 'cors', credentials: 'omit',
}, cookieTrue));
}
/* message.config({
top: 300,
duration: 2,
}); */
function check(data, payload) {
if (data == null) {
//message.info("当前网络比较慢,请刷新页面重试")
console.log("当前网络比较慢,请刷新页面重试")
return false
}
if (data.errorCode == "auth") {
if(payload.auth!=null){
console.log("xxxxxxxxxxxx")
payload.auth()
}
return false
}
if (data.errorCode == "fail") {
// message.error(data.msg ,data.msg.length /2 >3?data.msg.length /2:3, null)
return false
}
if (data.errorCode == "delay") {
// message.error("服务器请求错误,请联系管理员", 10, null)
return false
}
return true
}
export {
POST, GET, getImgUrl, getUser, check
}
/* import fetch from 'fetch'; */
import { stringify } from 'qs';
import { Toast, Modal } from 'antd-mobile';
import { routerRedux } from 'dva/router';
import store from '../../index';
import FormdataWrapper from './object-to-formdata-custom';
import { getToken } from './authority';
const codeMessage = {
200: '服务器成功返回请求的数据。',
201: '新建或修改数据成功。',
202: '一个请求已经进入后台排队(异步任务)。',
204: '删除数据成功。',
400: '发出的请求有错误,服务器没有进行新建或修改数据的操作。',
401: '用户没有权限(令牌、用户名、密码错误)。',
403: '用户得到授权,但是访问是被禁止的。',
404: '发出的请求针对的是不存在的记录,服务器没有进行操作。',
406: '请求的格式不可得。',
410: '请求的资源被永久删除,且不会再得到的。',
422: '当创建一个对象时,发生一个验证错误。',
500: '服务器发生错误,请检查服务器。',
502: '网关错误。',
503: '服务不可用,服务器暂时过载或维护。',
504: '网关超时。',
};
function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response;
}
const errortext = codeMessage[response.status] || response.statusText;
Toast.info(`请求错误 ${response.status}: ${response.url}`)
const error = new Error(errortext);
error.name = response.status;
error.response = response;
throw error;
}
/**
* Requests a URL, returning a promise.
*
* @param {string} url The URL we want to request
* @param {object} [options] The options we want to pass to "fetch"
* @return {object} An object containing either "data" or "err"
*/
export default function request(url, options) {
const defaultOptions = {
credentials: 'omit',
mode: 'cors',
};
const newOptions = { ...defaultOptions, ...options };
if (getToken() && url.indexOf('/third/token') <= -1) {
url = url + "?token=" + getToken()
}
if (newOptions.method === 'POST' || newOptions.method === 'PUT') {
if (!(newOptions.body instanceof FormData)) {
newOptions.headers = {
Accept: 'application/json;charset=UTF-8',
/* 'X-Requested-With':'XMLHttpRequest', */
...newOptions.headers,
};
newOptions.body = FormdataWrapper(newOptions.body);
} else {
// newOptions.body is FormData
newOptions.headers = {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
...newOptions.headers,
};
}
} else {
if (options) {
url = url + '?' + stringify(options);
}
}
return fetch(url, newOptions).then(checkStatus)
.then(response => {
if (response.status === 202) {
return response.text();
}
return response.json();
})
.then(response => {
if (typeof response === 'string') {
let xxx = '';
try{
xxx = JSON.parse(response)
if (xxx.errMsg) {
Toast.hide();
Modal.alert('', `${xxx.errMsg}`, [
{ text: '知道了', onPress: () => console.log('ok') },
]);
return;
}
}catch(e){
}
}
return response;
})
.catch(e => {
const { dispatch } = store;
const status = e.name;
if (status === 401) {
Toast.hide();
Toast.info('登录信息已过期,请重新登录')
dispatch(routerRedux.push('/'));
return;
}
if (status === 403) {
dispatch(routerRedux.push('/exception/403'));
return;
}
if (status <= 504 && status >= 500) {
dispatch(routerRedux.push('/exception/500'));
return;
}
if (status >= 404 && status < 422) {
dispatch(routerRedux.push('/exception/404'));
return;
}
});
}
import { getLocalStorage, setLocalStorage } from './helper';
var websocket = null;
var listeners = []
function getUser() {
return getLocalStorage("user")
}
let user = getUser()
function wsConnect(firstMsg,onMsg){
if(websocket==null){
if('WebSocket' in window){
websocket = new WebSocket("ws://localhost:52058/websocket");
clearListener()
listeners.push(onMsg)
websocket.onerror = function(){
console.log("链接错误")
};
//连接成功建立的回调方法
websocket.onopen = function(event){
wsSend(firstMsg)
console.log("链接建立")
}
//接收到消息的回调方法
websocket.onmessage = function(event){
for (var i=0;i<listeners.length;i++) {
listeners[i](JSON.parse(event.data))
}
}
//连接关闭的回调方法
websocket.onclose = function(){
console.log("链接关闭")
}
}else{
console.log('Not support websocket')
}
}
}
function wsSend(message){
message.token=user.token
websocket.send(JSON.stringify(message));
}
function wsCloset(){
websocket.close();
}
function clearListener(func){
listeners=[]
}
function addListener(func){
listeners.push(func)
}
export {
wsSend,addListener,clearListener,wsConnect
}
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论