本文整理汇总了TypeScript中request-promise.default方法的典型用法代码示例。如果您正苦于以下问题:TypeScript request-promise.default方法的具体用法?TypeScript request-promise.default怎么用?TypeScript request-promise.default使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类request-promise
的用法示例。
在下文中一共展示了request-promise.default方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: async
Coinbase: async () => {
const usd = await rp({ uri: 'https://api.coinbase.com/v2/prices/spot?currency=USD', json: true });
const aud = await rp({ uri: 'https://api.coinbase.com/v2/prices/spot?currency=AUD', json: true });
return {
usd: {
raw: parseFloat(usd.data.amount),
formatted: colors.green(`$${parseFloat(usd.data.amount).toFixed(2)}USD`)
},
aud: {
raw: parseFloat(aud.data.amount),
formatted: colors.blue(`$${parseFloat(aud.data.amount).toFixed(2)}AUD`)
}
};
},
示例2: getNewsList
public async getNewsList(searchKeyword: string, page: number): Promise<[any]> {
const newsData: any = [];
const queryURL = `http://search.naver.com/search.naver`;
try {
await delay(5000);
const response = await request({
uri: queryURL,
qs: {
where: 'news',
query: searchKeyword,
nso: 'so:r,p:1d,a:all',
start: page,
},
headers: commonHeaders,
});
const $ = cheerio.load(response);
for (const elem of $('.type01 a')) {
const $elem = $(elem);
if ($elem.text().indexOf('네이버뉴스') === 0) {
newsData.push(await this.getNewsContent($elem.attr('href')));
}
}
} catch (err) {
console.error(err);
}
return newsData;
}
示例3: getTasks
/**
* Description of the method.
* @method
* @private
*/
private getTasks(date: any): Promise<any> {
const options = {
"method": "GET",
"uri": `${this.apiUri}/tasks`,
"qs": {
"access_token": this.apiToken,
"project_id": this.apiProjectId,
"page_size": 20
},
"json": this.apiJson
};
let tasksForDate = [];
return rp(options)
.then(tasks => {
tasks.data.forEach(task => {
if (task.custom_fields[this.taskDay].indexOf(date.format("dddd")) !== -1 ||
task.custom_fields[this.taskMonth].indexOf(date.format("MMMM")) !== -1 &&
task.custom_fields[this.taskDate] === date.format("D")) {
tasksForDate.push(task);
}
});
this.handleSuccess(`Processing ${tasksForDate.length}/${tasks.data.length} tasks`);
return tasksForDate;
})
.catch(err => this.handleError(err));
}
示例4: getAll
public async getAll(): Promise<ITodo[]> {
console.log(`[GET] /api/todos`);
return await rp({
uri: `${this.url}/api/todos`,
json: true
});
}
示例5: getNewsContent
public async getNewsContent(newsURL: string): Promise<NewsContent> {
try {
await delay(5000);
const response = await request({
uri: newsURL,
headers: commonHeaders,
encoding: null,
});
let $ = cheerio.load(response);
$('script').remove();
const encodedResponse = iconv.decode(response, $('meta[charset]').attr('charset')).toString();
$ = cheerio.load(encodedResponse);
const newsTitle = $('meta[property=\'og:title\']').attr('content');
const newsContent = $('#articeBody, #newsEndContents, #articleBodyContents');
return {
title: newsTitle,
content: newsContent.html(),
plain_text: newsContent.text(),
press: $('.press_logo img, #pressLogo img').attr('alt'),
link: newsURL,
};
} catch (err) {
logger.error(err);
}
}
示例6: getUrlInfo
export async function getUrlInfo(url: string) {
if(!url.includes('http://') && !url.includes('https://')) {
url = `http://${url}`;
}
const html = await request(url);
const $ = cheerio.load(html);
let htmlInfo: any = {
'og:title':null,
'og:description':null,
'og:image':null
};
const meta = $('meta');
const keys = Object.keys(meta);
for (let s in htmlInfo) {
keys.forEach(function(key) {
if ( meta[key].attribs
&& meta[key].attribs.property
&& meta[key].attribs.property === s) {
htmlInfo[s] = meta[key].attribs.content;
}
})
}
htmlInfo.title = $('title').html();
return htmlInfo;
}
示例7: log
export function request<U>(baseOpts: requestPromise.RequestPromiseOptions & { dryRun?: boolean }, path: string, extra: requestPromise.RequestPromiseOptions = {}) {
let opts = {
...baseOpts,
...extra,
headers: {
...(baseOpts.headers || {}),
...(extra || {}).headers
}
};
if (opts.qs) {
let qs = opts.qs;
delete opts.qs;
path += '?' + Object.keys(qs).map(x => `${encode(x)}=${encode(qs[x])}`).join('&')
}
const method = ('' + (opts.method || 'GET')).toUpperCase()
const suppress = !!opts.dryRun && method !== 'GET';
log(`${suppress ? '[SKIPPED] ' : ''}${method} ${baseOpts.baseUrl}${path}`, opts);
if (suppress) {
return Promise.resolve({});
} else {
return (requestPromise(path, opts) as any as Promise<U>);
}
}
示例8: _getUserInfoFromHeaderCookie
private static _getUserInfoFromHeaderCookie(headerCookie: string, accountName: string): Promise<TpUserInfo> {
logger.debug('Enter getUserInfo');
if (!headerCookie || !headerCookie.length) {
return Promise.resolve(null);
}
const options = {
qs: {
include: '[id, firstName, lastName]',
format: 'json'
},
json: true,
headers: {
'Cookie': headerCookie
}
};
const accountUrl = AccountInfo.buildAccountUrl(AccountInfo.getAccountResolverFromConfig(), accountName);
return rp(`${accountUrl}/api/v1/Users/LoggedUser`, options)
.then(response => {
logger.debug('Got auth response from TP');
return {
id: response.Id,
firstName: response.FirstName,
lastName: response.LastName,
accountName,
accountUrl,
cookie: headerCookie
};
});
}
示例9: request
public request(query: string, cb?: cb) {
if (!query || typeof query !== "string") {
throw new Error(
"You must pass in a Spotify API endpoint to use this method."
);
}
let request;
const opts: searchOpts = { method: "GET", uri: query, json: true };
if (
!this.token ||
!this.token.expires_in ||
!this.token.expires_at ||
!this.token.access_token ||
this.isTokenExpired()
) {
request = this.setToken().then(() => {
opts.headers = this.getTokenHeader();
return rp(opts);
});
} else {
opts.headers = this.getTokenHeader();
request = rp(opts);
}
if (cb) {
request
.then((response: any) => cb(null, response))
.catch((err: Error) => cb(err, null));
} else {
return request;
}
}
示例10: postTask
/**
* Description of the method.
* @method
* @param {object} task Description of the method argument.
* @private
*/
private postTask(task: any): Promise<any> {
const options = {
"method": "POST",
"uri": `${this.apiUri}/incidents`,
"qs": {
"access_token": this.apiToken,
},
"body": {
"item": {
"name": task.name,
"description": task.description,
"assigned_to": {
"type": task.assigned_to.type,
"id": task.assigned_to.id,
},
"project": {
"id": task.project.id,
}
},
},
"json": this.apiJson
};
return rp(options)
.then(res => {
this.handleSuccess(`- ${res.data.name}`);
return res;
})
.catch(err => this.handleError(err));
}