當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript request-promise類代碼示例

本文整理匯總了TypeScript中request-promise的典型用法代碼示例。如果您正苦於以下問題:TypeScript request-promise類的具體用法?TypeScript request-promise怎麽用?TypeScript request-promise使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了request-promise類的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`)
         }
     };
 },
開發者ID:khell,項目名稱:scrape-coinjar,代碼行數:15,代碼來源:index.ts

示例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;
  }
開發者ID:endlessdev,項目名稱:PortalRank,代碼行數:30,代碼來源:naver-parser.ts

示例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));
  }
開發者ID:juliandawson,項目名稱:axosoft-diary,代碼行數:33,代碼來源:diary.ts

示例4: getAll

 public async getAll(): Promise<ITodo[]> {
     console.log(`[GET] /api/todos`);
     return await rp({
         uri: `${this.url}/api/todos`,
         json: true
     });
 }
開發者ID:gantrior,項目名稱:solarwinds-meetup-workshop,代碼行數:7,代碼來源:todoRestService.ts

示例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);
    }
  }
開發者ID:endlessdev,項目名稱:PortalRank,代碼行數:28,代碼來源:naver-parser.ts

示例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;
    }
開發者ID:jgkim7,項目名稱:blog,代碼行數:27,代碼來源:bookmarkService.ts

示例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>);
  }
}
開發者ID:arciisine,項目名稱:BitbucketImporter,代碼行數:27,代碼來源:util.ts

示例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
                };
            });
    }
開發者ID:itsuryev,項目名稱:tp-oauth-server,代碼行數:33,代碼來源:userInfoProvider.ts

示例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;
    }
  }
開發者ID:kukrejadinesh,項目名稱:node-spotify-api,代碼行數:33,代碼來源:index.ts

示例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));
  }
開發者ID:juliandawson,項目名稱:axosoft-diary,代碼行數:36,代碼來源:diary.ts


注:本文中的request-promise類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。