Commit 09b3eebd authored by rockyl's avatar rockyl

增加共用网络接口组件

parent efdac5b1
/**
* Created by rockyl on 2018-12-16.
*
* Api接口组件基类
*/
import {ScillaComponent, ScillaEvent} from "scilla";
export default class ApiComponent extends ScillaComponent {
onResponse: ScillaEvent = new ScillaEvent();
onError: ScillaEvent = new ScillaEvent();
onFinish: ScillaEvent = new ScillaEvent();
autoCall: boolean = false;
private _args;
onAwake() {
super.onAwake();
if(this.autoCall){
this.execute();
}
}
protected async execute(paramsInput?, ...args) {
this._args = args;
}
onGotResponse(response: any) {
if(this._args && this._args.length > 0){
this.onResponse.invoke(response, ...this._args);
}else{
this.onResponse.invoke(response);
}
this.onCallFinish();
}
onGotError(e) {
if(this._args && this._args.length > 0){
this.onError.invoke(e, ...this._args);
}else{
this.onError.invoke(e);
}
this.onCallFinish();
}
onCallFinish(){
if(this._args && this._args.length > 0){
this.onFinish.invoke(...this._args);
}else{
this.onFinish.invoke();
}
}
}
/**
* Created by hwj on 2018/12/1.
*
* 简单的api组件
*/
import {utils} from 'scilla'
import ApiComponent from "./ApiComponent";
import {callApi} from "./webService";
export default class SampleApi extends ApiComponent {
name: string;
uri: string;
method: string = 'POST';
params: any;
ignoreSuccessField: boolean = false;
async callApi(name, paramsInput, ...args){
if(this.name == name){
await this.execute(paramsInput, ...args);
}
}
protected async execute(paramsInput?, ...args) {
await super.execute(paramsInput, ...args);
const params = {
};
if(this.params){
utils.injectProp(params, this.params);
}
if(paramsInput){
utils.injectProp(params, paramsInput);
}
const {uri, method} = this;
try {
const response = await callApi(uri, params, method, 'json', this.ignoreSuccessField);
this.onGotResponse(response);
return response.data;
} catch (e) {
this.onGotError(e);
}
}
}
/**
* Created by hwj on 2018/12/1.
*
* 简单的api组件
*/
import {utils} from 'scilla'
import ApiComponent from "./ApiComponent";
import {callApi, polling} from "./webService";
export default class SamplePollingApi extends ApiComponent {
name: string;
successField: string;
successValues: any[];
uri: string;
method: string = 'GET';
params: any;
maxTimes: number = 5;
delay: number = 500;
async callApi(name, paramsInput, ...args) {
if (this.name == name) {
await this.execute(paramsInput, ...args);
}
}
protected async execute(paramsInput?, ...args) {
await super.execute(paramsInput, ...args);
const params = {
};
if (this.params) {
utils.injectProp(params, this.params);
}
if (paramsInput) {
utils.injectProp(params, paramsInput);
}
const {uri, method} = this;
try {
const response = await polling(this.successFunc, uri, params, this.maxTimes, this.delay, method);
this.onGotResponse(response);
return response.data;
} catch (e) {
this.onGotError(e);
}
}
successFunc=(response)=> {
const {successField, successValues} = this;
let v = successField ? response.data[successField] : response.data;
return successValues.indexOf(v) >= 0;
}
}
/**
* Created by hwj on 2018/11/22.
* 网络组件
*/
import {utils} from "scilla";
/**
* 调用接口
* @param uri
* @param params
* @param method
* @param responseType
* @param ignoreSuccessField
*/
export function callApi(uri: string, params: any = null, method: string = 'post', responseType = 'json', ignoreSuccessField = false): Promise<any> {
let ts = Date.now() + Math.floor(Math.random() * 9999999);
let url = uri.indexOf('//') === 0 ? uri : `${uri}?_=${ts}`;
params = params || {};
let options: any = {
method,
};
//if (!GameConfig.debug) {
options.credentials = 'include';
//}
let temp = typeof params === 'string' ? params : utils.objectStringify(params);
switch (method.toUpperCase()) {
case 'GET':
if(temp && temp.length > 0){
url += (url.indexOf('?') < 0 ? '?' : '') + '&' + temp;
}
break;
case 'POST':
options.body = temp;
options.headers = {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
};
break;
}
const fetchMethod = responseType == 'jsonp' ? window['fetchJsonp'] : fetch;
return fetchMethod(url, options)
.then((response) => {
if (response.type === 'opaque') {
return null;
}
return response.text();
})
.then((response) => {
//console.log('fetch ==>', url, response);
if (response) {
let data;
switch (responseType) {
case 'json':
try {
/*console.log('debug', GameConfig.debug);
console.log(url, options);
console.log(response);*/
data = JSON.parse(response);
} catch (e) {
console.log('decode json failed: ' + url);
return Promise.reject({});
}
if (ignoreSuccessField || data.success) {
return {
data: data.hasOwnProperty('data') ? data.data : data,
origin: data,
};
} else {
return Promise.reject(data.code);
}
case 'html':
let html = null;//DOMParser.parseFromString(response, 'text/html');
return html;
case 'txt':
return response;
}
}
return Promise.reject();
})
}
/**
* 轮训请求
* @param successFunc
* @param maxTimes
* @param delay
* @param uri
* @param params
* @param method
* @param responseType
*/
export function polling(successFunc, uri, params, maxTimes = 10, delay = 500, method = 'POST', responseType = 'json'): Promise<any> {
let p = Promise.resolve();
for (let i = 0; i < maxTimes; i++) {
p = p.then(func);
p = p.then(() => {
return utils.waitPromise(delay)
})
}
let lastData;
return p.then(
() => {
return Promise.reject(null);
},
(e) => {
if (e === 'success') {
return Promise.resolve(lastData);
}
return Promise.reject(e);
}
);
function func() {
return callApi(uri, params, method, responseType).then(
(data) => {
if (successFunc(data)) {
lastData = data;
return Promise.reject('success');
}
},
(e) => {
return Promise.reject(e);
}
)
}
}
/**
* 获取token并发送
* @param uri
* @param params
* @param method
* @param responseType
*/
export async function getToken(uri: string, params: any, method: string = 'POST', responseType: string = 'json') {
if (window['getDuibaToken']) {
window['getDuibaToken'](async (tokenObj: any) => {
params.token = tokenObj.token;
await this.send(uri, params, method, responseType);
}, () => {
});
} else {
await this.send(uri, params, method, responseType);
}
}
// /**
// * 通讯底层错误
// */
// protected onError(key,msgObj): void {
// const msg = `${key}:${msgObj}`
// this.dispatchEvent('Error', msg );
// }
/**
* 生成签名
* @param {number} ticketId
* @param {number} score
* @param {any} gameData
* @param {string} submitToken 提交
* @returns {string} 签名
*/
export function createSgin(ticketId: number, score: number, gameData: any, submitToken: string): string {
return window['duiba_md5'](ticketId + '' + score + '' + gameData + '' + submitToken);
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment