Files
play-dl-test/play-dl/YouTube/utils/request.ts

54 lines
1.8 KiB
TypeScript
Raw Normal View History

2021-09-13 00:31:52 +05:30
import https, { RequestOptions } from 'https'
2021-09-13 14:30:59 +09:00
import { IncomingMessage } from 'http'
2021-09-13 00:31:52 +05:30
import { URL } from 'url'
interface RequestOpts extends RequestOptions{
body? : string;
method? : "GET" | "POST"
}
async function https_getter(req_url : string, options : RequestOpts = {}): Promise<IncomingMessage>{
return new Promise((resolve, reject) => {
let s = new URL(req_url)
2021-09-13 14:13:36 +09:00
options.method ??= "GET"
2021-09-13 00:31:52 +05:30
let req_options : RequestOptions = {
host : s.hostname,
path : s.pathname + s.search,
2021-09-13 14:13:36 +09:00
headers : options.headers ?? {},
2021-09-13 10:23:18 +05:30
method : options.method
2021-09-13 00:31:52 +05:30
}
let req = https.request(req_options, (response) => {
resolve(response)
})
if(options.method === "POST") req.write(options.body)
req.end()
})
2021-09-04 20:38:39 +09:00
}
2021-09-13 00:31:52 +05:30
export async function request(url : string, options? : RequestOpts): Promise<string>{
return new Promise(async (resolve, reject) => {
2021-09-13 14:30:59 +09:00
let data = ''
let res = await https_getter(url, options)
if(Number(res.statusCode) >= 300 && Number(res.statusCode) < 400){
res = await https_getter(res.headers.location as string , options)
2021-09-13 00:31:52 +05:30
}
2021-09-13 14:30:59 +09:00
else if(Number(res.statusCode) > 400){
reject(`Got ${res.statusCode} from the request`)
2021-09-13 00:31:52 +05:30
}
2021-09-13 14:30:59 +09:00
res.setEncoding('utf-8')
res.on('data', (c) => data+=c)
res.on('end', () => resolve(data))
2021-09-13 00:31:52 +05:30
})
}
export async function request_stream(url : string, options? : RequestOpts): Promise<IncomingMessage>{
return new Promise(async (resolve, reject) => {
2021-09-13 14:30:59 +09:00
let res = await https_getter(url, options)
if(Number(res.statusCode) >= 300 && Number(res.statusCode) < 400){
res = await https_getter(res.headers.location as string, options)
2021-09-13 00:31:52 +05:30
}
2021-09-13 14:30:59 +09:00
resolve(res)
2021-09-13 00:31:52 +05:30
})
2021-09-13 14:30:59 +09:00
}