Skip to content

Commit

Permalink
use http module
Browse files Browse the repository at this point in the history
  • Loading branch information
saqqdy committed Nov 30, 2021
1 parent 975356e commit 4bff905
Show file tree
Hide file tree
Showing 9 changed files with 232 additions and 79 deletions.

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion app/www/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@
<div id="box"></div>

<script nomodule>!function(){var e=document,t=e.createElement("script");if(!("noModule"in t)&&"onbeforeload"in t){var n=!1;e.addEventListener("beforeload",(function(e){if(e.target===t)n=!0;else if(!e.target.hasAttribute("nomodule")||!n)return;e.preventDefault()}),!0),t.type="module",t.src=".",e.head.appendChild(t),t.remove()}}();</script>
<script nomodule id="vite-legacy-polyfill" src="/assets/polyfills-legacy.5229e370.js"></script>
<script nomodule id="vite-legacy-polyfill" src="/assets/polyfills-legacy.a3a493e7.js"></script>
<script nomodule id="vite-legacy-entry" data-src="/assets/index-legacy.716cba63.js">System.import(document.getElementById('vite-legacy-entry').getAttribute('data-src'))</script>
</body>
</html>
2 changes: 1 addition & 1 deletion bin/core/api/getUserToken.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ async function getUserToken(): Promise<FetchDataType> {
}

const fetchData =
((await request({ url: `${config.api}?name=${user}` }))
((await request.get({ url: `${config.api}?name=${user}` }))
.data as FetchDataType) || null
// 没有查到用户信息或者没有设置token
if (!fetchData) {
Expand Down
170 changes: 139 additions & 31 deletions bin/core/request.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,145 @@
const https = require('https')
const http = require('http')
const zlib = require('zlib')
const { URL } = require('url')
const qs = require('qs')

function request(options: any) {
const url = new URL(options.url)
return new Promise((resolve, reject) => {
const req = https.request(
{
hostname: url.hostname,
port: url.port,
path: `${url.pathname}${url.search}`,
method: 'GET',
...options
},
(res: any) => {
res.on('data', (buf: any) => {
const data = Buffer.from(buf).toString()
let result = null
try {
result = JSON.parse(data)
} catch {
//
}
if (result.code === 0) {
resolve(result)
} else {
reject(result)
}
})
class Request {
cookies: string[] = []
constructor() {
// if (cookie) {
// this.setCookie(cookie)
// }
}
/**
* 获取请求头
*
* @param host - 请求的域名
* @param propsData - 请求数据
* @returns headers - 请求头
*/
public getHeaders(host: string, postData?: string) {
const headers: { [prop: string]: string | number | boolean } = {
Host: host,
rejectUnauthorized: false,
Pragma: 'no-cache',
Connection: 'keep-alive',
'Cache-Control': 'no-cache',
'Content-Type': 'application/x-www-form-urlencoded',
'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4,es;q=0.2',
Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'User-Agent':
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Safari/537.36'
}
if (this.cookies.length) {
headers.Cookie = this.cookies.join('; ')
}
if (postData) {
headers['Content-Length'] = Buffer.byteLength(postData)
}
return headers
}
/**
* 设置cookie
*
* @param cookie - cookie
* @returns this - 当前类
*/
public setCookie(cookie: string) {
const cookies = cookie.split(';')
for (let item of cookies) {
item = item.replace(/^\s/, '')
this.cookies.push(item)
}
return this
}
/**
* 发起请求
*
* @param method - 请求方法:'GET' | 'POST' | 'DELETE' | 'OPTIONS'
* @param url - 请求链接
* @param params - 请求参数
* @returns Promise - 请求结果
*/
public request(
method: 'GET' | 'POST' | 'DELETE' | 'OPTIONS',
url: string,
params?: object
) {
const postData = qs.stringify(params || {}, {
arrayFormat: 'indices',
allowDots: true
})
const urlObj = new URL(url)
const options = {
hostname: urlObj.hostname,
port: urlObj.port,
path: urlObj.pathname + urlObj.search,
method,
headers: this.getHeaders(urlObj.host, postData)
}
return new Promise((resolve, reject) => {
const req = (urlObj.protocol == 'http:' ? http : https).request(
options,
(res: any) => {
const chunks: any[] = []
res.on('data', (buf: any) => {
// const data = JSON.parse(Buffer.from(buf).toString())
chunks.push(buf)
})
res.on('end', () => {
const buffer = Buffer.concat(chunks)
const encoding = res.headers['content-encoding']
if (encoding === 'gzip') {
zlib.gunzip(
buffer,
function (err: Error, decoded: any) {
resolve(decoded.toString())
}
)
} else if (encoding === 'deflate') {
zlib.inflate(
buffer,
function (err: Error, decoded: any) {
resolve(decoded.toString())
}
)
} else {
resolve(JSON.parse(buffer.toString()))
}
})
}
)
req.on('error', (err: Error) => {
reject(err)
})
if (postData) {
req.write(postData)
}
)
req.on('error', reject)
req.end()
})
req.end()
})
}
/**
* get方法
*
* @param option - 参数
* @param option.url - 请求链接
* @returns Promise - 请求结果
*/
public async get({ url }: any) {
return await this.request('GET', url)
}
/**
* post方法
*
* @param option - 参数
* @param option.url - 请求链接
* @param option.params - 请求参数
* @returns Promise - 请求结果
*/
public async post({ url, params }: any) {
return await this.request('POST', url, params)
}
}

module.exports = request
module.exports = new Request()
1 change: 1 addition & 0 deletions docs/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
## 2021.11.30 v2.14.4 更新日志

1. 替换`curl`脚本,处理win7不能执行curl的兼容问题
2. 封装`request`方法

## 2021.11.28 v2.14.3 更新日志

Expand Down
2 changes: 1 addition & 1 deletion lib/core/api/getUserToken.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ async function getUserToken() {
sh.echo(error("\u8BF7\u8BBE\u7F6E\u672C\u5730git\u7528\u6237\u540D"));
process.exit(1);
}
const fetchData = (await request({ url: `${config.api}?name=${user}` })).data || null;
const fetchData = (await request.get({ url: `${config.api}?name=${user}` })).data || null;
if (!fetchData) {
sh.echo(error("\u6CA1\u6709\u627E\u5230\u7528\u6237\uFF0C\u8BF7\u8054\u7CFB\u7BA1\u7406\u5458"));
process.exit(1);
Expand Down
125 changes: 84 additions & 41 deletions lib/core/request.js
Original file line number Diff line number Diff line change
@@ -1,48 +1,91 @@
'use strict';

var __defProp = Object.defineProperty;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
const https = require("https");
const http = require("http");
const zlib = require("zlib");
const { URL } = require("url");
function request(options) {
const url = new URL(options.url);
return new Promise((resolve, reject) => {
const req = https.request(__spreadValues({
hostname: url.hostname,
port: url.port,
path: `${url.pathname}${url.search}`,
method: "GET"
}, options), (res) => {
res.on("data", (buf) => {
const data = Buffer.from(buf).toString();
let result = null;
try {
result = JSON.parse(data);
} catch (e) {
}
if (result.code === 0) {
resolve(result);
} else {
reject(result);
}
const qs = require("qs");
class Request {
constructor() {
this.cookies = [];
}
getHeaders(host, postData) {
const headers = {
Host: host,
rejectUnauthorized: false,
Pragma: "no-cache",
Connection: "keep-alive",
"Cache-Control": "no-cache",
"Content-Type": "application/x-www-form-urlencoded",
"Accept-Language": "zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4,es;q=0.2",
Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Safari/537.36"
};
if (this.cookies.length) {
headers.Cookie = this.cookies.join("; ");
}
if (postData) {
headers["Content-Length"] = Buffer.byteLength(postData);
}
return headers;
}
setCookie(cookie) {
const cookies = cookie.split(";");
for (let item of cookies) {
item = item.replace(/^\s/, "");
this.cookies.push(item);
}
return this;
}
request(method, url, params) {
const postData = qs.stringify(params || {}, {
arrayFormat: "indices",
allowDots: true
});
const urlObj = new URL(url);
const options = {
hostname: urlObj.hostname,
port: urlObj.port,
path: urlObj.pathname + urlObj.search,
method,
headers: this.getHeaders(urlObj.host, postData)
};
return new Promise((resolve, reject) => {
const req = (urlObj.protocol == "http:" ? http : https).request(options, (res) => {
const chunks = [];
res.on("data", (buf) => {
chunks.push(buf);
});
res.on("end", () => {
const buffer = Buffer.concat(chunks);
const encoding = res.headers["content-encoding"];
if (encoding === "gzip") {
zlib.gunzip(buffer, function(err, decoded) {
resolve(decoded.toString());
});
} else if (encoding === "deflate") {
zlib.inflate(buffer, function(err, decoded) {
resolve(decoded.toString());
});
} else {
resolve(JSON.parse(buffer.toString()));
}
});
});
req.on("error", (err) => {
reject(err);
});
if (postData) {
req.write(postData);
}
req.end();
});
req.on("error", reject);
req.end();
});
}
async get({ url }) {
return await this.request("GET", url);
}
async post({ url, params }) {
return await this.request("POST", url, params);
}
}
module.exports = request;
module.exports = new Request();
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -65,12 +65,14 @@
"node-pty": "^0.10.1",
"ora": "^5.4.1",
"os": "^0.1.2",
"qs": "^6.10.1",
"shelljs": "^0.8.4",
"slash": "^3.0.0",
"socket.io": "4.4.0",
"text-table": "^0.2.0",
"tracer": "1.1.5",
"uuid": "^8.3.2"
"uuid": "^8.3.2",
"zlib": "^1.0.5"
},
"devDependencies": {
"@microsoft/api-extractor": "^8.0.0",
Expand Down
3 changes: 1 addition & 2 deletions script/lib.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* @Author:
* @LastEditors: saqqdy
* @Date: 2021-07-22 22:39:42
* @LastEditTime: 2021-07-23 00:00:12
* @LastEditTime: 2021-11-30 14:41:08
*/
const fs = require('fs')
const path = require('path')
Expand All @@ -23,7 +23,6 @@ const readDir = entry => {
})
}
const getInfo = url => {
console.log(url, url.replace(/^bin\//, 'lib/'))
builder
.build({
entryPoints: [url],
Expand Down

1 comment on commit 4bff905

@vercel
Copy link

@vercel vercel bot commented on 4bff905 Nov 30, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.