diff --git a/packages/client/__tests__/fixtures/server.ts b/packages/client/__tests__/fixtures/server.ts index dade8cd..fa0ccdb 100644 --- a/packages/client/__tests__/fixtures/server.ts +++ b/packages/client/__tests__/fixtures/server.ts @@ -6,11 +6,11 @@ import formidable from 'formidable'; const createServer = async (port: number, host: string) => { return new Promise((resolve) => { - let server = http + const server = http .createServer(async (req, res) => { - // 处理CORS - res.setHeader('Access-Control-Allow-Origin', "*"); - res.setHeader('Access-Control-Allow-Credentials', "*"); + // 处理CORS + res.setHeader('Access-Control-Allow-Origin', '*'); + res.setHeader('Access-Control-Allow-Credentials', '*'); res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS'); res.setHeader('Access-Control-Allow-Headers', '*'); @@ -39,16 +39,16 @@ const createServer = async (port: number, host: string) => { } // 也可以用searchParams - let query = (url.parse(req.url!).query || '') + const query = (url.parse(req.url!).query || '') .split('&') .filter(i => !!i) .reduce((pre, cur) => { - let [key, value] = cur.split('='); + const [key, value] = cur.split('='); pre[key] = decodeURIComponent(value); return pre; }, {}); - + let body = {}; if (req.method === 'POST' || req.method === 'DELETE' || req.method === 'PUT') { @@ -60,7 +60,7 @@ const createServer = async (port: number, host: string) => { .then(([fields, files]) => { let response = JSON.parse(fields?.response?.[0] || null); if (!response && files && Object.keys(files).length) { - let file = files[Object.keys(files)[0]][0]; + const file = files[Object.keys(files)[0]][0]; response = JSON.parse(fs.readFileSync(file.filepath).toString())?.response; } resolve$({ response }); @@ -69,10 +69,10 @@ const createServer = async (port: number, host: string) => { resolve$({ response: { status: 0, body: e } }); }); return; - } + } let postData = ''; - req.on('data', chunk => { + req.on('data', (chunk) => { postData += chunk; }); req.on('end', async () => { @@ -80,7 +80,7 @@ const createServer = async (port: number, host: string) => { resolve$(JSON.parse(postData.toString() || '{}')); } catch (e) { try { - let data = new URLSearchParams(postData.toString()); + const data = new URLSearchParams(postData.toString()); resolve$({ response: JSON.parse(data.get('response')!) }); } catch { resolve$({ response: { status: 0 } }); @@ -90,17 +90,17 @@ const createServer = async (port: number, host: string) => { }); } - let { - delay = 0.1, - response = JSON.stringify({ - method: req.method, + const { + delay = 0.1, + response = JSON.stringify({ + method: req.method, url: req.url, reuqest: body }) } = { ...query, ...body }; - response = typeof response === 'string' ? response : JSON.stringify(response); - setTimeout(() => res.end(response), delay * 1000); + const response$ = typeof response === 'string' ? response : JSON.stringify(response); + setTimeout(() => res.end(response$), delay * 1000); }); server.listen({ port, host }, () => { @@ -127,11 +127,10 @@ export const impl = async () => { return baseUrl; }; - if (typeof beforeAll === 'undefined') { (async () => { const { port, host, baseUrl } = await Server.available(); await createServer(port as number, host); console.log(baseUrl); })(); -} \ No newline at end of file +} diff --git a/packages/client/__tests__/index.spec.ts b/packages/client/__tests__/index.spec.ts index bff721e..6fac642 100644 --- a/packages/client/__tests__/index.spec.ts +++ b/packages/client/__tests__/index.spec.ts @@ -21,4 +21,4 @@ describe('index.ts', async () => { expect(Network3.request.onRequest.length).toBe(1); expect(Network3.request.onResponse.length).toBe(1); }); -}); \ No newline at end of file +}); diff --git a/packages/client/__tests__/limit.spec.ts b/packages/client/__tests__/limit.spec.ts index a96f42a..97444ef 100644 --- a/packages/client/__tests__/limit.spec.ts +++ b/packages/client/__tests__/limit.spec.ts @@ -9,7 +9,7 @@ describe('limit.ts', async () => { const { body } = leaf.response!; if ( - !body + !body || (body && typeof body.status !== 'number') ) { leaf.response!.statusText = `response.body must be a json.`; @@ -43,7 +43,7 @@ describe('limit.ts', async () => { data: {} } }; - const response = await Network.http(serverUrl, { + const response = await Network.http(serverUrl, { method: 'POST', body }); @@ -64,7 +64,7 @@ describe('limit.ts', async () => { } }; try { - await Network.http(serverUrl, { + await Network.http(serverUrl, { method: 'POST', body }); @@ -81,7 +81,7 @@ describe('limit.ts', async () => { } }; try { - await Network.http(serverUrl, { + await Network.http(serverUrl, { method: 'POST', body }); @@ -89,4 +89,4 @@ describe('limit.ts', async () => { expect(response.statusText).toBe('HTTP_CANCEL'); } }); -}); \ No newline at end of file +}); diff --git a/packages/client/__tests__/native.spec.ts b/packages/client/__tests__/native.spec.ts index 94424be..bdac55d 100644 --- a/packages/client/__tests__/native.spec.ts +++ b/packages/client/__tests__/native.spec.ts @@ -7,11 +7,11 @@ describe.skip('request.ts', async () => { const launch = E2E.impl(); const baseUrl = `file://${resolve(__dirname, './fixtures/native.html')}`; const methods = [ - 'string', - 'blob', - 'file', - 'formData', - 'arrayBuffer', + 'string', + 'blob', + 'file', + 'formData', + 'arrayBuffer', 'files', 'URLSearchParams' ]; @@ -28,7 +28,7 @@ describe.skip('request.ts', async () => { task$ = task$ .then(() => operater.setValue(`#${id}`, api)) .then(() => page.waitForResponse(v => v.url() === api)) - .then((e) => e.json()) + .then(e => e.json()) .then((e) => { expect(e).toEqual({ status: 1, data: {} }); }); @@ -38,4 +38,4 @@ describe.skip('request.ts', async () => { return task; }, Promise.resolve()); }); -}); \ No newline at end of file +}); diff --git a/packages/client/__tests__/provider-fetch.spec.ts b/packages/client/__tests__/provider-fetch.spec.ts index 880d987..2d167aa 100644 --- a/packages/client/__tests__/provider-fetch.spec.ts +++ b/packages/client/__tests__/provider-fetch.spec.ts @@ -26,7 +26,7 @@ describe('fetch.ts', async () => { data: {} } }; - const response = await Network.http(serverUrl, { + const response = await Network.http(serverUrl, { timeout: 0, method: 'POST', body @@ -47,7 +47,7 @@ describe('fetch.ts', async () => { data: {} } }; - const response = await Network.http(serverUrl, { + const response = await Network.http(serverUrl, { method: 'DELETE', body }); @@ -67,7 +67,7 @@ describe('fetch.ts', async () => { data: {} } }; - const response = await Network.http(serverUrl, { + const response = await Network.http(serverUrl, { method: 'PUT', body }); @@ -82,7 +82,7 @@ describe('fetch.ts', async () => { it('timeout', async () => { try { - await Network.http(serverUrl, { + await Network.http(serverUrl, { method: 'PUT', timeout: 100 }); @@ -93,7 +93,7 @@ describe('fetch.ts', async () => { it('cancel', async () => { try { - const leaf = Network.http(serverUrl, { + const leaf = Network.http(serverUrl, { method: 'PUT', }); setTimeout(() => leaf.cancel()); @@ -141,7 +141,7 @@ describe('fetch.ts', async () => { }); it('headers', async () => { - let headers = {}; + const headers = {}; // eslint-disable-next-line no-proto (headers as any).__proto__['Cookie'] = 'any'; (headers as any)['Cookies'] = ''; @@ -157,4 +157,4 @@ describe('fetch.ts', async () => { expect(e.status).toBe(500); } }); -}); \ No newline at end of file +}); diff --git a/packages/client/__tests__/provider-jsonp.spec.ts b/packages/client/__tests__/provider-jsonp.spec.ts index bef9330..36bd47c 100644 --- a/packages/client/__tests__/provider-jsonp.spec.ts +++ b/packages/client/__tests__/provider-jsonp.spec.ts @@ -41,4 +41,4 @@ describe('jsonp.ts', async () => { (window as any)[jsonp]({}); } }); -}); \ No newline at end of file +}); diff --git a/packages/client/__tests__/provider-xhr.spec.ts b/packages/client/__tests__/provider-xhr.spec.ts index 9fcb5b3..aa6e62b 100644 --- a/packages/client/__tests__/provider-xhr.spec.ts +++ b/packages/client/__tests__/provider-xhr.spec.ts @@ -28,7 +28,7 @@ describe('xhr.ts', async () => { data: {} } }; - const response = await Network.http(serverUrl, { + const response = await Network.http(serverUrl, { method: 'POST', body }); @@ -48,7 +48,7 @@ describe('xhr.ts', async () => { data: {} } }; - const response = await Network.http(serverUrl, { + const response = await Network.http(serverUrl, { method: 'DELETE', body }); @@ -68,7 +68,7 @@ describe('xhr.ts', async () => { data: {} } }; - const response = await Network.http(serverUrl, { + const response = await Network.http(serverUrl, { method: 'PUT', body }); @@ -83,7 +83,7 @@ describe('xhr.ts', async () => { it('timeout', async () => { try { - await Network.http(serverUrl, { + await Network.http(serverUrl, { method: 'PUT', timeout: 100 }); @@ -94,7 +94,7 @@ describe('xhr.ts', async () => { it('cancel', async () => { try { - const leaf = Network.http(serverUrl, { + const leaf = Network.http(serverUrl, { method: 'PUT', }); setTimeout(() => leaf.cancel()); @@ -157,7 +157,7 @@ describe('xhr.ts', async () => { }); it('headers', async () => { - let headers = {}; + const headers = {}; // eslint-disable-next-line no-proto (headers as any).__proto__['Cookie'] = 'any'; (headers as any)['Cookies'] = ''; @@ -184,4 +184,4 @@ describe('xhr.ts', async () => { } }); }); -}); \ No newline at end of file +}); diff --git a/packages/client/src/fetch.ts b/packages/client/src/fetch.ts index 9e9bd5a..3145b74 100644 --- a/packages/client/src/fetch.ts +++ b/packages/client/src/fetch.ts @@ -1,23 +1,22 @@ -import type { HTTPProvider } from "@deot/http-core"; -import { HTTPRequest, HTTPResponse, HTTPHeaders, HTTPShellLeaf, ERROR_CODE } from "@deot/http-core"; +import type { HTTPProvider } from '@deot/http-core'; +import { HTTPRequest, HTTPResponse, HTTPHeaders, HTTPShellLeaf, ERROR_CODE } from '@deot/http-core'; export const provider: HTTPProvider = (request: HTTPRequest, leaf: HTTPShellLeaf) => { return new Promise((resolve, reject) => { const { url, headers, body, credentials, method, timeout, responseType, ...fetchOptions } = request; - const controller = new AbortController(); - let timer = timeout + let timer = timeout ? setTimeout(() => { controller.abort(); onError(ERROR_CODE.HTTP_REQUEST_TIMEOUT); }, timeout) : null; - let response: Response; + let response: Response; const getExtra = () => { - let headers$ = new HTTPHeaders(); + const headers$ = new HTTPHeaders(); if (response) { response.headers.forEach((v, k) => headers$.set(k, v, true)); } @@ -37,9 +36,9 @@ export const provider: HTTPProvider = (request: HTTPRequest, leaf: HTTPShellLeaf }; const onSuccess = (body$: any) => { - resolve(new HTTPResponse({ + resolve(new HTTPResponse({ ...getExtra(), - body: body$ + body: body$ })); timer && clearTimeout(timer); timer = null; @@ -60,7 +59,7 @@ export const provider: HTTPProvider = (request: HTTPRequest, leaf: HTTPShellLeaf }).then((res) => { response = res; if (res.status >= 200 && res.status < 300) { - let fn = res[responseType || 'text']; + const fn = res[responseType || 'text']; if (!fn) return onSuccess(res); fn.call(res) .then((data: any) => { @@ -76,7 +75,7 @@ export const provider: HTTPProvider = (request: HTTPRequest, leaf: HTTPShellLeaf return res; }).catch((e) => { onError(ERROR_CODE.HTTP_STATUS_ERROR, e); - // no throw again, avoid unhandled error + // no throw again, avoid unhandled error }); // rebuild cancel @@ -88,4 +87,4 @@ export const provider: HTTPProvider = (request: HTTPRequest, leaf: HTTPShellLeaf leaf.server = fetch$; }); -}; \ No newline at end of file +}; diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts index 6d42c9b..1ee8790 100644 --- a/packages/client/src/index.ts +++ b/packages/client/src/index.ts @@ -1,7 +1,7 @@ -import { HTTPController } from "@deot/http-core"; -import type { HTTPRequestOptions } from "@deot/http-core"; +import { HTTPController } from '@deot/http-core'; +import type { HTTPRequestOptions } from '@deot/http-core'; import { onRequest, onResponse } from '@deot/http-hooks'; -import { provider } from "./provider"; +import { provider } from './provider'; export const createInstance = (options: HTTPRequestOptions = {}) => { const onBaseRequest = (Array.isArray(options.onRequest) ? options.onRequest : (options.onRequest ? [options.onRequest] : [])); @@ -16,4 +16,4 @@ export const createInstance = (options: HTTPRequestOptions = {}) => { return client; }; -export const Network = createInstance({} as HTTPRequestOptions); \ No newline at end of file +export const Network = createInstance({} as HTTPRequestOptions); diff --git a/packages/client/src/jsonp.ts b/packages/client/src/jsonp.ts index 48e197c..e956cdb 100644 --- a/packages/client/src/jsonp.ts +++ b/packages/client/src/jsonp.ts @@ -1,5 +1,5 @@ -import type { HTTPProvider } from "@deot/http-core"; -import { HTTPRequest, HTTPResponse, ERROR_CODE } from "@deot/http-core"; +import type { HTTPProvider } from '@deot/http-core'; +import { HTTPRequest, HTTPResponse, ERROR_CODE } from '@deot/http-core'; export const provider: HTTPProvider = (request: HTTPRequest) => { return new Promise((resolve, reject) => { @@ -13,10 +13,10 @@ export const provider: HTTPProvider = (request: HTTPRequest) => { value: (body: any) => resolve(new HTTPResponse({ body })) }); - let script = document.createElement("script"); - let head = document.getElementsByTagName("head")[0]; + const script = document.createElement('script'); + const head = document.getElementsByTagName('head')[0]; script.src = url; head.appendChild(script); }); -}; \ No newline at end of file +}; diff --git a/packages/client/src/provider.ts b/packages/client/src/provider.ts index 4812efa..b385ccf 100644 --- a/packages/client/src/provider.ts +++ b/packages/client/src/provider.ts @@ -1,7 +1,7 @@ -import type { HTTPProvider } from "@deot/http-core"; -import { provider as XHRProvider } from "./xhr"; -import { provider as FetchProvider } from "./fetch"; -import { provider as JSONProvider } from "./jsonp"; +import type { HTTPProvider } from '@deot/http-core'; +import { provider as XHRProvider } from './xhr'; +import { provider as FetchProvider } from './fetch'; +import { provider as JSONProvider } from './jsonp'; export const provider: HTTPProvider = (request, leaf) => { if (request.jsonp) { @@ -10,4 +10,4 @@ export const provider: HTTPProvider = (request, leaf) => { return request.useXHR || !(window?.fetch) ? XHRProvider(request, leaf) : FetchProvider(request, leaf); -}; \ No newline at end of file +}; diff --git a/packages/client/src/xhr.ts b/packages/client/src/xhr.ts index d278f54..e690ebc 100644 --- a/packages/client/src/xhr.ts +++ b/packages/client/src/xhr.ts @@ -1,5 +1,5 @@ -import type { HTTPProvider } from "@deot/http-core"; -import { HTTPHeaders, HTTPResponse, ERROR_CODE } from "@deot/http-core"; +import type { HTTPProvider } from '@deot/http-core'; +import { HTTPHeaders, HTTPResponse, ERROR_CODE } from '@deot/http-core'; const ignoreDuplicateOf = { 'age': !0, @@ -32,12 +32,12 @@ const parseHeaders = (rawHeaders: string) => { key = line.substring(0, i).trim().toLowerCase(); val = line.substring(i + 1).trim(); - /* istanbul ignore next -- @preserve */ + /* istanbul ignore next -- @preserve */ if (!key || (parsed[key] && ignoreDuplicateOf[key])) { return; } - /* istanbul ignore next -- @preserve */ + /* istanbul ignore next -- @preserve */ if (key === 'set-cookie') { if (parsed[key]) { parsed[key].push(val); @@ -56,8 +56,8 @@ export const provider: HTTPProvider = (request, leaf) => { return new Promise((resolve, reject) => { const { onDownloadProgress, onUploadProgress, responseType, timeout, credentials, body, headers, method, url, async = true } = request; - let xhr = new XMLHttpRequest(); - + const xhr = new XMLHttpRequest(); + const getExtra = () => { return { status: xhr.status, @@ -73,9 +73,9 @@ export const provider: HTTPProvider = (request, leaf) => { }; const onSuccess = (body$: any) => { - resolve(new HTTPResponse({ + resolve(new HTTPResponse({ ...getExtra(), - body: body$ + body: body$ })); }; @@ -91,12 +91,12 @@ export const provider: HTTPProvider = (request, leaf) => { ) return; if (xhr.status >= 200 && xhr.status < 300) { - const response = !xhr.responseType - ? xhr.responseText + const response = !xhr.responseType + ? xhr.responseText : xhr.response; - xhr.responseType && response === null - ? onError(ERROR_CODE.HTTP_RESPONSE_PARSING_FAILED) + xhr.responseType && response === null + ? onError(ERROR_CODE.HTTP_RESPONSE_PARSING_FAILED) : onSuccess(response); } else { onError(ERROR_CODE.HTTP_STATUS_ERROR); @@ -113,7 +113,7 @@ export const provider: HTTPProvider = (request, leaf) => { /* istanbul ignore next -- @preserve */ xhr.withCredentials = credentials === 'omit' ? false : !!credentials; timeout && (xhr.timeout = timeout); - responseType && (xhr.responseType = responseType); + responseType && (xhr.responseType = responseType); for (const h in headers.toJSON()) { xhr.setRequestHeader(h, headers[h]); @@ -130,4 +130,4 @@ export const provider: HTTPProvider = (request, leaf) => { leaf.server = xhr; }); -}; \ No newline at end of file +}; diff --git a/packages/core/README.md b/packages/core/README.md index afc6385..0e01a02 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -20,7 +20,7 @@ const Network = new HTTPController({ onRequest(leaf) { const request = new HTTPRequest(leaf.request); if (request.url && !/[a-zA-z]+:\/\/[^\s]*/.test(request.url)) { - let [key, query] = request.url.split('?'); // 避免before带上?token=*之类 + const [key, query] = request.url.split('?'); // 避免before带上?token=*之类 request.url = `${apis[key] ? `${baseURL}${apis[key]}` : ''}${query ? `?${query}` : ''}`; } return request; diff --git a/packages/core/__tests__/controller.spec.ts b/packages/core/__tests__/controller.spec.ts index 28b5680..b8463a9 100644 --- a/packages/core/__tests__/controller.spec.ts +++ b/packages/core/__tests__/controller.spec.ts @@ -5,8 +5,8 @@ describe('controller.ts', () => { provider: (request: HTTPRequest) => { return new Promise((resolve, reject) => { setTimeout(() => { - request.reject - ? reject(HTTPResponse.error('', request)) + request.reject + ? reject(HTTPResponse.error('', request)) : resolve(new HTTPResponse({ body: request.body })); }, 300); }); @@ -30,7 +30,7 @@ describe('controller.ts', () => { onRequest(leaf) { const request = new HTTPRequest(leaf.request); if (request.url && !/[a-zA-z]+:\/\/[^\s]*/.test(request.url)) { - let [key, query] = request.url.split('?'); // 避免before带上?token=*之类 + const [key, query] = request.url.split('?'); // 避免before带上?token=*之类 request.url = `${apis[key] ? `${baseURL}${apis[key]}` : ''}${query ? `?${query}` : ''}`; } @@ -180,7 +180,7 @@ describe('controller.ts', () => { shell.send().catch((e) => { expect(e.statusText).toBe('HTTP_CANCEL'); }); - + await Network.cancel(); expect(Network.shells.length).toBe(0); expect(Object.keys(shell.leafs).length).toBe(0); @@ -194,7 +194,7 @@ describe('controller.ts', () => { leaf.catch((e) => { expect(e.statusText).toBe('HTTP_CANCEL'); }); - + await Network.cancel(); expect(Network.shells.length).toBe(0); expect(Object.keys(shell.leafs).length).toBe(0); @@ -341,7 +341,7 @@ describe('controller.ts', () => { it('maxTries', async () => { let count = 0; - let maxTries = 10; + const maxTries = 10; const body = { status: 1, data: {} @@ -436,4 +436,4 @@ describe('controller.ts', () => { expect(count).toBe(1); }); -}); \ No newline at end of file +}); diff --git a/packages/core/__tests__/headers.spec.ts b/packages/core/__tests__/headers.spec.ts index 68060d7..635199f 100644 --- a/packages/core/__tests__/headers.spec.ts +++ b/packages/core/__tests__/headers.spec.ts @@ -18,13 +18,12 @@ describe('headers.ts', () => { headers.set('c', null, true); expect(headers.toJSON()).toEqual({ b: 'b' }); - headers.set({ 'b': null }); + headers.set({ b: null }); expect(headers.toJSON()).toEqual({ b: 'b' }); - headers.set({ 'b': null }, true); + headers.set({ b: null }, true); expect(headers.toJSON()).toEqual({}); expect(Object.prototype.toString.call(headers)).toBe(`[object HTTPHeaders]`); }); - -}); \ No newline at end of file +}); diff --git a/packages/core/__tests__/request.spec.ts b/packages/core/__tests__/request.spec.ts index 4a42a9b..a173602 100644 --- a/packages/core/__tests__/request.spec.ts +++ b/packages/core/__tests__/request.spec.ts @@ -8,4 +8,4 @@ describe('request.ts', () => { // extra value expect(request.allowExtraKey).toBe(true); }); -}); \ No newline at end of file +}); diff --git a/packages/core/__tests__/response.spec.ts b/packages/core/__tests__/response.spec.ts index 1d0c7e0..ad929b5 100644 --- a/packages/core/__tests__/response.spec.ts +++ b/packages/core/__tests__/response.spec.ts @@ -10,4 +10,4 @@ describe('response.ts', () => { // extra value expect(response.allowExtraKey).toBe(true); }); -}); \ No newline at end of file +}); diff --git a/packages/core/src/controller.ts b/packages/core/src/controller.ts index a91352a..57b7a0e 100644 --- a/packages/core/src/controller.ts +++ b/packages/core/src/controller.ts @@ -1,8 +1,8 @@ -import type { HTTPRequestOptions } from "./request"; -import { HTTPRequest } from "./request"; +import type { HTTPRequestOptions } from './request'; +import { HTTPRequest } from './request'; -import { HTTPShell } from "./shell"; -import type { HTTPShellLeaf } from "./shell-leaf"; +import { HTTPShell } from './shell'; +import type { HTTPShellLeaf } from './shell-leaf'; export class HTTPController { request: HTTPRequest; @@ -17,12 +17,12 @@ export class HTTPController { /** * 发起一个请求,返回Promise - * @param {string|HTTPRequest|HTTPRequestOptions} url ~ - * @param {HTTPRequestOptions} requestOptions ~ - * @returns {HTTPShellLeaf} ~ + * @param url ~ + * @param requestOptions ~ + * @returns ~ */ http( - url: string | HTTPRequest | HTTPRequestOptions, + url: string | HTTPRequest | HTTPRequestOptions, requestOptions?: HTTPRequestOptions, ): HTTPShellLeaf { const shell = new HTTPShell(url, requestOptions, this); @@ -32,12 +32,12 @@ export class HTTPController { /** * 发起一个请求,返回HttpShell, 支持单个重复发送,取消操作 - * @param {string|HTTPRequest|HTTPRequestOptions} url ~ - * @param {HTTPRequestOptions} requestOptions ~ - * @returns {HTTPShell} ~ + * @param url ~ + * @param requestOptions ~ + * @returns ~ */ custom( - url: string | HTTPRequest | HTTPRequestOptions, + url: string | HTTPRequest | HTTPRequestOptions, requestOptions?: HTTPRequestOptions, ): HTTPShell { const shell = new HTTPShell(url, requestOptions, this); @@ -47,7 +47,7 @@ export class HTTPController { /** * 取消所有请求或取消指定请求 - * @param {string|HTTPShellLeaf} id ~ + * @param id ~ */ async cancel(id?: string | HTTPShellLeaf) { await this.shells.reduce((pre, shell) => { @@ -71,4 +71,4 @@ export class HTTPController { _remove(shell: HTTPShell) { this.shells = this.shells.filter(i => i !== shell); } -} \ No newline at end of file +} diff --git a/packages/core/src/error.ts b/packages/core/src/error.ts index 8bd87ff..1b427ec 100644 --- a/packages/core/src/error.ts +++ b/packages/core/src/error.ts @@ -7,4 +7,4 @@ export const ERROR_CODE = { HTTP_STATUS_ERROR: 'HTTP_STATUS_ERROR', HTTP_CODE_ILLEGAL: 'HTTP_CODE_ILLEGAL', HTTP_RESPONSE_PARSING_FAILED: 'HTTP_RESPONSE_PARSING_FAILED' -}; \ No newline at end of file +}; diff --git a/packages/core/src/headers.ts b/packages/core/src/headers.ts index 8db2773..9044ac4 100644 --- a/packages/core/src/headers.ts +++ b/packages/core/src/headers.ts @@ -13,8 +13,8 @@ export class HTTPHeaders { set(key: string, value: any, rewrite?: boolean): HTTPHeaders; set(keyOrHeaders: string | Headers, valueOrRewrite: any, rewrite?: boolean) { if (typeof keyOrHeaders === 'string') { - let key = keyOrHeaders; - let value = valueOrRewrite; + const key = keyOrHeaders; + const value = valueOrRewrite; this[key] = rewrite ? value : (this[key] || value); } else { let headers = keyOrHeaders; @@ -26,7 +26,7 @@ export class HTTPHeaders { headers = { ...headers }; } - Object.keys(headers).forEach(k => { + Object.keys(headers).forEach((k) => { this.set(k, headers[k], rewrite); }); } @@ -57,4 +57,4 @@ export class HTTPHeaders { get [Symbol.toStringTag]() { return 'HTTPHeaders'; } -} \ No newline at end of file +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index b04db0e..9627b4f 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -5,4 +5,4 @@ export * from './response'; export * from './shell'; export * from './shell-leaf'; export * from './error'; -export * from './headers'; \ No newline at end of file +export * from './headers'; diff --git a/packages/core/src/provider.ts b/packages/core/src/provider.ts index 3fd2bcf..c10122e 100644 --- a/packages/core/src/provider.ts +++ b/packages/core/src/provider.ts @@ -1,7 +1,7 @@ -import type { HTTPRequest } from "./request"; -import type { HTTPResponse } from "./response"; -import type { HTTPShellLeaf } from "./shell-leaf"; +import type { HTTPRequest } from './request'; +import type { HTTPResponse } from './response'; +import type { HTTPShellLeaf } from './shell-leaf'; export interface HTTPProvider { (request: HTTPRequest, leaf: HTTPShellLeaf): Promise; -} \ No newline at end of file +} diff --git a/packages/core/src/request.ts b/packages/core/src/request.ts index 290c1f4..1b87154 100644 --- a/packages/core/src/request.ts +++ b/packages/core/src/request.ts @@ -72,7 +72,7 @@ export class HTTPRequest { provider!: HTTPProvider; constructor( - url: string | HTTPRequest | HTTPRequestOptions, + url: string | HTTPRequest | HTTPRequestOptions, options?: HTTPRequestOptions, parent?: HTTPRequest ) { @@ -97,12 +97,12 @@ export class HTTPRequest { provider: defaultProvider }; const isUrlAsOptions = url && (url.constructor === Object || url instanceof HTTPRequest); - const kv = isUrlAsOptions - ? { ...defaults, ...parent, ...(url as (HTTPRequest | HTTPRequestOptions)), ...options } + const kv = isUrlAsOptions + ? { ...defaults, ...parent, ...(url as (HTTPRequest | HTTPRequestOptions)), ...options } : { ...defaults, ...parent, url, ...options }; Object.keys(kv).forEach((key) => { - const v = typeof kv[key] !== 'undefined' + const v = typeof kv[key] !== 'undefined' ? kv[key] : defaults[key]; this[key] = key === 'headers' ? new HTTPHeaders(v) : v; @@ -127,4 +127,4 @@ export class HTTPRequest { // formData() {} // json() {} // text() {} -} \ No newline at end of file +} diff --git a/packages/core/src/response.ts b/packages/core/src/response.ts index 05df51d..5f4aa59 100644 --- a/packages/core/src/response.ts +++ b/packages/core/src/response.ts @@ -35,7 +35,7 @@ export class HTTPResponse { // Custom constructor( - body?: BodyInit | null | HTTPResponse | HTTPResponseOptions, + body?: BodyInit | null | HTTPResponse | HTTPResponseOptions, options?: HTTPResponseOptions ) { const defaults = { @@ -51,13 +51,13 @@ export class HTTPResponse { }; const isBodyAsOptions = body && (body.constructor === Object || body instanceof HTTPResponse); - const kv = isBodyAsOptions - ? { ...defaults, ...(body as (HTTPResponse | HTTPResponseOptions)), ...options } + const kv = isBodyAsOptions + ? { ...defaults, ...(body as (HTTPResponse | HTTPResponseOptions)), ...options } : { ...defaults, body, ...options }; Object.keys(kv).forEach((key) => { - let v = typeof kv[key] !== 'undefined' - ? kv[key] + const v = typeof kv[key] !== 'undefined' + ? kv[key] : defaults[key]; this[key] = key === 'headers' ? new HTTPHeaders(v) : v; }); @@ -81,4 +81,4 @@ export class HTTPResponse { // formData() {} // json() {} // text() {} -} \ No newline at end of file +} diff --git a/packages/core/src/shell-leaf.ts b/packages/core/src/shell-leaf.ts index 5db09ad..9d879b8 100644 --- a/packages/core/src/shell-leaf.ts +++ b/packages/core/src/shell-leaf.ts @@ -1,13 +1,13 @@ import { getUid } from './utils'; -import { HTTPRequest } from "./request"; -import type { HTTPResponse } from "./response"; +import { HTTPRequest } from './request'; +import type { HTTPResponse } from './response'; type PromiseHook = (response: HTTPResponse) => any; export class HTTPShellLeaf { id = getUid(`shell.leaf`); cancel!: () => Promise; - + timeout?: ReturnType; /** @@ -54,4 +54,4 @@ export class HTTPShellLeaf { finally(callback?: () => void) { return this.target.finally(callback); } -} \ No newline at end of file +} diff --git a/packages/core/src/shell.ts b/packages/core/src/shell.ts index 7fbc6d4..911775d 100644 --- a/packages/core/src/shell.ts +++ b/packages/core/src/shell.ts @@ -1,13 +1,13 @@ /* eslint-disable no-promise-executor-return */ /* eslint-disable no-dupe-class-members */ /* eslint-disable lines-between-class-members */ -import type { HTTPController } from "./controller"; +import type { HTTPController } from './controller'; -import { HTTPRequest } from "./request"; -import { HTTPResponse } from "./response"; -import { HTTPShellLeaf } from "./shell-leaf"; +import { HTTPRequest } from './request'; +import { HTTPResponse } from './response'; +import { HTTPShellLeaf } from './shell-leaf'; import { ERROR_CODE } from './error'; -import type { HTTPRequestOptions, HTTPHook } from "./request"; +import type { HTTPRequestOptions, HTTPHook } from './request'; export class HTTPShell { parent: HTTPController; @@ -19,7 +19,7 @@ export class HTTPShell { isPending = false; // 用于控制多个send时,只执行一次onStart/onFinish constructor( - url: string | HTTPRequest | HTTPRequestOptions, + url: string | HTTPRequest | HTTPRequestOptions, requestOptions: HTTPRequestOptions | undefined, parent: HTTPController ) { @@ -37,7 +37,7 @@ export class HTTPShell { const cancel = new Promise((_, reject) => { leaf.cancel = async () => { reject(this.error(leaf, ERROR_CODE.HTTP_CANCEL)); - await new Promise(resolve => { + await new Promise((resolve) => { leaf.target.catch(() => {}).finally(resolve); }); }; @@ -88,7 +88,7 @@ export class HTTPShell { .then(onSuccess) .catch(onError); } - + return isError ? onError(error || response) : onSuccess(response); }); }); @@ -106,7 +106,7 @@ export class HTTPShell { pre = pre .then(() => { if (!needBreak) { - let result = fn(leaf); + const result = fn(leaf); // leaf含then方法是基于leaf.target 所以不能直接返回leaf return result === leaf || result; } @@ -140,8 +140,8 @@ export class HTTPShell { /** * 请求完成后清理,避免内存泄漏 - * @param {string|HTTPShellLeaf} id 当前请求或当前请求id - * @returns {Promise} ~ + * @param id 当前请求或当前请求id + * @returns ~ */ async cancel(id?: string | HTTPShellLeaf): Promise { if (id) { @@ -159,8 +159,8 @@ export class HTTPShell { /** * 请求前完成触发,在onRequest之前 - * @param {HTTPShellLeaf} leaf 当前请求 - * @returns {Promise} ~ + * @param leaf 当前请求 + * @returns ~ */ async loading(leaf: HTTPShellLeaf): Promise { const { localData, onStart } = leaf.originalRequest; @@ -173,8 +173,8 @@ export class HTTPShell { /** * 请求完成触发, 在onResponse之后 - * @param {HTTPShellLeaf} leaf 当前请求 - * @returns {Promise} ~ + * @param leaf 当前请求 + * @returns ~ */ async loaded(leaf: HTTPShellLeaf): Promise { const { localData, onFinish } = leaf.originalRequest; @@ -188,13 +188,13 @@ export class HTTPShell { /** * 请求前处理,可修改请求信息,或根据结果全局事务 - * @param {HTTPShellLeaf} leaf 当前请求 - * @returns {Promise} ~ + * @param leaf 当前请求 + * @returns ~ */ async before(leaf: HTTPShellLeaf): Promise { const { onRequest } = leaf.originalRequest; - try { + try { await this.task(leaf, onRequest, (result: any) => { let request: HTTPRequest; if (result instanceof HTTPRequest) { @@ -217,16 +217,16 @@ export class HTTPShell { /** * 请求后处理,可修改返回信息,或根据结果全局事务 - * @param {HTTPShellLeaf} leaf 当前请求 - * @returns {Promise} ~ + * @param leaf 当前请求 + * @returns ~ */ async after(leaf: HTTPShellLeaf): Promise { const { localData, onResponse, provider } = leaf.request!; - - let target = localData - ? Promise.resolve(new HTTPResponse({ body: localData })) + + const target = localData + ? Promise.resolve(new HTTPResponse({ body: localData })) : provider(leaf.request!, leaf); - + let originalResponse: HTTPResponse; try { @@ -258,10 +258,10 @@ export class HTTPShell { /** * 错误处理 - * @param {HTTPShellLeaf} leaf 当前请求 - * @param {string} statusText Error Code - * @param {any} body exception - * @returns {HTTPResponse} ~ + * @param leaf 当前请求 + * @param statusText Error Code + * @param body exception + * @returns ~ */ error(leaf: HTTPShellLeaf, statusText: string, body?: any): HTTPResponse { return HTTPResponse.error(statusText, { @@ -279,4 +279,4 @@ export class HTTPShell { } }); } -} \ No newline at end of file +} diff --git a/packages/hooks/__tests__/dynamic.spec.ts b/packages/hooks/__tests__/dynamic.spec.ts index abb6804..b1bd8e8 100644 --- a/packages/hooks/__tests__/dynamic.spec.ts +++ b/packages/hooks/__tests__/dynamic.spec.ts @@ -3,12 +3,11 @@ import { onRequest, onResponse } from '@deot/http-hooks'; describe('common.ts', async () => { const Network = new HTTPController({ - provider: async (request) => (new HTTPResponse({ body: { url: request.url } })), + provider: async request => (new HTTPResponse({ body: { url: request.url } })), onRequest, onResponse }); - it('dynamic, baseUrl', async () => { const baseUrl = `https://example.com`; try { @@ -93,4 +92,4 @@ describe('common.ts', async () => { }); expect(response.body.url).toBe(`/`); }); -}); \ No newline at end of file +}); diff --git a/packages/hooks/__tests__/fetch.spec.ts b/packages/hooks/__tests__/fetch.spec.ts index 05f8947..822feee 100644 --- a/packages/hooks/__tests__/fetch.spec.ts +++ b/packages/hooks/__tests__/fetch.spec.ts @@ -230,4 +230,4 @@ describe('fetch.ts', async () => { expect(response.status).toBe(200); }); -}); \ No newline at end of file +}); diff --git a/packages/hooks/__tests__/fixtures/data.ts b/packages/hooks/__tests__/fixtures/data.ts index 650f675..ae589e9 100644 --- a/packages/hooks/__tests__/fixtures/data.ts +++ b/packages/hooks/__tests__/fixtures/data.ts @@ -39,8 +39,8 @@ export const string = JSON.stringify(json); export const blob = new Blob([JSON.stringify(json)], { type: 'application/json' }); export const blobWithoutType = new Blob([JSON.stringify(json)]); export const blobWithoutContent = new Blob(); -export const file = new File([JSON.stringify(json)], "foo.json", { - type: "application/json", +export const file = new File([JSON.stringify(json)], 'foo.json', { + type: 'application/json', }); export const formData = new FormData(); @@ -81,4 +81,4 @@ class Custom { } } -export const custom = new Custom(response); \ No newline at end of file +export const custom = new Custom(response); diff --git a/packages/hooks/__tests__/index.spec.ts b/packages/hooks/__tests__/index.spec.ts index 7b1abc7..34efc6a 100644 --- a/packages/hooks/__tests__/index.spec.ts +++ b/packages/hooks/__tests__/index.spec.ts @@ -5,4 +5,4 @@ describe('index.ts', () => { expect(typeof onRequest).toBe('function'); expect(typeof onResponse).toBe('function'); }); -}); \ No newline at end of file +}); diff --git a/packages/hooks/__tests__/node.spec.ts b/packages/hooks/__tests__/node.spec.ts index 6e87517..343d445 100644 --- a/packages/hooks/__tests__/node.spec.ts +++ b/packages/hooks/__tests__/node.spec.ts @@ -182,4 +182,4 @@ describe('node.ts', async () => { expect(response.status).toBe(200); }); -}); \ No newline at end of file +}); diff --git a/packages/hooks/__tests__/xhr.spec.ts b/packages/hooks/__tests__/xhr.spec.ts index e5e69e5..35dc948 100644 --- a/packages/hooks/__tests__/xhr.spec.ts +++ b/packages/hooks/__tests__/xhr.spec.ts @@ -217,4 +217,4 @@ describe('xhr.ts', async () => { expect(response.status).toBe(200); }); -}); \ No newline at end of file +}); diff --git a/packages/hooks/src/request.ts b/packages/hooks/src/request.ts index 538042e..92d88d4 100644 --- a/packages/hooks/src/request.ts +++ b/packages/hooks/src/request.ts @@ -10,19 +10,19 @@ const MContentType = `multipart/form-data`; * 如: { response: { status: 1 } } * 当前转义:response=%7B%22status%22%3A1%7D * axios转义:response%5Bstatus%5D=1 (reponse[status]=1) - * @param {{}} body ~ - * @returns {string} ~ + * @param body ~ + * @returns ~ */ const toURLEncodedForm = (body: {}): string => { const results: string[] = []; - for (let key in body) { + for (const key in body) { /** * 过滤掉值为null, undefined情况 */ if ( - body[key] - || body[key] === false - || body[key] === 0 + body[key] + || body[key] === false + || body[key] === 0 || body[key] === '' ) { results.push(key + '=' + encodeURIComponent(Is.plainObject(body[key]) ? JSON.stringify(body[key]) : body[key])); @@ -33,9 +33,11 @@ const toURLEncodedForm = (body: {}): string => { }; export const onRequest: HTTPHook = (leaf) => { - let { url, body, headers, method, dynamic } = leaf.request; + const { url: originalUrl, body: originaBody, headers, method, dynamic } = leaf.request; const type = method.toLowerCase(); + let url = originalUrl; + let body = originaBody; /** * 解析RESTFUL URL 或者动态的; * 支持以下场景: @@ -48,8 +50,8 @@ export const onRequest: HTTPHook = (leaf) => { * 2. 对应使用过的字段会被移除,如果是 config.article_id 会删除config下的article_id字段 */ if (dynamic && Is.plainObject(body)) { - let original = body as {}; - let regex = /(\/?{[^?\/\&]+|\/?:[^\d][^?\/\&]+)/g; + const original = body as {}; + const regex = /(\/?{[^?\/\&]+|\/?:[^\d][^?\/\&]+)/g; let url$ = ''; let pathAndSearch = url.replace(/[a-zA-z]+:\/\/[^\/{]*/, (key) => { @@ -58,24 +60,24 @@ export const onRequest: HTTPHook = (leaf) => { }); if (regex.test(pathAndSearch)) { - let delTmp: any[] = []; - pathAndSearch = pathAndSearch.replace(regex, key => { - let k = key.replace(/({|}|\s|:|\/)/g, ''); - let result = getPropByPath(original, k); - + const delTmp: any[] = []; + pathAndSearch = pathAndSearch.replace(regex, (key) => { + const k = key.replace(/({|}|\s|:|\/)/g, ''); + const result = getPropByPath(original, k); + delTmp.push(result); - return result.v - ? `${key.indexOf('/') === 0 ? '/' : ''}${result.v}` + return result.v + ? `${key.indexOf('/') === 0 ? '/' : ''}${result.v}` : ''; }); - + delTmp.forEach(i => typeof i.o[i.k] !== 'undefined' && delete i.o[i.k]); url = url$ + pathAndSearch; } } if (['get'].includes(type) && Is.plainObject(body)) { - let encodedForm = toURLEncodedForm(body as {}); + const encodedForm = toURLEncodedForm(body as {}); if (encodedForm.length > 0) { url += (url.includes('?') ? '&' : '?') + encodedForm; } @@ -95,11 +97,11 @@ export const onRequest: HTTPHook = (leaf) => { } if (!( - Is.arrayBuffer(body) - || Is.buffer(body) - || Is.stream(body) - || Is.file(body) - || Is.blob(body) + Is.arrayBuffer(body) + || Is.buffer(body) + || Is.stream(body) + || Is.file(body) + || Is.blob(body) || Is.formData(body) || Is.string(body) || !body @@ -110,7 +112,7 @@ export const onRequest: HTTPHook = (leaf) => { headers.set('Content-Type', XContentType, false); body = (body as URLSearchParams).toString(); } else if (Is.files(body)) { - let original = body; + const original = body; body = new FormData(); Array.from((original as FileList)).forEach((file: File) => { (body as any).append('files[]', file); @@ -119,10 +121,10 @@ export const onRequest: HTTPHook = (leaf) => { if (contentType.includes(XContentType)) { body = toURLEncodedForm(body as {}); } else if (contentType.includes(MContentType)) { - let original = body as {}; + const original = body as {}; body = new FormData(); Object.keys(original).forEach((key) => { - let args: any = [key, original[key]]; + const args: any = [key, original[key]]; /* istanbul ignore next -- @preserve */ if (Is.file(args[1]) && args[1].name) { args.push(args[1].name); @@ -142,7 +144,7 @@ export const onRequest: HTTPHook = (leaf) => { body = JSON.stringify(body); } } - + if (!Is.formData(body) && ['post', 'put', 'patch'].includes(type)) { headers.set('Content-Type', XContentType, false); } @@ -151,10 +153,10 @@ export const onRequest: HTTPHook = (leaf) => { if (Is.formData(body)) { headers.set('Content-Type', null, true); } - + leaf.request.url = url; leaf.request.body = body; leaf.request.headers = headers; return leaf; -}; \ No newline at end of file +}; diff --git a/packages/hooks/src/response.ts b/packages/hooks/src/response.ts index de5f00e..bb8a0e8 100644 --- a/packages/hooks/src/response.ts +++ b/packages/hooks/src/response.ts @@ -3,7 +3,7 @@ import * as Is from '@deot/helper-is'; export const onResponse: HTTPHook = (leaf) => { let { body } = leaf.response!; - + if (Is.string(body)) { try { body = JSON.parse(body.toString()); @@ -12,4 +12,4 @@ export const onResponse: HTTPHook = (leaf) => { leaf.response!.body = body; return leaf; -}; \ No newline at end of file +}; diff --git a/packages/index/src/index.browser.ts b/packages/index/src/index.browser.ts index 373735b..d0c1d3b 100644 --- a/packages/index/src/index.browser.ts +++ b/packages/index/src/index.browser.ts @@ -1 +1 @@ -export * from '@deot/http-client'; \ No newline at end of file +export * from '@deot/http-client'; diff --git a/packages/index/src/index.node.ts b/packages/index/src/index.node.ts index a5fc512..c5d4a46 100644 --- a/packages/index/src/index.node.ts +++ b/packages/index/src/index.node.ts @@ -1 +1 @@ -export * from '@deot/http-server'; \ No newline at end of file +export * from '@deot/http-server'; diff --git a/packages/index/src/index.ts b/packages/index/src/index.ts index 93ad093..d8ff731 100644 --- a/packages/index/src/index.ts +++ b/packages/index/src/index.ts @@ -1,6 +1,6 @@ -import type { HTTPController, HTTPRequestOptions } from "@deot/http-core"; -import * as ServerAdapter from "@deot/http-server"; -import * as ClientAdapter from "@deot/http-client"; +import type { HTTPController, HTTPRequestOptions } from '@deot/http-core'; +import * as ServerAdapter from '@deot/http-server'; +import * as ClientAdapter from '@deot/http-client'; interface Adapter { createInstance: (options: HTTPRequestOptions) => HTTPController; diff --git a/packages/server/__tests__/hooks.spec.ts b/packages/server/__tests__/hooks.spec.ts index 993d0b4..7c6bf3a 100644 --- a/packages/server/__tests__/hooks.spec.ts +++ b/packages/server/__tests__/hooks.spec.ts @@ -57,7 +57,7 @@ describe('hooks.ts', async () => { formData.append('response', Data.responseString); // escapeName formData.append('blob"', Data.blobWithoutType); - + const response = await Network.http(`${serverUrl}`, { method: 'POST', body: formData, @@ -149,4 +149,4 @@ describe('hooks.ts', async () => { expect(e.body.message).toMatch('Body after t'); } }); -}); \ No newline at end of file +}); diff --git a/packages/server/__tests__/index.spec.ts b/packages/server/__tests__/index.spec.ts index b59ab17..45005da 100644 --- a/packages/server/__tests__/index.spec.ts +++ b/packages/server/__tests__/index.spec.ts @@ -19,4 +19,4 @@ describe('index.ts', async () => { expect(Network3.request.onRequest.length).toBe(2); expect(Network3.request.onResponse.length).toBe(1); }); -}); \ No newline at end of file +}); diff --git a/packages/server/__tests__/provider.spec.ts b/packages/server/__tests__/provider.spec.ts index f67868a..b791fa2 100644 --- a/packages/server/__tests__/provider.spec.ts +++ b/packages/server/__tests__/provider.spec.ts @@ -26,7 +26,7 @@ describe('provider.ts', async () => { data: {} } }; - const response = await Network.http(serverUrl, { + const response = await Network.http(serverUrl, { timeout: 0, method: 'POST', body @@ -46,7 +46,7 @@ describe('provider.ts', async () => { * 以这样的形式 /user/:id */ it('Delete', async () => { - const response = await Network.http(serverUrl, { + const response = await Network.http(serverUrl, { method: 'DELETE' }); @@ -59,11 +59,10 @@ describe('provider.ts', async () => { it('Delete,Bad Request', async () => { try { - await Network.http(serverUrl, { + await Network.http(serverUrl, { method: 'DELETE', body: 'any' }); - } catch (e: any) { expect(e.status).toBe(400); } @@ -76,7 +75,7 @@ describe('provider.ts', async () => { data: {} } }; - const response = await Network.http(serverUrl, { + const response = await Network.http(serverUrl, { method: 'PUT', body }); @@ -98,7 +97,7 @@ describe('provider.ts', async () => { }); it('headers', async () => { - let headers = {}; + const headers = {}; // eslint-disable-next-line no-proto (headers as any).__proto__['Cookie'] = 'any'; await Network.http(`${serverUrl}`, { @@ -107,7 +106,7 @@ describe('provider.ts', async () => { }); it('headers, null', async () => { - let headers = {}; + const headers = {}; // eslint-disable-next-line no-proto (headers as any)['Cookie'] = null; await Network.http(`${serverUrl}`, { @@ -120,7 +119,6 @@ describe('provider.ts', async () => { await Network.http(`${serverUrl}`, { maxContentLength: 10 }); - } catch (e: any) { expect(e.statusText).toBe('HTTP_CONTENT_EXCEEDED'); } @@ -128,7 +126,7 @@ describe('provider.ts', async () => { it('cancel', async () => { try { - const leaf = Network.http(serverUrl, { + const leaf = Network.http(serverUrl, { method: 'PUT', }); setTimeout(() => leaf.cancel()); @@ -149,7 +147,7 @@ describe('provider.ts', async () => { stream.push(JSON.stringify(body)); stream.push(null); // no more data - const response = await Network.http(serverUrl, { + const response = await Network.http(serverUrl, { method: 'POST', body: stream }); @@ -194,7 +192,7 @@ describe('provider.ts', async () => { } }; - const response = await Network.http(serverUrl, { + const response = await Network.http(serverUrl, { method: 'POST', body, responseType: 'arraybuffer' @@ -211,24 +209,24 @@ describe('provider.ts', async () => { } }; - const response = await Network.http(serverUrl, { + const response = await Network.http(serverUrl, { method: 'POST', body, responseType: 'stream' }); const data = await new Promise((resolve) => { - let responseBuffer: any[] = []; + const responseBuffer: any[] = []; response.body.on('data', (chunk) => { responseBuffer.push(chunk); }); response.body.on('end', () => { - let responseData = Buffer.concat(responseBuffer); + const responseData = Buffer.concat(responseBuffer); resolve(JSON.parse(responseData.toString('utf8'))); }); }); expect(data).toEqual(body.response); }); -}); \ No newline at end of file +}); diff --git a/packages/server/src/helper/form-data-to-stream.ts b/packages/server/src/helper/form-data-to-stream.ts index 71e9a3f..1832f8b 100644 --- a/packages/server/src/helper/form-data-to-stream.ts +++ b/packages/server/src/helper/form-data-to-stream.ts @@ -27,7 +27,7 @@ class FormDataPart { if (isStringValue) { value = textEncoder.encode(String(value).replace(/\r?\n|\r\n?/g, CRLF)); } else { - headers += `Content-Type: ${value.type || "application/octet-stream"}${CRLF}`; + headers += `Content-Type: ${value.type || 'application/octet-stream'}${CRLF}`; } this.headers = textEncoder.encode(headers + CRLF); @@ -45,7 +45,7 @@ class FormDataPart { if (Is.typedArray(value)) { yield value; } else { - yield* readBlob(value); + yield * readBlob(value); } yield CRLF_BYTES; } @@ -63,7 +63,7 @@ class FormDataPart { export const formDataToStream = (form: FormData, headersHandler?: any, options?: any) => { const boundary = options?.boundary || 'form-data-boundary-' + generateString(25); - + const boundaryBytes = textEncoder.encode('--' + boundary + CRLF); const footerBytes = textEncoder.encode('--' + boundary + '--' + CRLF + CRLF); let contentLength = footerBytes.byteLength; @@ -89,9 +89,9 @@ export const formDataToStream = (form: FormData, headersHandler?: any, options?: return Readable.from((async function* () { for (const part of parts) { yield boundaryBytes; - yield* part.encode(); + yield * part.encode(); } yield footerBytes; })()); }; -export default formDataToStream; \ No newline at end of file +export default formDataToStream; diff --git a/packages/server/src/helper/read-blob.ts b/packages/server/src/helper/read-blob.ts index 4e36f24..a8680a7 100644 --- a/packages/server/src/helper/read-blob.ts +++ b/packages/server/src/helper/read-blob.ts @@ -3,12 +3,12 @@ const { asyncIterator } = Symbol; export const readBlob = async function* (blob: any) { /* istanbul ignore next -- @preserve */ if (blob.stream) { - yield* blob.stream(); + yield * blob.stream(); } else if (blob.arrayBuffer) { yield await blob.arrayBuffer(); } else if (blob[asyncIterator]) { - yield* blob[asyncIterator](); + yield * blob[asyncIterator](); } else { yield blob; } -}; \ No newline at end of file +}; diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts index 423ee32..b6f5c8f 100644 --- a/packages/server/src/index.ts +++ b/packages/server/src/index.ts @@ -1,8 +1,8 @@ -import { HTTPController } from "@deot/http-core"; -import type { HTTPRequestOptions } from "@deot/http-core"; +import { HTTPController } from '@deot/http-core'; +import type { HTTPRequestOptions } from '@deot/http-core'; import { onRequest, onResponse } from '@deot/http-hooks'; import { onRequest as onRequestForServer } from './on-request'; -import { provider } from "./provider"; +import { provider } from './provider'; export const createInstance = (options: HTTPRequestOptions = {}) => { const onBaseRequest = (Array.isArray(options.onRequest) ? options.onRequest : (options.onRequest ? [options.onRequest] : [])); @@ -17,4 +17,4 @@ export const createInstance = (options: HTTPRequestOptions = {}) => { return client; }; -export const Network = createInstance({} as HTTPRequestOptions); \ No newline at end of file +export const Network = createInstance({} as HTTPRequestOptions); diff --git a/packages/server/src/on-request.ts b/packages/server/src/on-request.ts index 3b374e1..d031d42 100644 --- a/packages/server/src/on-request.ts +++ b/packages/server/src/on-request.ts @@ -5,8 +5,9 @@ import { formDataToStream, readBlob } from './helper'; // 针对服务端要额外做处理 export const onRequest: HTTPHook = (leaf) => { - let { body, headers } = leaf.request; - + const { body: originalBody, headers } = leaf.request; + + let body = originalBody; if (!(Is.buffer(body) || Is.stream(body) || Is.string(body) || !body)) { if (Is.arrayBuffer(body)) { body = Buffer.from(new Uint8Array(body as ArrayBuffer)); @@ -18,7 +19,7 @@ export const onRequest: HTTPHook = (leaf) => { } ); } else if (Is.blob(body) || Is.file(body)) { - let original = body as Blob; + const original = body as Blob; if (original.size) { headers.set('Content-Type', original.type || 'application/octet-stream', true); } @@ -34,4 +35,4 @@ export const onRequest: HTTPHook = (leaf) => { leaf.request.headers = headers; return leaf; -}; \ No newline at end of file +}; diff --git a/packages/server/src/provider.ts b/packages/server/src/provider.ts index 57f83cd..d8b99d2 100644 --- a/packages/server/src/provider.ts +++ b/packages/server/src/provider.ts @@ -3,8 +3,8 @@ import * as https from 'node:https'; import * as url from 'node:url'; import followRedirects from 'follow-redirects'; -import type { HTTPProvider } from "@deot/http-core"; -import { HTTPHeaders, HTTPResponse, ERROR_CODE } from "@deot/http-core"; +import type { HTTPProvider } from '@deot/http-core'; +import { HTTPHeaders, HTTPResponse, ERROR_CODE } from '@deot/http-core'; const { http: httpFollow, https: httpsFollow } = followRedirects; @@ -12,7 +12,7 @@ export const provider: HTTPProvider = (request, leaf) => { return new Promise((resolve, reject) => { let timer: any; - let response: http.IncomingMessage; + let response: http.IncomingMessage; const getExtra = () => { return { @@ -31,21 +31,21 @@ export const provider: HTTPProvider = (request, leaf) => { }; const onSuccess = (body$: any) => { - resolve(new HTTPResponse({ + resolve(new HTTPResponse({ ...getExtra(), - body: body$ + body: body$ })); timer && clearTimeout(timer); timer = null; }; - const { + const { url: url$, - maxRedirects, - responseType, - maxContentLength = Infinity, - body, - method, + maxRedirects, + responseType, + maxContentLength = Infinity, + body, + method, headers, timeout, ...requestOptions @@ -62,7 +62,7 @@ export const provider: HTTPProvider = (request, leaf) => { transport = isHttps ? httpsFollow : httpFollow; } - let req = transport.request({ + const req = transport.request({ method, hostname, port, @@ -78,14 +78,14 @@ export const provider: HTTPProvider = (request, leaf) => { onSuccess(res); return; } - - let responseBuffer: any[] = []; + + const responseBuffer: any[] = []; res.on('data', (chunk) => { responseBuffer.push(chunk); // 如果指定,请确保内容长度不超过maxContentLength if ( - maxContentLength > -1 + maxContentLength > -1 && Buffer.concat(responseBuffer).length > maxContentLength ) { onError('HTTP_CONTENT_EXCEEDED'); @@ -98,7 +98,7 @@ export const provider: HTTPProvider = (request, leaf) => { }); res.on('end', () => { - let responseData = Buffer.concat(responseBuffer); + const responseData = Buffer.concat(responseBuffer); let result: Buffer | string = responseData; if (responseType !== 'arraybuffer') { result = responseData.toString('utf8'); @@ -125,7 +125,7 @@ export const provider: HTTPProvider = (request, leaf) => { }; leaf.server = req; - + // body instanceof Readable if (body && typeof (body as any).pipe === 'function') { (body as any).pipe(req); diff --git a/packages/shared/__tests__/global.spec.ts b/packages/shared/__tests__/global.spec.ts index bbb3fcd..902ed56 100644 --- a/packages/shared/__tests__/global.spec.ts +++ b/packages/shared/__tests__/global.spec.ts @@ -2,11 +2,11 @@ import type { AnyFunction } from '@deot/http-shared'; describe('global.types.ts', () => { it('dts', () => { - type DTS = { + type DTS = { fn?: AnyFunction; }; const options: DTS = {}; expect(typeof options).toBe('object'); }); -}); \ No newline at end of file +}); diff --git a/packages/shared/src/global.types.ts b/packages/shared/src/global.types.ts index e19eb29..cfb9ca5 100644 --- a/packages/shared/src/global.types.ts +++ b/packages/shared/src/global.types.ts @@ -1,16 +1,16 @@ export type Indexable = { [key: string]: T; -} +}; -export type Hash = Indexable +export type Hash = Indexable; // 默认值any -export type Options = Indexable & T +export type Options = Indexable & T; export interface AnyFunction { (...args: any[]): T; } export type Nullable = T | null; -export type Customized = Origin & Extend -export type TimeoutHandle = ReturnType +export type Customized = Origin & Extend; +export type TimeoutHandle = ReturnType; diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index a1ccf23..8a4ae8a 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -4,5 +4,4 @@ export * from './global.types'; - export const Utils = {}; diff --git a/packages/shims.d.ts b/packages/shims.d.ts index 040e08a..56c18cc 100644 --- a/packages/shims.d.ts +++ b/packages/shims.d.ts @@ -4,4 +4,4 @@ declare module 'fs-extra' declare module 'inquirer' declare module 'inquirer-autocomplete-prompt' declare module 'formidable'; -declare module 'follow-redirects'; \ No newline at end of file +declare module 'follow-redirects';