提交 11c0367e authored 作者: vipcxj's avatar vipcxj

从web工程迁移公用代码

上级 1f139e04
......@@ -2,11 +2,11 @@ node_modules/
.expo/
ios/build/
android/.gradle
android/.idea
android/build/
android/app/build/
npm-debug.*
*.iml
.idea
npm-debug.log
yarn-error.log
......
......@@ -34,6 +34,9 @@
"dependencies": {
"antd-mobile": "^2.0.0",
"dva-core": "^1.1.0",
"fastjson_ref_resolver": "0.0.3",
"lodash": "latest",
"moment": "^2.19.1",
"react": "^16.0.0-beta.5",
"react-native": "^0.49.3",
"react-navigation": "^1.0.0-beta.14",
......
import { mapKeys, toPairs, isUndefined, isString, partial } from 'lodash';
import request from '../utils/request';
import post from '../utils/post';
import { normParams } from '../utils/http-helper';
import { split } from '../utils/filter';
import config from '../utils/config';
const parseFilters = filtersIn => (filtersIn || []).filter(({ filter }) => !!filter).map(({ key, filter }) => [
split(key, false).map(value => `f-${value}`).join('|'),
filter,
]);
export const datasourceApi = (coordinate) => {
const { containerType, containerName, datasourceName } = isString(coordinate) ? {
containerType: 'global',
moduleName: coordinate,
} : (coordinate || {});
if (containerType === 'global') {
return {
query: partial(calcGlobalDatasource, datasourceName),
count: partial(countGlobalDatasource, datasourceName),
cursor: partial(cursorGlobalDatasource, datasourceName),
meta: partial(getGlobalDatasourceMeta, datasourceName),
update: partial(updateGlobalDatasource, datasourceName),
create: partial(createGlobalDatasource, datasourceName),
remove: partial(removeGlobalDatasource, datasourceName),
validateUpdate: partial(validateUpdateGlobalDatasource, datasourceName),
validateCreate: partial(validateCreateGlobalDatasource, datasourceName),
validateRemove: partial(validateRemoveGlobalDatasource, datasourceName),
};
} else if (containerType === 'module') {
return {
query: partial(calcModuleDatasource, containerName, datasourceName),
count: partial(countModuleDatasource, containerName, datasourceName),
cursor: partial(cursorModuleDatasource, containerName, datasourceName),
meta: partial(getModuleDatasourceMeta, containerName, datasourceName),
update: partial(updateModuleDatasource, containerName, datasourceName),
create: partial(createModuleDatasource, containerName, datasourceName),
remove: partial(removeModuleDatasource, containerName, datasourceName),
validateUpdate: partial(validateUpdateModuleDatasource, containerName, datasourceName),
validateCreate: partial(validateCreateModuleDatasource, containerName, datasourceName),
validateRemove: partial(validateRemoveModuleDatasource, containerName, datasourceName),
};
} else {
throw new Error(`Unsupported containerType: ${containerType}`);
}
};
const makeQueryParams = ({ pst, psz, filters = [], sortBys = [], sortTypes = [], params = {} }) => {
let stBy = sortBys.join(',');
stBy = stBy || undefined;
let stType = sortTypes.join(',');
stType = stType || undefined;
return [
...toPairs({ pst, psz, stBy, stType }),
...parseFilters(filters),
...normParams(mapKeys(params, (v, k) => `p-${k}`)),
].filter(v => v && !isUndefined((v[1])));
};
const makeParams = (otherParams, { filters = [], sortBys = [], sortTypes = [], params = {} }) => {
return [
...toPairs(otherParams),
...makeQueryParams({ filters, sortBys, sortTypes, params }),
].filter(v => v && !isUndefined((v[1])));
};
export async function calcGlobalDatasource(name, { pst, psz, filters = [], sortBys = [], sortTypes = [], params = {}, dmPath }) {
return request(`${config.apiContextPath}/api/datasource/${name}`, makeParams({ pst, psz, dmPath }, { filters, sortBys, sortTypes, params }));
}
export async function countGlobalDatasource(name, { filters = [], params = {}, dmPath }) {
return request(`${config.apiContextPath}/api/datasource/${name}/count`, makeParams({ dmPath }, { filters, params }));
}
export async function cursorGlobalDatasource(name, key, params = {}, dmPath) {
return request(`${config.apiContextPath}/api/datasource/${name}/cursor`, makeParams({ key, dmPath }, { params }));
}
export async function validateUpdateGlobalDatasource(name, key, params = {}, dmPath) {
return request(`${config.apiContextPath}/api/datasource/${name}/update/validate`, makeParams({ key, dmPath }, { params }));
}
export async function updateGlobalDatasource(name, key, params = {}, dmPath) {
return post(`${config.apiContextPath}/api/datasource/${name}/update`, {
key,
params,
dmPath,
});
}
export async function validateCreateGlobalDatasource(name, params = {}, dmPath) {
return request(`${config.apiContextPath}/api/datasource/${name}/create/validate`, makeParams({ dmPath }, { params }));
}
export async function createGlobalDatasource(name, params = {}, dmPath) {
return post(`${config.apiContextPath}/api/datasource/${name}/create`, {
params,
dmPath,
});
}
export async function validateRemoveGlobalDatasource(name, key, params = {}, dmPath) {
return request(`${config.apiContextPath}/api/datasource/${name}/remove/validate`, makeParams({ key, dmPath }, { params }));
}
export async function removeGlobalDatasource(name, key, params = {}, dmPath) {
return post(`${config.apiContextPath}/api/datasource/${name}/remove`, {
key,
params,
dmPath,
});
}
export async function getGlobalDatasourceMeta(name) {
return request(`${config.apiContextPath}/api/datasource/${name}/meta`);
}
export async function calcModuleDatasource(mdName, dsName, { pst, psz, filters = [], sortBys = [], sortTypes = [], params = {}, dmPath }) {
return request(`${config.apiContextPath}/api/module/user/${mdName}/datasource/${dsName}`, makeParams({ pst, psz, dmPath }, { filters, sortBys, sortTypes, params }));
}
export async function countModuleDatasource(mdName, dsName, { filters = [], params = {}, dmPath }) {
return request(`${config.apiContextPath}/api/module/user/${mdName}/datasource/${dsName}/count`, makeParams({ dmPath }, { filters, params }));
}
export async function cursorModuleDatasource(mdName, dsName, key, params = {}, dmPath) {
return request(`${config.apiContextPath}/api/module/user/${mdName}/datasource/${dsName}/cursor`, makeParams({ key, dmPath }, { params }));
}
export async function validateUpdateModuleDatasource(mdName, dsName, key, params = {}, dmPath) {
return request(`${config.apiContextPath}/api/module/user/${mdName}/datasource/${dsName}/update/validate`, makeParams({ key, dmPath }, { params }));
}
export async function updateModuleDatasource(mdName, dsName, key, params = {}, dmPath) {
return post(`${config.apiContextPath}/api/module/user/${mdName}/datasource/${dsName}/update`, {
key,
params,
dmPath,
});
}
export async function validateCreateModuleDatasource(mdName, dsName, params = {}, dmPath) {
return request(`${config.apiContextPath}/api/module/user/${mdName}/datasource/${dsName}/create/validate`, makeParams({ dmPath }, { params }));
}
export async function createModuleDatasource(mdName, dsName, params = {}, dmPath) {
return post(`${config.apiContextPath}/api/module/user/${mdName}/datasource/${dsName}/create`, {
params,
dmPath,
});
}
export async function validateRemoveModuleDatasource(mdName, dsName, key, params = {}, dmPath) {
return request(`${config.apiContextPath}/api/module/user/${mdName}/datasource/${dsName}/remove/validate`, makeParams({ key, dmPath }, { params }));
}
export async function removeModuleDatasource(mdName, dsName, key, params = {}, dmPath) {
return post(`${config.apiContextPath}/api/module/user/${mdName}/datasource/${dsName}/remove`, {
key,
params,
dmPath,
});
}
export async function getModuleDatasourceMeta(mdName, dsName) {
return request(`${config.apiContextPath}/api/module/user/${mdName}/datasource/${dsName}/meta`);
}
/* eslint-disable no-param-reassign */
import request from '../utils/request';
import post from '../utils/post';
import config from '../utils/config';
import { getDomain } from '../utils/auth';
export async function fetchDomains(basePath, withRoot = false) {
if (!basePath) {
const domain = await getDomain();
if (!domain) {
throw new Error('Not set domain yet!');
}
basePath = domain.path;
}
const rootDomainInfo = withRoot ? await request(`${config.apiContextPath}/api/domain/user/info`, { dmPath: basePath }) : null;
const childrenDomainInfoList = await request(`${config.apiContextPath}/api/domain/user/children-info`, { dmPath: basePath });
let infoList;
if (rootDomainInfo && childrenDomainInfoList) {
infoList = [
rootDomainInfo,
...childrenDomainInfoList,
];
} else if (rootDomainInfo) {
infoList = [rootDomainInfo];
} else if (childrenDomainInfoList) {
infoList = childrenDomainInfoList;
} else {
infoList = [];
}
return infoList;
}
export async function switchDomain(path) {
return post(`${config.apiContextPath}/api/domain/user/path`, { dmPath: path });
}
export async function currentDomain() {
return request(`${config.apiContextPath}/api/domain/user/info`);
}
import Fingerprint from 'fingerprintjs';
import post from '../utils/post';
import request from '../utils/request';
import config from '../utils/config';
export async function login(payload) {
const data = {};
data.type = payload.type;
if (data.type === 'userName') {
data.data = payload.userName;
}
if (payload.authType === 'password') {
data.authRequest = {
type: payload.authType,
parameters: {
cipher: payload.password,
},
};
}
data.tokenInfo = {
productId: 'big-machine-web-front',
deviceId: `${new Fingerprint({ ie_activex: true }).get()}`,
};
return post(`${config.apiContextPath}/api/auth/login`, data, {}, {}, false);
}
export async function userInfo() {
return request(`${config.apiContextPath}/api/user/info`);
}
/**
* Created by yaohx_169 on 2017/6/8.
*/
import { cookie } from './config';
import { AsyncStorage } from 'react-native';
export async function getToken() {
return AsyncStorage.getItem(cookie.token);
}
export async function setToken(token) {
return AsyncStorage.setItem(cookie.token, token);
}
export async function delToken() {
return AsyncStorage.removeItem(cookie.token);
}
export async function getUser() {
return {
id: await AsyncStorage.getItem(cookie.userId),
name: await AsyncStorage.getItem(cookie.userName),
};
}
export async function setUser(id, name) {
await AsyncStorage.setItem(cookie.userId, id);
await AsyncStorage.setItem(cookie.userName, name);
}
export async function delUser() {
await AsyncStorage.removeItem(cookie.userId);
await AsyncStorage.removeItem(cookie.userName);
}
export async function getDomain() {
return {
name: await AsyncStorage.getItem(cookie.domainName),
path: await AsyncStorage.getItem(cookie.domainPath),
};
}
export async function setDomain(name, path) {
await AsyncStorage.setItem(cookie.domainName, name);
await AsyncStorage.setItem(cookie.domainPath, path);
}
export async function delDomain() {
await AsyncStorage.removeItem(cookie.domainName);
await AsyncStorage.removeItem(cookie.domainPath);
}
export async function isAuthed() {
return getToken().then(result => !!result);
}
export async function hasDomain() {
return getDomain().then(result => !!result);
}
import _ from 'lodash';
import { fetch } from './polyfill';
import { encrypt } from './helper';
import { errors } from './error';
import { getToken } from './auth';
import { checkStatus, normParams, parseObject } from './http-helper';
const defaultOptions = {
headers: { Accept: 'application/json' },
};
/**
* Requests a URL, returning a promise.
*
* @param {string} url The URL we want to request
* @param auth
* @param params
* @param {object} [options] The options we want to pass to "fetch"
* @return {object} An object containing either "data" or "err"
*/
export default async function doDelete(url, params = {}, options = {}, auth = true) {
let token;
if (auth) {
token = await getToken();
if (!token) {
return Promise.reject(errors.tokenMissing());
}
token = encrypt(token);
}
let queryParams = token ? [...normParams(params), ['token', token]] : normParams(params);
queryParams = queryParams.map(([k, v]) => (_.isNil(v) ? k : `${k}=${encodeURIComponent(v)}`));
queryParams = queryParams.join('&');
let realUrl = url;
if (queryParams) {
realUrl = `${url}?${queryParams}`;
}
const realOptions = _.defaults(options, defaultOptions);
realOptions.method = 'DELETE';
return fetch(realUrl, realOptions)
.then(checkStatus)
.then(parseObject);
}
const findSep = (value, offset = 0) => {
const find = value.indexOf('|', offset);
if (find !== -1) {
let count = 0;
let from = find;
while (value[--from] === '#') ++count;
if ((count & 1) === 1) {
return findSep(value, find + 1);
} else {
return find;
}
} else {
return -1;
}
};
const transform = (value) => {
const find = value.indexOf('#');
if (find !== -1) {
const left = value.slice(0, find);
const me = value[find + 1] ? value[find + 1] : '';
const right = value.slice(find + 2);
return `${left}${me}${transform(right)}`;
} else {
return value;
}
};
export const split = (value, unescape = true) => {
const ret = [];
let offset = 0;
let posSep = -1;
do {
posSep = findSep(value, offset);
if (posSep !== -1) {
if (unescape) {
ret.push(transform(value.slice(offset, posSep)));
} else {
ret.push(value.slice(offset, posSep));
}
offset = posSep + 1;
}
} while (posSep !== -1);
if (unescape) {
ret.push(transform(value.slice(offset)));
} else {
ret.push(value.slice(offset));
}
return ret;
};
import moment from 'moment';
import _ from 'lodash';
import { createJSEncrypt } from './jsencrypt';
import config from './config';
const { contextPath, pubKey } = config;
export function setCookie(name, value, options = {}) {
const { path, domain, expires } = options;
if (name) {
const expireSet = expires ? ` expires=${moment().add(expires, 'ms').toDate().toUTCString()};` : '';
const domainSet = domain ? ` domain=${domain};` : '';
const pathSet = path ? ` path=${path};` : '';
const valueSet = value ? `${name}=${encodeURIComponent(value)};` : '';
document.cookie = `${valueSet}${expireSet}${domainSet};${pathSet}`; // eslint-disable-line
}
}
export function getCookie(name) {
const reg = new RegExp(`(^|)${name}=([^;]*)(;|$)`);
const arr = document.cookie.match(reg); // eslint-disable-line
if (arr) {
return decodeURIComponent(arr[2]);
} else {
return null;
}
}
export function delCookie(name, { domain, path } = {}) {
if (getCookie(name)) {
const domainSet = domain ? ` domain=${domain};` : '';
const pathSet = path ? ` path=${path};` : '';
document.cookie = `${name}=; expires=Thu, 01-Jan-70 00:00:01 GMT;${pathSet}${domainSet}`; // eslint-disable-line
}
}
export function setLocalStorge(key, value) {
return localStorage.setItem(key, JSON.stringify(value)); // eslint-disable-line
}
export function getLocalStorge(key) {
return JSON.parse(localStorage.getItem(key)); // eslint-disable-line
}
export function delLocalStorge(key) {
return localStorage.removeItem(key); // eslint-disable-line
}
export function locationOrigin(withContext = true) {
return `${location.protocol}//${location.hostname}${location.port ? ':' + location.port : ''}${withContext ? contextPath : ''}`; // eslint-disable-line
}
export function currentPath() {
let path = location.pathname; // eslint-disable-line
if (!path) {
path = '/';
}
if (path[0] !== '/') {
path = `/${path}`;
}
if (path.slice(0, contextPath.length) === contextPath) {
return path.slice(contextPath.length);
} else {
return '/';
}
}
export function fullPath(path) {
return `${contextPath}${path}`;
}
export function encrypt(text) {
const jsEncrypt = createJSEncrypt();
jsEncrypt.setPublicKey(pubKey);
let out = jsEncrypt.encryptLong(text);
out = out.split('=')[0];
out = out.replace(/\+/g, '-');
return out.replace(/\//g, '_');
}
/**
* @param name {String}
* @return {String}
*/
export function queryURL(name) {
const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`, 'i');
// eslint-disable-next-line no-undef
const r = window ? window.location.search.substr(1).match(reg) : null;
if (r !== null) return decodeURI(r[2]);
return null;
}
export function padDigits(number, digits) {
return new Array(Math.max(digits - String(number).length + 1, 0)).join('0') + number;
}
export function is(obj, type) {
return (type === 'Null' && obj === null) ||
(type === 'Undefined' && obj === void 0) || // eslint-disable-line no-void
(type === 'Number' && isFinite(obj)) ||
Object.prototype.toString.call(obj).slice(8, -1) === type;
}
export function makePromise0(thunk) {
return new Promise((resolve) => {
thunk(data => resolve(data));
});
}
export function makePromise1(thunk) {
return new Promise((resolve, reject) => {
thunk(err => reject(err), data => resolve(data));
});
}
export function filterValidParams(params) {
return _.pickBy(params, _.negate(_.isUndefined));
}
import _ from 'lodash';
import { Resolver } from 'fastjson_ref_resolver';
export function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response;
}
return response.json().then((data) => {
const error = new Error(data.message ? data.message : response.statusText);
error.data = data;
throw error;
});
}
export function normParams(unnormed) {
if (_.isPlainObject(unnormed)) {
return _(unnormed).toPairs().flatMap(([k, v]) => (_.isArray(v) ? v.map(vv => [k, vv]) : [[k, v]])).value();
} else {
return unnormed;
}
}
// eslint-disable-next-line max-len
export function parseObject(response, {
num2str = false, bool2str = false, nul2str = false, ud2str = false, nil2str = false,
} = {}) {
if (response.status === 204) { // no-content
return null;
} else {
const contentType = response.headers.get('content-type');
if (contentType) {
const needMap = num2str || bool2str || nul2str || ud2str || nil2str;
const mapStr = (value) => {
if (num2str && _.isNumber(value)) {
return value.toString();
}
if (bool2str && _.isBoolean(value)) {
return value.toString();
}
if (nul2str && _.isNull(value)) {
return '';
}
if (ud2str && _.isUndefined(value)) {
return '';
}
if (nil2str && _.isNil(value)) {
return '';
}
return value;
};
const mapObj = (obj, mapArrFunc) => {
if (_.isArray(obj)) {
return mapArrFunc(obj, mapObj);
}
if (_.isPlainObject(obj)) {
return _.mapValues(obj, (val) => {
const ret = mapStr(val);
return mapObj(ret, mapArrFunc);
});
}
return obj;
};
const mapArr = (arr, mapObjFunc) => {
if (_.isPlainObject(arr)) {
return mapObjFunc(arr, mapArr);
}
if (_.isArray(arr)) {
return _.map(arr, (val) => {
const ret = mapStr(val);
return mapArr(ret, mapObjFunc);
});
}
return arr;
};
const mapValue = _.curry(mapObj)(_, mapArr);
if (contentType.indexOf('json') !== -1) {
return response.json()
.then((json) => {
if (json.errorCode === 0) {
let { data } = json;
if (_.isObjectLike(data)) {
data = new Resolver(json.data).resolve();
}
return needMap ? mapValue(data) : data;
} else {
throw new Error(json.message);
}
});
} else if (contentType.indexOf('xml') !== -1) {
return response.text().then((text) => {
return require.ensure([], (require) => {
const { parseString } = require('xml2js');
const options = {};
const json = JSON.parse(parseString(text, options));
return needMap ? mapValue(json) : json;
});
});
} else if (contentType.indexOf('text') !== -1) {
return response.text();
} else {
throw new Error(`Unsupported response content type: ${contentType}`);
}
} else {
throw new Error('No response content type.');
}
}
}
This source diff could not be displayed because it is too large. You can view the blob instead.
差异被折叠。
差异被折叠。
差异被折叠。
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论