How to use node-fetch - 10 common examples

To help you get started, we’ve selected a few node-fetch examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github decentralized-identity / sidetree / tests / core / Observer.spec.ts View on Github external
function createReadableStreamResponse (content: object, status?: number): Response {
  // const stream = new Readable({ objectMode: true });
  const stream = new RepeatingReadable(content);
  stream.push(JSON.stringify(content));

  const response = new Response(stream, { status: status ? status : 200 });
  return response;
}
github fortunejs / fortune / test / integration / middlewares.js View on Github external
import Test from 'tape'
import connect from 'connect'
import express from 'express'
import fetch from 'node-fetch'
import Fortune from '../../lib'
import generateApp from './generate_app'
import Serializer from '../../lib/serializer'


// Set promise polyfill for old versions of Node.
fetch.Promise = Promise

const port = 1337
const mediaType = 'application/json'

class DefaultSerializer extends Serializer {
  processResponse (context) {
    const { payload } = context.response
    context.response.payload = new Buffer(JSON.stringify(payload))
    return context
  }
}

DefaultSerializer.id = mediaType

const frameworks = [
  { name: 'express', fn: express },
github pd4d10 / octohint / scripts / get-lib-names.js View on Github external
async function main() {
  //   const res = await fetch('https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/master/notNeededPackages.json')
  //   const { packages } = await res.json()
  try {
    const r0 = await fetch('https://api.github.com/repos/DefinitelyTyped/DefinitelyTyped/git/trees/master')
    const { tree: t0 } = await r0.json()
    const { url } = t0.filter(({ path }) => path === 'types')[0]
    const r1 = await fetch(url)
    const { tree: t1 } = await r1.json()
    const libs = t1.map(({ path }) => path)
    const content = `module.exports = ${JSON.stringify(libs)}`

    fs.writeFileSync(path.resolve(__dirname, '../src/libs.js'), content)
  } catch (err) {
    console.log(err)
  }
}
github pulumi / pulumi-awsx / nodejs / examples / dashboards / index.ts View on Github external
const subscription = topic.onEvent("for-each-url", async (event) => {
    const records = event.Records || [];
    for (const record of records) {
        const url = record.Sns.Message;

        console.log(`${url}: Processing`);

        // Fetch the contents at the URL
        console.log(`${url}: Getting`);
        try {
            const res = await fetch.default(url);
        } catch (err) {
            console.log(`${url}: Failed to GET`);
            return;
        }
    }
});
github adidas / mashery-toolbelt / src / masheryClient.js View on Github external
const { URL } = require('url');
const fetch = require('node-fetch');

require('dotenv').config();

const MASHERY_KEY = process.env.MASHERY_KEY;
const MASHERY_HOST = process.env.MASHERY_HOST;

// Common request headers
const RequestHeaders = new fetch.Headers({
  "Accept": "application/json",
  "Authorization": `Bearer ${MASHERY_KEY}`,
});

// Fetch HTTP Error Handler
function handleHTTPError(response) {
  if (!response.ok) {
    var message = `(${response.status}) ${response.statusText}\n\n`;
    const headers = response.headers['_headers'];

    for (var key in headers) {
      message += `${key}: ${headers[key]}\n`;
    }

    // response.text().then(data => console.log(data));
github hammerspacecouk / tubealert.co.uk / src / models / Status.js View on Github external
fetchNewLatest() {
    const now = this.dateTimeHelper.getNow();
    const url =
      "https://api.tfl.gov.uk/Line/Mode/tube,dlr,tflrail,overground/Status" +
      `?app_id=${this.config.TFL_APP_ID}` +
      `&app_key=${this.config.TFL_APP_KEY}`;

    this.logger.info("Fetching from TFL");
    // only include this require on invocation (so the memory is cleared)
    return require("node-fetch")(url) // eslint-disable-line global-require
      .then(response => response.json())
      .then(this.mutateData.bind(this))
      .then(data => this.storeStatus(now, data));
  }
github jakejrichards / cod-api / index.js View on Github external
function getDataFromAPI(uri) {
    return node_fetch_1["default"](uri)
        .then(function (response) { return response.json(); })
        .then(function (response) {
        var status = response.status, error = response.data;
        if (status !== 'success') {
            throw new Error("cod-api request failed: " + error.message);
        }
        return response;
    });
}
// API Methods
github rockstat / chwriter / dist / clickhouse / CHClient.js View on Github external
async execute(body) {
        const queryUrl = this.url + '/?' + qs.stringify(this.params);
        let responseBody;
        // try {
        const res = await node_fetch_1.default(queryUrl, {
            method: constants_1.METHOD_POST,
            body: body,
            timeout: this.timeout
        });
        responseBody = await res.text();
        if (!res.ok) {
            throw new Error(responseBody);
        }
        // } catch (error) {
        //   throw error;
        // }
        return responseBody;
    }
    /**
github microsoft / rushstack / apps / rush-lib / src / logic / InstallManager.ts View on Github external
private _queryIfReleaseIsPublished(registryUrl: string): Promise {
    let queryUrl: string = registryUrl;
    if (queryUrl[-1] !== '/') {
      queryUrl += '/';
    }
    // Note that the "@" symbol does not normally get URL-encoded
    queryUrl += RushConstants.rushPackageName.replace('/', '%2F');

    const userAgent: string = `pnpm/? npm/? node/${process.version} ${os.platform()} ${os.arch()}`;

    const headers: fetch.Headers = new fetch.Headers();
    headers.append('user-agent', userAgent);
    headers.append('accept', 'application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*');

    let agent: http.Agent | undefined = undefined;
    if (process.env.HTTP_PROXY) {
      agent = new HttpsProxyAgent(process.env.HTTP_PROXY);
    }

    return fetch
      .default(queryUrl, {
        headers: headers,
        agent: agent
      })
      .then((response: fetch.Response) => {
        if (!response.ok) {
          return Promise.reject(new Error('Failed to query'));
github hensm / fx_cast / app / src / bridge / airplay / auth.ts View on Github external
public async sendPostRequest (
            path: string
          , contentType?: string
          , data?: Buffer | string): Promise {

        // Create URL from base receiver URL and path
        const requestUrl = new URL(path, this.baseUrl);

        const requestHeaders = new Headers({
            "User-Agent": "AirPlay/320.20"
        });

        // Append Content-Type header if request has body
        if (data && contentType) {
            requestHeaders.append("Content-Type", contentType);
        }

        const response = await fetch(requestUrl.href, {
            method: "POST"
          , headers: requestHeaders
          , body: data
        });

        if (!response.ok) {
            throw new Error(`AirPlay request error: ${response.status}`);