Browse Source

Use custom requests function instead of async-request due to size

Wasi Master 3 years ago
parent
commit
020a9995cf
2 changed files with 87 additions and 17 deletions
  1. 13 17
      src/extension.ts
  2. 74 0
      src/requests.ts

+ 13 - 17
src/extension.ts

@@ -2,22 +2,17 @@
 // Import the module and reference it with the alias vscode in your code below
 import * as vscode from 'vscode';
 import { escape as htmlEscape } from 'html-escaper';
-import request = require('@endom8rix/async-request');
-import markdownEscape = require("markdown-escape");
+import { request } from './requests';
+const markdownEscape = require("markdown-escape");
 
 // this method is called when your extension is activated
 // your extension is activated the very first time the command is executed
 export function activate(context: vscode.ExtensionContext) {
 
-	// Use the console to output diagnostic information (console.log) and errors (console.error)
-	// This line of code will only be executed once when your extension is activated
-	console.log('Congratulations, your extension "wikipedia-hyperlinker" is now active!');
 
-	// The command has been defined in the package.json file
-	// Now provide the implementation of the command with registerCommand
-	// The commandId parameter must match the command field in package.json
+
 	let disposable = vscode.commands.registerCommand('wikipedia-hyperlinker.addHyperlink', () => {
-		// The code you place here will be executed every time your command is executed
+
 		var editor = vscode.window.activeTextEditor;
 		if (editor !== undefined) {
 			const currentSelection = editor.selection;
@@ -32,9 +27,9 @@ export function activate(context: vscode.ExtensionContext) {
 				title: 'Loading article from wikipedia...'
 			}, async (progress) => {
 				progress.report({ increment: 0 });
-				// Make a request to wikipedia to get short description
+
 				try {
-					const response = await request(`https://en.wikipedia.org/w/api.php?format=json&action=query&prop=info|extracts&exintro&explaintext&&inprop=url&redirects=1&titles=${encodeURIComponent(text)}`);
+
 					const body = JSON.parse(response.body);
 					progress.report({ increment: 100 });
 					console.log(response);
@@ -44,7 +39,7 @@ export function activate(context: vscode.ExtensionContext) {
 						vscode.window
 							.showInformationMessage(
 								`There are multiple articles under the term ${text}. Do you want to see all the possible articles in wikipedia inside your browser?`,
-								{modal: true},
+								{ modal: true },
 								...["Yes", "No"]
 							)
 							.then((answer) => {
@@ -57,7 +52,7 @@ export function activate(context: vscode.ExtensionContext) {
 						return false;
 					}
 					var currentLanguage = editor?.document.languageId;
-					// vscode.window.showInformationMessage(`Added wikipedia article for ${text}`);
+
 					if (currentLanguage === "markdown") {
 						editor?.edit(editBuilder => {
 							editBuilder.replace(currentSelection,
@@ -70,9 +65,9 @@ export function activate(context: vscode.ExtensionContext) {
 								`<a href="${url}" title="${htmlEscape(summary)}">${htmlEscape(text)}</a>`
 							);
 						});
-					}else {
+					} else {
 						vscode.window.showWarningMessage(`The current language (${currentLanguage}) is not supported`,
-						...["Use HTML", "Use Markdown", "Cancel"]
+							...["Use HTML", "Use Markdown", "Cancel"]
 						).then((answer) => {
 							if (answer === "Use HTML") {
 								editor?.edit(editBuilder => {
@@ -80,7 +75,7 @@ export function activate(context: vscode.ExtensionContext) {
 										`<a href="${url}" title="${htmlEscape(summary)}">${htmlEscape(text)}</a>`
 									);
 								});
-							} else if (answer === "Use Markdown"){
+							} else if (answer === "Use Markdown") {
 								editor?.edit(editBuilder => {
 									editBuilder.replace(currentSelection,
 										`[${markdownEscape(text)}](${url} "${markdownEscape(summary)}")`
@@ -95,7 +90,7 @@ export function activate(context: vscode.ExtensionContext) {
 				}
 
 			});
-			// Display a message box to the user
+
 		} else {
 			vscode.window.showInformationMessage('No window is active');
 
@@ -107,3 +102,4 @@ export function activate(context: vscode.ExtensionContext) {
 
 // this method is called when your extension is deactivated
 export function deactivate() { }
+g

+ 74 - 0
src/requests.ts

@@ -0,0 +1,74 @@
+import { URL } from "url";
+
+const https = require('https');
+const qs = require('querystring');
+
+export interface RequestOptions {
+    headers?: { [key: string]: string | number }
+}
+
+/**
+ * Parse a request body based on known MIME types, based on the Content-Type
+ * header. If unknown or undefined, will return the original request body.
+ * @param {Object} opts - The request options.
+ * @param {Object|string} body - The request body.
+ * @returns {Object|string} A parsed request body for known MIME types, or the original request body.
+ */
+function parse(opts: RequestOptions = {}, body: Object | string) {
+    if (opts.headers == null) {
+        return body;
+    }
+
+    switch (opts.headers['Content-Type']) {
+        case 'application/json': return JSON.stringify(body);
+        case 'application/x-www-form-urlencoded': return qs.stringify(body);
+        default: return body;
+    }
+}
+
+/**
+ * Make an asynchronous request to an HTTP or HTTPS address. Automatically
+ * derives protocol from URL input, and content length from the request body.
+ * @param {URL|string} url - The request URL.
+ * @param {Object} opts - The request options.
+ * @param {Object|string} body - The request body.
+ * @returns {Promise} A promise to return either a response object, or an error.
+ */
+export function request(url: URL | string, opts: RequestOptions = {}, body: Object | string = ''): Promise<any>  {
+    const data = parse(opts, body);
+
+    if (opts.headers == null) {
+        opts.headers = {};
+    }
+    return new Promise((resolve, reject) => {
+        if (!(url instanceof URL)) {
+            url = new URL(url);
+        }
+        const tick = new Date().getTime();
+        const request = https.request(url, opts, (response: any) => {
+            const chunks: any[] = [];
+
+            response.on('data', (chunk: any) => {
+                chunks.push(chunk);
+            });
+
+            response.on('end', () => {
+                try {
+                    const { headers } = response;
+                    const body = chunks.join('');
+                    resolve({ headers, body });
+                }
+                catch (error) {
+                    reject(error);
+                }
+            });
+
+            response.on('error', (error: Error) => {
+                reject(error);
+            });
+        });
+
+        request.write(data);
+        request.end();
+    });
+}