智能照明系统APP-本地串口
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 
LightingSystemApp-serial/.svn/pristine/31/31cea8436553a46f55ace9a1293...

125 lines
2.2 KiB

import {
isPlainObject
} from 'uni-shared'
import {
invoke
} from 'uni-core/service/bridge'
import {
onMethod,
invokeMethod
} from '../../platform'
const requestTasks = Object.create(null)
function formatResponse (res, args) {
if (
typeof res.data === 'string' &&
res.data.charCodeAt(0) === 65279
) {
res.data = res.data.substr(1)
}
res.statusCode = parseInt(res.statusCode, 10)
if (isPlainObject(res.header)) {
res.header = Object.keys(res.header).reduce(function (ret, key) {
const value = res.header[key]
if (Array.isArray(value)) {
ret[key] = value.join(',')
} else if (typeof value === 'string') {
ret[key] = value
}
return ret
}, {})
}
if (args.dataType && args.dataType.toLowerCase() === 'json') {
try {
res.data = JSON.parse(res.data)
} catch (e) {}
}
return res
}
onMethod('onRequestTaskStateChange', function ({
requestTaskId,
state,
data,
statusCode,
header,
errMsg,
cookies
}) {
const {
args,
callbackId
} = requestTasks[requestTaskId] || {}
if (!callbackId) {
return
}
delete requestTasks[requestTaskId]
switch (state) {
case 'success':
invoke(callbackId, formatResponse({
data,
statusCode,
header,
errMsg: 'request:ok',
cookies
}, args))
break
case 'fail':
invoke(callbackId, {
errMsg: 'request:fail ' + errMsg
})
break
}
})
class RequestTask {
constructor (id) {
this.id = id
}
abort () {
invokeMethod('operateRequestTask', {
requestTaskId: this.id,
operationType: 'abort'
})
}
offHeadersReceived () {
}
onHeadersReceived () {
}
}
export function request (args, callbackId) {
let contentType
for (const name in args.header) {
if (name.toLowerCase() === 'content-type') {
contentType = args.header[name]
break
}
}
if (args.method !== 'GET' && contentType.indexOf('application/json') === 0 && isPlainObject(args.data)) {
args.data = JSON.stringify(args.data)
}
const {
requestTaskId
} = invokeMethod('createRequestTask', args)
requestTasks[requestTaskId] = {
args,
callbackId
}
return new RequestTask(requestTaskId)
}