not-an-aardvark / snoowrap

A JavaScript wrapper for the reddit API
MIT License
1.01k stars 125 forks source link

How to use proxy in snoowrap? #375

Open learnacadman opened 1 year ago

learnacadman commented 1 year ago

Let's say I want to use a proxy server 123.456.789 with the port 8080, how do I pass that to snoowrap?

learnacadman commented 1 year ago

@LucasianProfessor ok, and how to pass username password for the proxy?

noc2spam commented 1 year ago

This is how I made it work..

interface RequestOptions {
  json: boolean;
  baseUrl: string;
  uri: string;
  method: string;
  headers: object;
  qs?: object;
  form?: object;
  auth?: {
    bearer: string;
    user: string;
    pass: string;
  };
  formData: object;
  body: object;
  transform: Function;
  resolveWithFullResponse: boolean;
}

export default class SnoowrapWithProxy extends Snoowrap {
  proxy: {
    host: string;
    port: number;
    auth: {
      username: string;
      password: string;
    };
    protocol: "http";
  };
  constructor(
    options: SnoowrapOptions,
    proxy: {
      host: string;
      port: number;
      auth: {
        username: string;
        password: string;
      };
      protocol: "http";
    }
  ) {
    super(options);
    this.proxy = proxy;
  }
  rawRequest(options: RequestOptions) {
    const auth = options?.auth?.bearer
      ? `bearer ${options.auth.bearer}`
      : "basic " + btoa(`${options?.auth?.user}:${options?.auth?.pass}`);
    const agent = options?.headers!["user-agent"];
    const axiosOptions = {
      url: options.uri,
      method: options.method,
      baseURL: options.baseUrl,
      data: options.form,
      proxy: this.proxy,

      headers: {
        Authorization: auth,
        "user-agent": agent,
        "Content-Type": "application/x-www-form-urlencoded",
      },
    };
    const promise = axios(axiosOptions)
      .then((resp) => resp.data)
      .catch((r) => r.message);
    return promise;
  }
}

Note, this uses axios as the client, but it could be anything..

Not tested for all usages though. Please be sure to test it before you use it in important places.