export default (config) => {
	if (config.baseUrl && !isAbsoluteURL(config.url)) {
		config.url = combineURLs(config.baseUrl, config.url);
	}

	return new Promise((resolve, reject) => {
		config = Object.assign(config, {
			success: res => {
				if (res.statusCode === 200) {
					resolve(res);
				} else {
					reject(res);
				}
			},
			fail: res => {
				reject(res);
			}
		});
		uni.request(config);
	});
}

const combineURLs = (baseUrl, relativeUrl) => {
	return relativeUrl ?
		baseUrl.replace(/\/+$/, '') + '/' + relativeUrl.replace(/^\/+/, '') :
		baseUrl;
}

const isAbsoluteURL = (url) => {
	return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
};
