本文整理汇总了TypeScript中request-promise-native类的典型用法代码示例。如果您正苦于以下问题:TypeScript request-promise-native类的具体用法?TypeScript request-promise-native怎么用?TypeScript request-promise-native使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了request-promise-native类的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1:
import * as rp from 'request-promise-native';
rp('http://www.google.com')
.then(console.dir)
.catch(console.error);
var options: rp.Options = {
uri : 'http://posttestserver.com/post.php',
method : 'POST',
json: true,
body: { some: 'payload' }
};
rp(options)
.then(console.dir)
.catch(console.error);
rp('http://google.com').then(() => {});
// This works:
rp('http://google.com').then(console.dir);
rp('http://google.com').catch(console.error);
rp('http://google.com').then(console.dir, console.error);
rp({ uri: 'http://google.com', resolveWithFullResponse: true }).then((response) => {});
rp({ uri: 'http://google.com', simple: false }).catch((reason) => {});
//Defaults tests
(() => {
const githubUrl = 'https://github.com';
示例2:
import * as rpn from 'request-promise-native';
import * as errors from 'request-promise-native/errors';
import * as path from 'path';
rpn('http://www.google.com')
.then(console.dir)
.catch(console.error);
let options: rpn.Options = {
uri: 'http://posttestserver.com/post.php',
method: 'POST',
json: true,
body: { some: 'payload' }
};
const j = rpn.jar();
rpn(options)
.then(console.dir)
.catch(console.error);
rpn('http://google.com').then(() => { });
// This works:
rpn('http://google.com').then(console.dir);
rpn('http://google.com').catch(console.error);
rpn('http://google.com').then(console.dir, console.error);
rpn({ uri: 'http://google.com', resolveWithFullResponse: true }).then((response) => { });
rpn({ uri: 'http://google.com', simple: false }).catch((reason) => { });
示例3: startServer
test('Response data can be deduplicated with graphql-deduplicator', async t => {
const { uri, data: { book } } = await startServer(t)
const query = `
query {
books {
__typename
id
name
author {
__typename
id
name
lastName
}
}
}
`
const body = await request({
uri,
method: 'POST',
json: true,
body: { query },
}).promise()
const deduplicated = await request({
uri,
method: 'POST',
json: true,
body: { query },
headers: {
'X-GraphQL-Deduplicate': true
}
}).promise()
t.deepEqual(body, {
data: {
books: Array(5).fill(book)
}
})
t.deepEqual(deduplicated, {
data: {
books: [
book,
...Array(4).fill({
__typename: book.__typename,
id: book.id
})
]
}
})
t.deepEqual(body.data, inflate(deduplicated.data))
})
示例4: rpn
http.createServer((req, resp) => {
if (req.url === '/doodle.png') {
const x = rpn('http://mysite.com/doodle.png');
req.pipe(x);
x.pipe(resp);
}
});
示例5: request
/**
* @param {string} url
* @param {{}} form
* @param {Token?} token
*/
postForm<T = any>(
url: string,
form:
| FormData
| {
file: UploadFileStream;
path: string;
uploadToken: string | null;
} & Partial<UploadFileRequest>,
token?: Token | undefined,
): Promise<T> {
const header = this.authenticator.getHeader(token);
const options = {
method: 'POST',
url,
formData: form,
headers: header,
json: true,
};
return request(options).then(
response => {
if (response.statusCode < 200 || response.statusCode >= 300) {
return Promise.reject(response.body);
}
return response;
},
error => {
return Promise.reject(error);
},
);
}
示例6: resolve
public async resolve(value: any): Promise<IObject> {
if (value == null) {
throw new Error('resolvee is null (or undefined)');
}
if (typeof value !== 'string') {
return value;
}
if (this.history.has(value)) {
throw new Error('cannot resolve already resolved one');
}
this.history.add(value);
const object = await request({
url: value,
headers: {
Accept: 'application/activity+json, application/ld+json'
},
json: true
});
if (object === null || (
Array.isArray(object['@context']) ?
!object['@context'].includes('https://www.w3.org/ns/activitystreams') :
object['@context'] !== 'https://www.w3.org/ns/activitystreams'
)) {
log(`invalid response: ${value}`);
throw new Error('invalid response');
}
return object;
}
示例7: httpRequest
async function httpRequest(args: { path: string, method: string, body?: any, formData?: any, query?: any, json?: boolean }) {
const options: any = {
uri: `${Configuration.baseUrl}${args.path}`,
method: args.method,
resolveWithFullResponse: true
};
if (args.formData) {
options.formData = args.formData;
} else if (args.body) {
options.body = args.body;
} else if (args.query) {
options.qs = args.query;
}
if (args.json) {
options.json = true;
}
// console.log(options);
try {
return await request(options);
} finally {
// console.log(`request sent ${options.method} ${options.uri}`);
}
}
示例8:
return new Promise<null>((resolve, reject) => {
let params: any = {
timestamp: tsPost,
commentTimestamp: tsComment
};
let reqPath = path.join('/v1/server/posts', tsPost.toString(), 'comments', tsComment.toString());
let url = postAuthor + reqPath;
if(idtoken && sigtoken) {
params.idToken = idtoken;
let signature = utils.computeSignature('DELETE', url, params, sigtoken);
url += '?idToken=' + idtoken
url += '&signature=' + signature;
}
// We'll use HTTP only for localhost
if(url.indexOf('localhost') < 0 && !commons.settings.forceHttp) url = 'https://' + url;
else url = 'http://' + url
log.debug('Requesting DELETE', url);
request({
method: 'DELETE',
uri: url,
timeout: commons.settings.timeout
})
.then((response) => {
log.debug('Deleted a comment on', postAuthor.toString());
resolve(response);
}).catch(reject);
});
示例9: getSitemap
private async getSitemap() {
try {
if (helper.isUrl(this.url) && helper.isXml(this.url)) {
return await request(this.url);
}
} catch (error) {
console.error(`Error on Request Catch : ${error}`);
throw error;
}
}
示例10: request
export async function getTrainPredictions(station: Wmata.Station): Promise<Array<Wmata.TrainPrediction>> {
let options = {
url: `https://api.wmata.com/StationPrediction.svc/json/GetPrediction/${station.Code}`,
headers: {
api_key: wmataApiKey
},
json: true
};
return request(options)
.then(response => response.Trains);
};
示例11: sendAsync
private async sendAsync(payload: string): Promise<any> {
const opts = {
method: 'POST',
uri: `http://${this.host}:${this.port}`,
body: payload,
headers: {
'content-type': 'application/json'
},
};
const bodyString = await request(opts);
const body = JSON.parse(bodyString);
return body.result;
}
示例12: request
test.skip('recording is uploaded and inserted into the db', async () => {
expect(await serverHarness.getClipCount()).toBe(0);
const sentence = 'Wubba lubba dub dub!';
await request({
uri: `http://localhost:${getConfig().SERVER_PORT}/api/v1/en/clips`,
method: 'POST',
headers: {
'Content-Type': 'audio/ogg; codecs=opus4',
uid: 'wat',
sentence: encodeURIComponent(sentence),
},
body: fs.createReadStream(path.join(__dirname, 'test.ogg')),
});
expect(await serverHarness.getClipCount()).toBe(1);
});
示例13: fetchLegalDocument
export default async function fetchLegalDocument(
name: string,
locale: string
): Promise<string> {
if (!cache[name]) cache[name] = {};
let { fetchedAt, textHTML } = cache[name][locale] || ({} as any);
if (textHTML && fetchedAt > Date.now() - CACHE_AGE) {
return textHTML;
}
const [status, text] = await request({
uri: `https://raw.githubusercontent.com/mozilla/legal-docs/master/Common_Voice_${name}/${locale}.md`,
resolveWithFullResponse: true,
})
.then((response: any) => [response.statusCode, response.body])
.catch(response => [response.statusCode, null]);
if (status >= 400 && status < 500) {
return (await Promise.all(
// Fallback Languages
['en', 'es-CL', 'fr', 'pt-BR', 'zh-TW'].map(locale =>
fetchLegalDocument(name, locale)
)
)).join('<br>');
} else if (status < 300) {
textHTML = new commonmark.HtmlRenderer().render(
new commonmark.Parser().parse(
// There's a parseable datetime string in the legal documents, which we don't need to show
(text as string).replace(/{:\sdatetime=".*" }/, '')
)
);
}
cache[name][locale] = { fetchedAt: Date.now(), textHTML };
return textHTML;
}
示例14: main
async function main() {
// Ensure that the database exists.
let database = await initializeDatabase();
// Retrieve the main page.
console.log(`Retrieving page: ${DevelopmentApplicationsUrl}`);
let body = await request({ url: DevelopmentApplicationsUrl });
let $ = cheerio.load(body);
// Examine the HTML to determine how many pages need to be retrieved.
let pageCount = Math.max(1, $("tr.pagerRow td").length - 1);
let eventValidation = $("input[name='__EVENTVALIDATION']").val();
let viewState = $("input[name='__VIEWSTATE']").val();
if (pageCount === 1)
console.log(`There is ${pageCount} page to parse.`)
else
console.log(`There are at least ${pageCount} pages to parse.`)
// Process the text from each page.
for (let pageIndex = 1; pageIndex <= 50; pageIndex++) { // as a safety precaution enforce a hard limit of 50 pages
console.log(`Parsing page ${pageIndex}.`);
// Retrieve a subsequent page.
if (pageIndex >= 2) {
try {
let body = await request.post({
url: DevelopmentApplicationsUrl,
headers: { "Content-Type": "application/x-www-form-urlencoded" },
form: {
__EVENTARGUMENT: `Page$${pageIndex}`,
__EVENTTARGET: "ctl00$Content$cusResultsGrid$repWebGrid$ctl00$grdWebGridTabularView",
__EVENTVALIDATION: eventValidation,
__VIEWSTATE: viewState
}});
$ = cheerio.load(body);
eventValidation = $("input[name='__EVENTVALIDATION']").val();
viewState = $("input[name='__VIEWSTATE']").val();
} catch (ex) {
console.log(`Reached the last page: ${ex.message}`);
break;
}
}
// Use cheerio to find all development applications listed in the current page.
for (let element of $("table.grid tr.normalRow, table.grid tr.alternateRow").get()) {
let row = $(element).children("td").get().map(cell => $(cell).text().trim());
if (row.length < 4)
continue;
let applicationNumber = row[0];
let receivedDate = moment(row[1], "D/MM/YYYY", true); // allows the leading zero of the day to be omitted
let description = row[2];
let address = row[3];
// Check for a valid application number and a non-empty address.
if (!/^[0-9]{3}\/[0-9]{1,5}\/[0-9]{2}$/.test(applicationNumber) || address === "")
continue;
await insertRow(database, {
applicationNumber: applicationNumber,
address: address,
description: ((description === "") ? "No description provided" : description),
informationUrl: DevelopmentApplicationUrl.replace(/\{0\}/g, applicationNumber),
commentUrl: CommentUrl,
scrapeDate: moment().format("YYYY-MM-DD"),
receivedDate: receivedDate.isValid ? receivedDate.format("YYYY-MM-DD") : ""
});
}
}
}