Refactor request (#7814)
* status code
* Test ap-request.ts
4397fc5e70/test/ap-request.ts
* tune
This commit is contained in:
parent
03b04acb16
commit
482081c41b
12 changed files with 268 additions and 174 deletions
|
@ -2,7 +2,7 @@ import * as fs from 'fs';
|
|||
import * as stream from 'stream';
|
||||
import * as util from 'util';
|
||||
import got, * as Got from 'got';
|
||||
import { httpAgent, httpsAgent } from './fetch';
|
||||
import { httpAgent, httpsAgent, StatusError } from './fetch';
|
||||
import config from '@/config/index';
|
||||
import * as chalk from 'chalk';
|
||||
import Logger from '@/services/logger';
|
||||
|
@ -37,6 +37,7 @@ export async function downloadUrl(url: string, path: string) {
|
|||
http: httpAgent,
|
||||
https: httpsAgent,
|
||||
},
|
||||
http2: false, // default
|
||||
retry: 0,
|
||||
}).on('response', (res: Got.Response) => {
|
||||
if ((process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'test') && !config.proxy && res.ip) {
|
||||
|
@ -59,17 +60,17 @@ export async function downloadUrl(url: string, path: string) {
|
|||
logger.warn(`maxSize exceeded (${progress.transferred} > ${maxSize}) on downloadProgress`);
|
||||
req.destroy();
|
||||
}
|
||||
}).on('error', (e: any) => {
|
||||
if (e.name === 'HTTPError') {
|
||||
const statusCode = e.response?.statusCode;
|
||||
const statusMessage = e.response?.statusMessage;
|
||||
e.name = `StatusError`;
|
||||
e.statusCode = statusCode;
|
||||
e.message = `${statusCode} ${statusMessage}`;
|
||||
}
|
||||
});
|
||||
|
||||
await pipeline(req, fs.createWriteStream(path));
|
||||
try {
|
||||
await pipeline(req, fs.createWriteStream(path));
|
||||
} catch (e) {
|
||||
if (e instanceof Got.HTTPError) {
|
||||
throw new StatusError(`${e.response.statusCode} ${e.response.statusMessage}`, e.response.statusCode, e.response.statusMessage);
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
logger.succ(`Download finished: ${chalk.cyan(url)}`);
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue