Files
play-dl-test/play-dl/Request/index.ts

53 lines
1.5 KiB
TypeScript
Raw Normal View History

2021-10-09 16:18:05 +05:30
import { Response } from './classes';
2021-10-08 14:58:06 +05:30
export type Proxy = ProxyOpts | string;
interface ProxyOpts {
host: string;
port: number;
authentication?: {
username: string;
password: string;
};
}
interface RequestOptions {
body?: string;
method: 'GET' | 'POST';
proxies?: Proxy[];
2021-10-09 16:18:05 +05:30
cookies?: boolean;
headers?: Object;
timeout?: number;
2021-10-08 14:58:06 +05:30
}
2021-10-09 16:18:05 +05:30
interface StreamGetterOptions {
2021-10-08 14:58:06 +05:30
method: 'GET' | 'POST';
2021-10-09 16:18:05 +05:30
cookies?: boolean;
headers: Object;
2021-10-08 14:58:06 +05:30
}
2021-10-09 16:18:05 +05:30
export function request_stream(req_url: string, options: RequestOptions = { method: 'GET' }): Promise<Response> {
return new Promise(async (resolve, reject) => {
let res = new Response(req_url, options);
await res.stream();
2021-10-08 14:58:06 +05:30
if (res.statusCode >= 300 && res.statusCode < 400) {
res = await request_stream((res.headers as any).location, options);
2021-10-09 16:18:05 +05:30
await res.stream();
2021-10-08 14:58:06 +05:30
}
2021-10-09 16:18:05 +05:30
resolve(res);
});
2021-10-08 14:58:06 +05:30
}
2021-10-09 16:18:05 +05:30
export function request(req_url: string, options: RequestOptions = { method: 'GET' }): Promise<Response> {
return new Promise(async (resolve, reject) => {
let res = new Response(req_url, options);
await res.fetch();
2021-10-08 14:58:06 +05:30
if (Number(res.statusCode) >= 300 && Number(res.statusCode) < 400) {
res = await request((res.headers as any).location, options);
} else if (Number(res.statusCode) > 400) {
reject(new Error(`Got ${res.statusCode} from the request`));
}
2021-10-09 16:18:05 +05:30
resolve(res);
});
}