snoowrap icon indicating copy to clipboard operation
snoowrap copied to clipboard

How to use proxy in snoowrap?

Open learnacadman opened this issue 2 years ago • 2 comments

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 avatar Jan 20 '23 14:01 learnacadman

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

learnacadman avatar Apr 08 '23 11:04 learnacadman

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.

noc2spam avatar Jun 17 '23 03:06 noc2spam