当前位置: 首页>>代码示例>>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;未经允许,请勿转载。