apiClound 内部未使用 Vue-cil ,所以封装了写方法
Vue && api.js 封装的一些方法
(function(target, factory) {
target.ApiRender = factory();
}(this, function() {
const config = {
serverURL: 'http://bjbapi.wntree.com',
userSessionKey: 'USER_SESSION',
userTokenKey: 'USER_TOKEN'
}
function paramToURL(params) {
if (!params) {
return '';
}
const keys = Object.keys(params);
const end = keys.reduce((end, key) => {
const val = params[key];
if (val !== null && val !== undefined && val !== '') {
return `${end}${encodeURIComponent(key)}=${encodeURIComponent(val)}&`;
}
return end;
}, '');
return end.substring(0, end.length - 1);
}
function floatToPrice(f) {
if (f === null || f === undefined || f === '') {
return '0.00';
}
f = f + '';
var idx = f.indexOf('.');
if (idx === -1) {
return f + '.00';
}
var pat = f.split('.');
if (pat[1].length < 2) {
return pat[0] + '.' + pat[1] + "0".repeat(2 - pat[1].length);
}
return pat[0] + '.' + pat[1].substring(0, 2);
}
function formatDate(date) {
function addZero(num) {
return num > 9 ? num : '0' + num;
}
const d = new Date(date)
if (Number.isNaN(d.getDay())) {
return ''
}
var format = d.getFullYear() + '-'
return (format + addZero(d.getMonth() + 1) + '-' +
addZero(d.getDate()) + ' ' +
addZero(d.getHours()) + ':' +
addZero(d.getMinutes()) + ':' +
addZero(d.getSeconds()));
}
function formatDateYMD(date) {
var datestr = formatDate(date)
return datestr.substring(0, datestr.indexOf(' '));
}
function formatDateHMS(date) {
var datestr = formatDate(date)
return datestr.substring(datestr.indexOf(' '));
}
function getSearch(key) {
var search = window.location.search
search = search.substring(1)
var params = search.split('&')
for (var i = 0; i < params.length; i++) {
var param = params[i].split('=')
if (param[0] === key) {
return param[1];
}
}
return null;
}
function isEmpty(data) {
return data === undefined || data === null || data === '' ||
(Array.isArray(data) && data.length === 0) ||
(typeof data === 'object' && Object.keys(data).length === 0);
}
function PageHelper(pageIndex, pageSize, render) {
this.pageIndex = pageIndex;
this.pageSize = pageSize;
this.next = (callback) => {
render(this.pageIndex++, this.pageSize++)
}
}
function browserRequest(method, url, params, callback) {
try {
url = config.serverURL + url;
if (method === 'GET' && params) {
const urlParams = utils.paramToURL(params);
url = !urlParams ? url : (url + '?' + urlParams);
}
const xhr = new XMLHttpRequest()
xhr.open(method, url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Authorization", getStorage(config.userTokenKey) || "D6E7B697C4194FA9B9132B8C81406C54");
xhr.onload = function() {
console.log(JSON.stringify(xhr))
if (xhr.readyState === 4) {
callback(JSON.parse(xhr.responseText));
}
}
if (method === 'POST') {
return xhr.send(utils.paramToURL(params));
}
xhr.send();
}catch(err) {
callback(null, err)
}
}
function apiRequest(method, url, params, callback) {
url = config.serverURL + url;
if (method.toUpperCase() === 'GET' && params && Object.keys(params).length > 0) {
const urlParams = utils.paramToURL(params);
url = !urlParams ? url : (url + '?' + urlParams);
}
const options = {
url,
method: method.toLocaleLowerCase(),
dataType: 'json',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: getStorage(config.userTokenKey) || "1FFD9EC4DF704E189CEA05A97F9C2918",
},
}
if (method.toUpperCase() === 'POST'&& params && Object.keys(params).length > 0) {
options.data = {
values: params,
}
}
api.ajax(options, function(ret, err) {
if (ret.code !== 0) {
return callback(ret, ret);
}
callback(ret, err);
})
}
function get(url, params, callback) {
return apiRequest('GET', url, params, callback);
}
function post(url, params, callback) {
return apiRequest('POST', url, params, callback);
}
function setStorage(key, value) {
$api.setStorage(key, value);
}
function getStorage(key) {
return $api.getStorage(key);
}
function removeStorage(key) {
$api.rmStorage(key);
}
function existStorage(key) {
const val = getStorage(key)
return val !== undefined && val !== null && val !== '';
}
function clearStorage() {
$api.clearStorage();
}
function openWin(pageName, pagePath, parameterStr) {
api.openWin({
name: pageName,
url: pagePath,
pageParam: parameterStr,
reload: true,
slidBackEnabled: false,
allowEdit: false,
hScrollBarEnabled: false,
vScrollBarEnabled: false,
delay: 300
});
}
function closeWin(pageName) {
api.closeWin({
name: pageName ? api.frameName : pageName,
animation: {
type: 'reveal',
subType: 'from_left',
duration: 500
}
});
}
function showProgress(title, msg) {
api.showProgress({
style: 'default',
animationType: 'zoom',
title: title,
text: msg,
modal: true
});
}
function hideProgress() {
api.hideProgress();
}
function showAlert(msg, callback) {
api.alert({
title: "提示",
msg: msg
}, function (ret, err) {
try {
if (callback) {
callback(ret, err);
}
} catch (e) {
}
});
}
function showTitleAlert(title, msg, callback) {
api.alert({
title: title,
msg: msg
}, function (ret, err) {
try {
if (callback) {
callback(ret, err);
}
} catch (e) {
}
});
}
function checkNetwork(tips) {
var connectionType = api.connectionType;
var flat = false;
if (connectionType == "none") {
hideProgress();
if (tips) {
api.toast({
msg: '无法连接网络,请检查你的网络!'
});
}
} else {
flat = true;
}
return flat;
}
function getGpsLocation(callback) {
try {
const aMapLBS = api.require('aMapLBS');
aMapLBS.configManager({
accuracy: 'hundredMeters',
filter: 1
}, function(ret, err) {
if (err) { return callback(null, err); }
if (!ret.status) { return callback(null, ret); }
aMapLBS.stopUpdatingLocation();
aMapLBS.singleLocation({
timeout: 10
}, function(ret, err) {
if (err) { return callback(null, err); }
if (!ret.status) { return callback(null, ret); }
callback({lat: ret.lat, lon: ret.lon})
});
});
}catch(err){
callback(null, err);
}
}
function bindRefreshHeader(callback) {
api.setCustomRefreshHeaderInfo({
bgColor: '#FFF',
images:['widget://image/Frame12.png',
'widget://image/Frame13.png'],
tips: {
pull: '下拉刷新',
threshold: '松开立即刷新',
load: '正在刷新'
},
}, function() {
callback();
});
}
function refreshHeaderDone() {
api.refreshHeaderLoadDone();
}
function showToast(msg, duration = 2000, location = 'bottom') {
api.toast({ msg, duration, location });
}
function fsReadSync(path) {
const fs = api.require('fs');
const open = fs.openSync({path: path, flags: 'read'});
if (!open.status) {
return console.error('importVue 打开文件失败:' + JSON.stringify(open));
}
const read = fs.readSync({fd: open.fd});
if (!read.status) {
return console.error('importVie 读取文件失败:' + JSON.stringify(read));
}
return read.data;
}
function getTagContent(tag, content) {
let start = content.indexOf(`<${tag}>`);
if (start === -1){
return '';
}
start = start + tag.length + 2
const end = content.indexOf(`${tag}>`, start);
if (end === -1) {
return '';
}
return content.substring(start, end);
}
function importVue(path) {
let paths = [];
if (!Array.isArray(path)) {
if (typeof path !== 'string') {
return null;
}
paths.push(path);
} else {
paths = path;
}
const components = {};
paths.forEach(path => {
const content = fsReadSync(path);
const template = getTagContent('template', content);
const style = getTagContent('style', content);
const script = getTagContent('script', content).trim().replace('export default', '').trimLeft().replace(/;$/, '');
const component = eval('(' + script + ')');
if (style) {
const styleTag = document.createElement('style')
styleTag.innerHTML = style
document.getElementsByTagName('head')[0].appendChild(styleTag)
}
component.template = template;
components[component.name] = component;
})
return components;
}
const handles = {
config,
get,
post,
storage: {
setStorage,
getStorage,
removeStorage,
existStorage,
}
}
const utils = {
isEmpty,
paramToURL,
floatToPrice,
formatDate,
formatDateYMD,
getSearch,
PageHelper,
}
const apiHandles = {
openWin,
closeWin,
showProgress,
hideProgress,
showAlert,
showTitleAlert,
checkNetwork,
getGpsLocation,
bindRefreshHeader,
refreshHeaderDone,
showToast,
fsReadSync,
importVue,
}
function ApiRender(init) {
window.apiready = () => init(Object.assign(handles, utils, apiHandles));
}
return ApiRender;
}));