'use strict'; /** * @file requestInfo * @author baiduAip */ const HttpHeader = require('../const/httpHeader'); const CloudAuth = require('../auth/cloudAuth'); const HOST_DEFAULT = 'aip.baidubce.com'; const CONTENT_TYPE_FORMDEFAULT = 'application/x-www-form-urlencoded'; const SYMBOL_QUERYSTRING_PREFIX = '&aipSdk=node&access_token='; const SYMBOL_QUERYSTRING_PREFIX_BCE = '?aipSdk=node'; const SYMBOL_HTTPS_PREFIX = 'https://'; const SYMBOL_HTTP_PREFIX = 'http://'; /** * RequestInfo类 * 构造供request库调用的请求信息对象 * * @constructor */ class RequestInfo { constructor(path, scope, params, method, isHttp) { this.isHttp = isHttp || false; this.method = method; this.host = HOST_DEFAULT; this.path = path; this.scope = scope; this.params = params; this.createDate = new Date(); this.devAccessToken = null; this.initCommonHeader(); } initCommonHeader() { this.headers = {}; this.headers[HttpHeader.HOST] = this.host; this.headers[HttpHeader.CONTENT_TYPE] = CONTENT_TYPE_FORMDEFAULT; } setHost(host) { this.host = host; this.headers[HttpHeader.HOST] = this.host; } getAccessToken() { if (this.devAccessToken !== null) { return this.devAccessToken.token; } return null; } makeDevOptions(devAccessToken) { this.devAccessToken = devAccessToken; this.path += SYMBOL_QUERYSTRING_PREFIX + devAccessToken.token; } makeBceOptions(ak, sk) { let cloudAuth = new CloudAuth(ak, sk); this.headers[HttpHeader.BCE_DATE] = this.getUTCDateStr(); let signature = cloudAuth.getAuthorization(this.method, this.getTestPath(), {redirect_uri: this.path}, this.headers, this.createDate.getTime()); this.headers[HttpHeader.BCE_AUTHORIZATION] = signature; } getUTCDateStr() { let dateStrUTC = this.createDate.toISOString().replace(/\.\d+Z$/, 'Z'); return dateStrUTC; } getUrl() { if (this.isHttp) { return this.getHttpUrl(); } return this.getHttpsUrl(); } getHttpsUrl() { let path; if (this.getTestPath()) { path = this.getTestPath() + '?redirect_uri=' + this.path; } else { return SYMBOL_HTTPS_PREFIX + this.host + this.path + SYMBOL_QUERYSTRING_PREFIX_BCE; } return SYMBOL_HTTPS_PREFIX + this.host + path; } getPureUrl() { return this.getUrl().split('?')[0]; } getHttpUrl() { return SYMBOL_HTTP_PREFIX + this.host + this.path; } getTestPath() { let sp = this.path.split('/')[1]; if (sp === 'rest') { return '/rest/2.0/test/v1/test'; } if (sp === 'rpc') { return '/rpc/2.0/test/v1/test'; } } } module.exports = RequestInfo;