@zhiguang-gastrofy/capi
Version:
comany apis, including Northfork api and Gastrofy api
94 lines (77 loc) • 2.81 kB
text/typescript
import axios from 'axios';
const UA = window.navigator.userAgent;
const isIE11 = UA.indexOf('Trident/7') !== -1;
const isIE = UA.indexOf('MSIE') !== -1 || isIE11;
const isEdge = UA.indexOf('Edge/') !== -1;
const promise = new Promise( () => {} );
//const serverMap = {
// nf: 'https://api.northfork.se/api/',
// ga: 'https://www.gastrofy.se/api/',
//};
export class HttpService {
host: string;
customerToken: string;
memberToken: string;
constructor( options?:any ) {
this.config( options );
axios.defaults.headers.common['Content-Type'] = 'application/json';
if( isIE || isEdge ) {
axios.defaults.headers.common['Cache-Control'] = 'no-cache';
axios.defaults.headers.common['Pragma'] = 'no-cache';
axios.defaults.headers.common['Expires'] = 'Sat, 01 Jan 2000 00:00:00 GMT';
}
this.initMethods();
}
config( config:any ) {
if( !config ) return;
for( let attr of [ 'host', 'customerToken', 'memberToken' ] ) {
if( config[ attr ] ) this[attr] = config[attr];
}
}
// It is possible to use config.xxxToken to overwrite temperary
private parseConfig( config:any ) {
config = {...config||{}}
config.headers = {...config.headers||{}};
let customerToken = this.customerToken;
if( config.customerToken ) {
customerToken = config.customerToken;
delete config.customerToken;
}
let memberToken = this.memberToken;
if( config.memberToken ) {
memberToken = config.memberToken;
delete config.memberToken;
}
if( customerToken ) config.headers['X-Custom-Auth'] = customerToken;
if( memberToken ) config.headers['token'] = memberToken;
return config;
}
private initMethods() {
for( let action of [ 'get', 'post', 'delete', 'put', 'patch' ] ) {
this[ action ] = function() {
let args = [].slice.call( arguments );
let config:any = args.splice( ['post','put','patch'].indexOf( action ) === -1?1:2, 1 )[0];
config = this.parseConfig( config );
let host = this.host;
if( config.host ) {
host = config.host;
delete config.host;
}
if( host ) {
host = host.replace( /\/+$/, '' );
args[0] = args[0].replace( /^\/+/, '' );
args[0] = host +'/'+ args[0];
}
args.push( config );
return axios[action].apply( this, args ).then( ( res:any ) => {
return res.data;
} );
}
}
}
get( apiPath:string, config?:any ) { return promise; }
delete( apiPath:string, config?:any ) { return promise; }
post( apiPath:string, data?:any, config?:any ) { return promise; }
put( apiPath:string, data?:any, config?:any ) { return promise; }
patch( apiPath:string, data?:any, config?:any ) { return promise; }
}