typescript lol

This commit is contained in:
Flummi 2025-03-18 11:30:53 +01:00
parent 232fdef0d9
commit 6fad46fd95
7 changed files with 225 additions and 40 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
node_modules

63
dist/index.js vendored Normal file
View File

@ -0,0 +1,63 @@
import http from "http";
import https from "https";
import { URL } from "url";
import querystring from "querystring";
const readData = (res, mode) => new Promise((resolve, reject) => {
const chunks = [];
res
.on("data", chunk => chunks.push(chunk))
.on("end", () => {
const data = Buffer.concat(chunks);
try {
if (mode === "json")
resolve(JSON.parse(data.toString("utf8")));
else if (mode === "buffer")
resolve(data);
else if (mode === "arraybuffer")
resolve(new Uint8Array(data).buffer);
else
resolve(data.toString("utf8"));
}
catch (err) {
reject(err);
}
})
.on("error", reject);
});
export default async (urlString, options = {}) => {
const { protocol, hostname, pathname, search, port } = new URL(urlString);
const body = options.method === "POST" && options.body
? options.headers?.["Content-Type"] === "application/json"
? JSON.stringify(options.body)
: querystring.stringify(options.body)
: null;
const requestOptions = {
hostname,
port: port || (protocol === "https:" ? 443 : 80),
path: pathname + search,
method: options.method || "GET",
headers: {
...options.headers,
...(body ? { "Content-Length": Buffer.byteLength(body) } : {}),
}
};
return new Promise((resolve, reject) => {
const requester = protocol === "https:" ? https : http;
const req = requester.request(requestOptions, res => {
if (res.statusCode && (res.statusCode < 200 || res.statusCode >= 300))
return reject(new Error(`Request failed with status code ${res.statusCode}`));
resolve({
body: res,
headers: res.headers,
text: () => readData(res, "text"),
json: () => readData(res, "json"),
buffer: () => readData(res, "buffer"),
arrayBuffer: () => readData(res, "arraybuffer")
});
});
req.on("error", reject);
if (body)
req.write(body);
req.end();
});
};

48
package-lock.json generated Normal file
View File

@ -0,0 +1,48 @@
{
"name": "flumm-fetch",
"version": "2.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "flumm-fetch",
"version": "2.0.0",
"license": "MIT",
"devDependencies": {
"@types/node": "^22.13.10",
"typescript": "^5.8.2"
}
},
"node_modules/@types/node": {
"version": "22.13.10",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.13.10.tgz",
"integrity": "sha512-I6LPUvlRH+O6VRUqYOcMudhaIdUVWfsjnZavnsraHvpBwaEyMN29ry+0UVJhImYL16xsscu0aske3yA+uPOWfw==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~6.20.0"
}
},
"node_modules/typescript": {
"version": "5.8.2",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.2.tgz",
"integrity": "sha512-aJn6wq13/afZp/jT9QZmwEjDqqvSGp1VT5GVg+f/t6/oVyrgXM6BY1h9BRh/O5p3PlUPAe+WuiEZOmb/49RqoQ==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=14.17"
}
},
"node_modules/undici-types": {
"version": "6.20.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.20.0.tgz",
"integrity": "sha512-Ny6QZ2Nju20vw1SRHe3d9jVu6gJ+4e3+MMpqu7pqE5HT6WsTSlce++GQmK5UXS8mzV8DSYHrQH+Xrf2jVcuKNg==",
"dev": true,
"license": "MIT"
}
}
}

View File

@ -1,22 +1,28 @@
{ {
"name": "flumm-fetch", "name": "flumm-fetch",
"version": "1.0.2", "version": "2.0.0",
"description": "", "description": "",
"main": "src/index.mjs", "main": "dist/index.js",
"scripts": { "scripts": {
"test": "echo \"Error: no test specified\" && exit 1" "build": "tsc",
"test": "node src/test.mjs"
}, },
"repository": { "repository": {
"type": "git", "type": "git",
"url": "git+https://github.com/kein-Bot/flumm-fetch.git" "url": "git+https://git.lat/keinBot/flumm-fetch.git"
}, },
"keywords": [ "keywords": [
"fetch" "fetch"
], ],
"author": "Flummi", "author": "Flummi",
"license": "MIT", "license": "MIT",
"type": "module",
"bugs": { "bugs": {
"url": "https://github.com/kein-Bot/flumm-fetch/issues" "url": "https://git.lat/keinBot/flumm-fetch/issues"
}, },
"homepage": "https://github.com/kein-Bot/flumm-fetch#readme" "homepage": "https://git.lat/keinBot/flumm-fetch#readme",
"devDependencies": {
"@types/node": "^22.13.10",
"typescript": "^5.8.2"
}
} }

View File

@ -1,34 +0,0 @@
import http from "http";
import https from "https";
import url from "url";
import querystring from "querystring";
const readdata = (res, mode, data = "") => new Promise((resolve, reject) => res
.setEncoding("utf8")
.on("data", chunk => data += chunk)
.on("end", () => {
switch(mode) {
case "text": resolve(data); break;
case "json": try { resolve(JSON.parse(data)); } catch(err) { reject(data); } break;
case "buffer": resolve(new Buffer.from(data)); break;
default: reject("lol no D:"); break;
}
}));
export default (a, options = {}, link = url.parse(a), body = "") => new Promise((resolve, reject) => {
options = {...{ hostname: link.hostname, path: link.path, method: "GET" }, ...options};
if(options.method === "POST") {
body = typeof options.body === "object" ? querystring.stringify(options.body) : options.body;
delete options.body;
options.headers = {...{
"Content-Type": "application/x-www-form-urlencoded",
"Content-Length": Buffer.byteLength(body)
}, ...options.headers};
}
(link.protocol === "https:"?https:http).request(options, res => resolve({
body: res,
headers: res.headers,
text: () => readdata(res, "text"),
json: () => readdata(res, "json"),
buffer: () => readdata(res, "buffer")
})).on("error", err => reject(err)).end(body);
});

87
src/index.ts Normal file
View File

@ -0,0 +1,87 @@
import http from "http";
import https from "https";
import { URL } from "url";
import querystring from "querystring";
type ResponseData = {
body: http.IncomingMessage;
headers: http.IncomingHttpHeaders;
text: () => Promise<string>;
json: () => Promise<any>;
buffer: () => Promise<Buffer>;
arrayBuffer: () => Promise<ArrayBuffer>;
};
interface ExtendedRequestOptions extends http.RequestOptions {
body?: any;
}
const readData = (
res: http.IncomingMessage,
mode: "text" | "json" | "buffer" | "arraybuffer"
): Promise<string | any | Buffer | ArrayBuffer> =>
new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
res
.on("data", chunk => chunks.push(chunk))
.on("end", () => {
const data = Buffer.concat(chunks);
try {
if(mode === "json")
resolve(JSON.parse(data.toString("utf8")));
else if(mode === "buffer")
resolve(data);
else if(mode === "arraybuffer")
resolve(new Uint8Array(data).buffer);
else
resolve(data.toString("utf8"));
}
catch(err: any) {
reject(err);
}
})
.on("error", reject);
});
export default async (urlString: string, options: ExtendedRequestOptions = {}): Promise<ResponseData> => {
const { protocol, hostname, pathname, search, port } = new URL(urlString);
const body =
options.method === "POST" && options.body
? options.headers?.["Content-Type"] === "application/json"
? JSON.stringify(options.body)
: querystring.stringify(options.body as querystring.ParsedUrlQueryInput)
: null;
const requestOptions: http.RequestOptions = {
hostname,
port: port || (protocol === "https:" ? 443 : 80),
path: pathname + search,
method: options.method || "GET",
headers: {
...options.headers,
...(body ? { "Content-Length": Buffer.byteLength(body) } : {}),
}
};
return new Promise((resolve, reject) => {
const requester = protocol === "https:" ? https : http;
const req = requester.request(requestOptions, res => {
if(res.statusCode && (res.statusCode < 200 || res.statusCode >= 300))
return reject(new Error(`Request failed with status code ${res.statusCode}`));
resolve({
body: res,
headers: res.headers,
text: () => readData(res, "text"),
json: () => readData(res, "json"),
buffer: () => readData(res, "buffer"),
arrayBuffer: () => readData(res, "arraybuffer")
});
});
req.on("error", reject);
if(body)
req.write(body);
req.end();
});
};

14
tsconfig.json Normal file
View File

@ -0,0 +1,14 @@
{
"compilerOptions": {
"target": "es2024",
"module": "ESNext",
"moduleResolution": "node",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"removeComments": true
},
"include": ["src"],
"exclude": ["node_modules"]
}