接口定义
var UNDEFINED = 'undefined';
var FUNCTION = 'function';
var NUMBER = 'number';
var GLOBAL = 'global';
var ARGUMENTS = 'arguments';
var DATE = 'date';
var ERROR = 'error';
var NULL = 'null';
var OBJECT = 'object';
var STRING = 'string';
var ARRAY = 'array';
var REGEXP = 'regexp';
var BOOLEAN = 'boolean';
module.exports = {
//获取当前用户信息
getUserInfo: {
url: 'api/user/getUserInfo',
method: 'get',
params: {
withFavs: {
type: BOOLEAN,
required: false
},
useCache: {
type: BOOLEAN,
default:false,
required: false
}
}
},
//获取推荐列表
recomThreads: {
url: 'api/recommendList',
method: 'post',
params: {
recordTime: {
type: STRING,
required: true
},
cityName: {
type: STRING,
required: true
},
page: {
type: NUMBER,
default: 1,
required: false
},
perPage: {
type: NUMBER,
default: 50,
required: false
}
},
showLoading: true
},
}
接口实现
/*
* init.js 接口文件
* 接口请求promise实现
* 通过API['接口名称']['请求方法']调用接口 如API.publishContent.get(data).then(success, error)
* 接口配置统一放置 ./index.js
* 通过var API = require('./index.js') 获取API对象
*
*/
module.exports = function() {
Object.keys(config).forEach((key) => {
let item = config[key];
const method = item.method;
item[method] = (data, showLoading) => {
if (item.params) {
//参数校验
let params = item.params;
Object.keys(params).forEach((key) => {
const item2 = params[key];
if (item2.required) {
let value = data[key] === false ? false : (data[key] || item2.default);
if (value !== false && !value) {
console.error(item.url + ' -' + key + ' :is required');
} else {
if (typies(value) !== item2.type) {
console.error(item.url + ' -' + key + ' :type must be ' + item2.type);
}
}
} else {
if (data[key] === false || data[key]) {
if (typies(data[key]) !== item2.type) {
console.error(item.url + ' -' + key + ' :type must be ' + item2.type);
}
}
}
})
}
return asyncCreateFactory(item.url, method.toUpperCase(), data || {}, showLoading === false ? false : (item.showLoading || showLoading))
}
})
}
//返回 promise
function asyncCreateFactory(url, method, data, showLoading) {
if (showLoading) {
wx.showLoading({
title: '加载中'
})
}
return new Promise(function(resolve, reject) {
request({
method: method,
path: url,
data: data,
success: function(res) {
resolve(res.data);
if (showLoading) {
wx.hideLoading()
}
},
fail: function(error) {
reject(error);
if (showLoading) {
wx.hideLoading()
}
}
})
})
}
接口使用
//只要调用一次
var initApi = require('./init.js');
initApi();
//使用的地方调用
var API = require('./index.js')
API.getUserInfo.get({
withFavs:true,
useCache:false
}).then(function(data) {
console.log("此处已经拿到用户信息,可以做其他处理:"+da ta)
})