当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript request-promise-native类代码示例

本文整理汇总了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';
开发者ID:ArtemZag,项目名称:DefinitelyTyped,代码行数:31,代码来源:request-promise-native-tests.ts

示例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) => { });
开发者ID:enlight,项目名称:DefinitelyTyped,代码行数:30,代码来源:request-promise-native-tests.ts

示例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))
})
开发者ID:slimui,项目名称:graphql-yoga,代码行数:56,代码来源:index.test.ts

示例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);
  }
});
开发者ID:enlight,项目名称:DefinitelyTyped,代码行数:7,代码来源:request-promise-native-tests.ts

示例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);
      },
    );
  }
开发者ID:wix,项目名称:media-platform-js-sdk,代码行数:39,代码来源:http-client.ts

示例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;
	}
开发者ID:ha-dai,项目名称:Misskey,代码行数:34,代码来源:resolver.ts

示例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}`);
        }
    }
开发者ID:KnowledgeExpert,项目名称:allure-client,代码行数:25,代码来源:request.ts

示例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);
	});
开发者ID:JosephCaillet,项目名称:cozy-vinimay,代码行数:32,代码来源:commentUtils.ts

示例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;
   }
 }
开发者ID:Marabyte,项目名称:spa-static,代码行数:10,代码来源:urlExtractor.ts

示例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);
};
开发者ID:Swimburger,项目名称:CommuteStatus,代码行数:11,代码来源:wmataApi.ts

示例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;
 }
开发者ID:linki,项目名称:0x.js,代码行数:13,代码来源:rpc.ts

示例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);
});
开发者ID:terrylau2013,项目名称:voice-web,代码行数:15,代码来源:upload-recording.test.ts

示例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;
}
开发者ID:WordToken,项目名称:voice-web,代码行数:39,代码来源:fetch-legal-document.ts

示例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") : ""
            });
        }
    }
}
开发者ID:planningalerts-scrapers,项目名称:city_of_charles_sturt,代码行数:78,代码来源:scraper.ts


注:本文中的request-promise-native类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。