node-fetch#Request TypeScript Examples

The following examples show how to use node-fetch#Request. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: transaction.ts    From stellar-anchor-tests with Apache License 2.0 6 votes vote down vote up
returns404ForBadExternalId: Test = {
  assertion: "returns 404 for a nonexistent external transaction ID",
  sep: 24,
  group: transactionTestGroup,
  dependencies: [hasTransferServerUrl, returnsValidJwt],
  context: {
    expects: {
      transferServerUrl: undefined,
      token: undefined,
    },
    provides: {},
  },
  failureModes: genericFailures,
  async run(_config: Config): Promise<Result> {
    const result: Result = { networkCalls: [] };
    const getTransactionCall: NetworkCall = {
      request: new Request(
        this.context.expects.transferServerUrl +
          transactionEndpoint +
          "?external_transaction_id=9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d",
        {
          headers: {
            Authorization: `Bearer ${this.context.expects.token}`,
          },
        },
      ),
    };
    await makeRequest(getTransactionCall, 404, result);
    return result;
  },
}
Example #2
Source File: index.ts    From nodetskeleton with MIT License 6 votes vote down vote up
private buildRequest(
    url: string,
    method: string,
    body?: BodyType,
    headers?: Headers,
    options?: RequestInit,
  ): Request {
    if (!options) options = {};
    options["method"] = method;
    if (body) options["body"] = body;
    if (headers) options["headers"] = headers;

    return new Request(url, options);
  }
Example #3
Source File: transaction.ts    From stellar-anchor-tests with Apache License 2.0 6 votes vote down vote up
returns404ForBadStellarId: Test = {
  assertion: "returns 404 for a nonexistent Stellar transaction ID",
  sep: 24,
  group: transactionTestGroup,
  dependencies: [hasTransferServerUrl, returnsValidJwt],
  context: {
    expects: {
      transferServerUrl: undefined,
      token: undefined,
    },
    provides: {},
  },
  failureModes: genericFailures,
  async run(_config: Config): Promise<Result> {
    const result: Result = { networkCalls: [] };
    const getTransactionCall: NetworkCall = {
      request: new Request(
        this.context.expects.transferServerUrl +
          transactionEndpoint +
          "?stellar_transaction_id=021581089cb614be94b0ac5dc71cadf23a1cd96a2584152268de505ee2e5e999",
        {
          headers: {
            Authorization: `Bearer ${this.context.expects.token}`,
          },
        },
      ),
    };
    await makeRequest(getTransactionCall, 404, result);
    return result;
  },
}
Example #4
Source File: eos.ts    From coin-wallets with Apache License 2.0 6 votes vote down vote up
// https://docs.dfuse.io/guides/eosio/tutorials/write-chain/
function createCustomizedFetch(
  client: DfuseClient,
): (input: string | Request, init: RequestInit) => Promise<Response> {
  const customizedFetch = async (input: string | Request, init: RequestInit): Promise<Response> => {
    if (init.headers === undefined) {
      init.headers = {}; // eslint-disable-line no-param-reassign
    }

    // This is highly optimized and cached, so while the token is fresh, this is very fast
    const apiTokenInfo = await client.getTokenInfo();

    const headers = init.headers as { [name: string]: string };
    headers.Authorization = `Bearer ${apiTokenInfo.token}`;
    headers['X-Eos-Push-Guarantee'] = 'in-block';

    return fetch(input, init);
  };

  return customizedFetch;
}
Example #5
Source File: horizon.ts    From stellar-anchor-tests with Apache License 2.0 6 votes vote down vote up
loadAccount = async (
  account: string,
  result: Result,
  pubnet: boolean = false,
): Promise<AccountResponse | void> => {
  const horizon = pubnet ? pubnetHorizon : testnetHorizon;
  const networkCall: NetworkCall = {
    request: new Request(horizon + `/accounts/${account}`),
  };
  result.networkCalls.push(networkCall);
  await makeRequest(networkCall, result);
  if (!networkCall.response) return;
  const responseJson = await networkCall.response.clone().json();
  return new AccountResponse(responseJson);
}
Example #6
Source File: arcfetch.ts    From BotArcAPIs-Memories with MIT License 4 votes vote down vote up
export class ArcFetchRequest extends Request {

  private _init: ArcFetchExtra;
  private _method: ArcFetchMethod;
  private _resturl: ArcFetchRestUrl;

  set init(val: ArcFetchExtra) {
    this._init = val;
  }

  set methods(val: ArcFetchMethod) {
    this._method = val;
  }

  set resturl(val: ArcFetchRestUrl) {
    this._resturl = val;
  }

  get init(): ArcFetchExtra {
    return this._init;
  }

  get methods(): ArcFetchMethod {
    return this._method;
  }

  get resturl(): ArcFetchRestUrl {
    return this._resturl;
  }

  constructor(method: ArcFetchMethod, resturl: ArcFetchRestUrl, init: ArcFetchExtra) {

    // request url
    let _request_url: ArcFetchRestUrl =
      `${do_selectnode()}/${ARCAPI_URL_CODENAME}/${ARCAPI_VERSION}/${resturl}`;

    // http headers
    const _request_headers: ArcFetchHeaders = {
      'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
      'AppVersion': ARCAPI_APPVERSION,
      'User-Agent': ARCAPI_USERAGENT,
      'Platform': 'android',
      'Connection': 'Keep-Alive'
    }

    // extra identity header
    if (init.userToken) {
      _request_headers['Accept-Encoding'] = 'identity';
      _request_headers['Authorization'] = `Bearer ${init.userToken}`;
    }
    else if (init.userName && init.userPasswd) {
      _request_headers['Accept-Encoding'] = 'identity';
      _request_headers['Authorization'] = `Basic ${btoa(`${init.userName}:${init.userPasswd}`)}`;
    }

    // extra device header
    if (init.deviceId) {
      _request_headers['DeviceId'] = init.deviceId;
    }

    // challenge code
    let _hash_body = "";
    if (method == 'POST' && init.submitData) {
      _hash_body = init.submitData.toString();
    }

    _request_headers['X-Random-Challenge'] = archash(_hash_body);

    // append init.submitData after url if method is GET
    // otherwise it's post data
    let _request_body: any = null;
    if (init.submitData) {
      if (method == 'GET' && init.submitData instanceof URLSearchParams) {
        _request_url += '?' + init.submitData;
      }
      else if (method == 'POST') {
        _request_body = init.submitData;
      }
    }

    super(_request_url, {
      method: method,
      headers: _request_headers,
      body: _request_body
    });

    // save arguments
    this._init = init;
    this._method = method;
    this._resturl = resturl;
  }

}
Example #7
Source File: transactions.ts    From stellar-anchor-tests with Apache License 2.0 4 votes vote down vote up
honorsDepositTransactionKind: Test = {
  assertion: "only returns deposit transactions when kind=deposit",
  sep: 24,
  group: transactionsTestGroup,
  dependencies: [
    hasTransferServerUrl,
    hasProperDepositTransactionsSchema,
    hasProperWithdrawTransactionSchema,
    returnsValidJwt,
  ],
  context: {
    expects: {
      transferServerUrl: undefined,
      token: undefined,
    },
    provides: {},
  },
  failureModes: {
    BAD_KIND: {
      name: "deposit transaction returned",
      text(_args: any): string {
        return "Withdraw transactions should not be returned when kind=deposit";
      },
      links: {
        "Transaction Fields":
          "https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0024.md#shared-fields-for-both-deposits-and-withdrawals",
      },
    },
    NO_TRANSACTIONS: {
      name: "no transactions returned",
      text(_args: any): string {
        return "No transactions were returned, even though a deposit transaction was created";
      },
      links: {
        "Transactions Response":
          "https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0024.md#transaction-history",
      },
    },
    INVALID_TRANSACTIONS_SCHMEA: invalidTransactionsSchema,
    ...genericFailures,
  },
  async run(config: Config): Promise<Result> {
    const result: Result = { networkCalls: [] };
    const getDepositTransactionsCall: NetworkCall = {
      request: new Request(
        this.context.expects.transferServerUrl +
          transactionsEndpoint +
          `?asset_code=${config.assetCode}&kind=deposit`,
        {
          headers: {
            Authorization: `Bearer ${this.context.expects.token}`,
          },
        },
      ),
    };
    result.networkCalls.push(getDepositTransactionsCall);
    const depositTransactions = await makeRequest(
      getDepositTransactionsCall,
      200,
      result,
      "application/json",
    );
    if (!depositTransactions) return result;
    const validationResult = validate(depositTransactions, transactionsSchema);
    if (validationResult.errors.length !== 0) {
      result.failure = makeFailure(
        this.failureModes.INVALID_TRANSACTIONS_SCHMEA,
        { errors: validationResult.errors.join("\n") },
      );
      return result;
    }
    if (depositTransactions.transactions.length === 0) {
      result.failure = makeFailure(this.failureModes.NO_TRANSACTIONS);
      return result;
    }
    for (const transaction of depositTransactions.transactions) {
      if (transaction.kind !== "deposit") {
        result.failure = makeFailure(this.failureModes.BAD_KIND);
        return result;
      }
    }
    return result;
  },
}