request.js 1.6 KB
//const baseUrl = 'https://app.ydniu.com/graphql'
//const baseUrl = '/test_graphql'
const baseUrl = '/graphql'


function request(options = {}) {
	let header = Object.assign({
		"Accept": "application/json"
	}, options.header)

	return new Promise((resolve, reject) => {
		uni.request({
			url: baseUrl + (options.url || ''),
			method: options.type || 'GET',
			data: options.data || {},
			header
		}).then(data => {
			let [err, res] = data;
			res && res.data
			resolve(res);
		}).catch(error => {
			reject(error)
		})
	});
}

function get(options = {}) {
	options.type = 'GET';
	return request(options)
}

function post(options = {}) {
	options.type = 'POST';
	return request(options)
}

async function graphql(options = {}) {

	let header = {}
	try {
		if (Android) {
			header["ydn-cookie"] = JSON.parse(Android.getSystemInfo())['cookie']
		}
	} catch (e) {
		console.log(e.message)
	}

	let opts = Object.assign({
		type: 'query'
	}, options)

	let body = []
	body.push(`${opts.type}{${opts.name}`)
	if (opts.args) body.push(`(${opts.args})`)
	if (opts.body) body.push(`{${opts.body}}`)
	body.push('}')

	let res = await post({
		header,
		data: {
			query: body.join('')
		}
	})

	res = res.data.data[opts.name]

	if (res.Error == '未登录') {
		try {
			if (Android) window.location.href = 'ydncp://www.ydniu.com?type=7'
		} catch (e) {
			console.log(e.message)
			uni.navigateTo({
				url: `/login?from=${encodeURIComponent(getCurrentPages()[0].__page__.fullPath)}`
			})
		}
		return
	}

	return res
}

uni.$u.request = {
	request,
	get,
	post,
	graphql
}