// for CMD declare var require: any; declare var module: any; interface API { name: string, url: string }; var HTTP = require('./http'); interface config { config?: any, rules?: Array, formatter?: any }; class Service { apis: Array; rules: Array; headers: any; withCredentials: boolean; timeout: number; constructor(config) { // Note: // != is enough to seperate `undefined` & `null` // from other objects if (config != null) { for (var prop in config) { if (prop === 'config') { var ajaxConfig = config.config; for (var i in ajaxConfig) { if (ajaxConfig.hasOwnProperty(i)) { this[i] = ajaxConfig[i]; } } continue; } if (config.hasOwnProperty(prop)) this[prop] = config[prop]; } } this.rules = this.rules || []; // default rule function defaultRule(xhr, resolve, reject) { if (!/^[1-3]/.test(xhr.status)) { reject('HTTP Response code: ' + xhr.status); } else { resolve(xhr.responseText); } } this.rules.push(defaultRule); } config(apis: Array) { var self = this; apis.forEach(function(api) { var params = {}; // 将配置中的 :xx 占位符配置到 params 中 api.url.replace(/:(\w+)\/?/g, function(raw, name) { return params[name] = undefined; }); self[api.name] = new HTTP({ url: api.url, params: params, $service: self }); }); } set(name: string, value: any) { this[name] = value; return this; } }; module.exports = Service;