@tuzki/cli
Version:
🐇 lowcode-cli is an efficient cli tool for Rabbitpre plugin component secondary development. ❤️
122 lines (121 loc) • 4.93 kB
JavaScript
/*
* 请求函数封装
*
* @Author: xu.jin
* @Date: 2022-12-11 19:32:22
*
* Copyright © 2014-2022 Rabbitpre.com. All Rights Reserved.
*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
import https from 'https';
import Logger from '@tuzki/scaffold-logger';
import fetch from 'node-fetch';
import { getConfig } from './config.js';
import { stringifyQuery } from './query.js';
const logger = Logger.get('cli:utils:request');
const httpsAgent = new https.Agent({
rejectUnauthorized: false,
});
/**
* 统一请求调用函数
*/
export const request = (url, options) => __awaiter(void 0, void 0, void 0, function* () {
const { headers, customOptions = {} } = options, finalOptions = __rest(options, ["headers", "customOptions"]);
const { body, formData, blob, isExternalReq, buffer } = customOptions;
const config = yield getConfig();
const finalHeaders = Object.assign(Object.assign({}, headers), { cookie: `tz_sid=${config.token}` });
let finalBody = body;
if (options.method === 'POST' && !formData) {
// @ts-ignore
finalHeaders['Content-Type'] = 'application/json';
finalBody = JSON.stringify(body);
}
logger.debug('请求开始:', JSON.stringify({
url,
options,
}));
return fetch(url, Object.assign(Object.assign({}, finalOptions), { headers: finalHeaders, agent: httpsAgent, body: finalBody })).then(res => {
// 返回 blob 格式
if (blob) {
logger.debug('请求成功, 格式为 blob');
return res.blob();
}
if (buffer) {
logger.debug('请求成功, 返回 buffer');
return res.buffer();
}
// console.log('res', res);
// 返回 json 格式并添加统一校验
return res
.json()
.then(result => {
const resJson = result;
if (isExternalReq) {
return resJson;
}
// 请求成功直接返回 data
if (+resJson.code === 0 || +resJson.code === 200) {
logger.debug('请求成功, 返回值为:', JSON.stringify(resJson));
return resJson.data;
}
// 授权问题直接退出
if (+resJson.code === 4003) {
logger.error('cli 未登录, 请先登录');
process.exit(1);
}
logger.debug('请求出错, 返回值为:', JSON.stringify(resJson));
// 其余的问题抛出错误给业务处理
// 这里有可能会报后端的错误, 或者是 node 层的错误
throw new Error(resJson.showMsg || resJson.errorMsg);
})
.catch(error => {
logger.error('请求出错', `错误信息:${res.statusText}`, `状态码:${res.status}`);
logger.error('请求出错, 错误信息:', error);
throw error;
});
});
});
/**
* post 请求封装
* @param url 请求链接
* @param body 请求数据
* @param opts 配置项
*/
export function post(url, body, opts) {
return __awaiter(this, void 0, void 0, function* () {
const res = yield request(url, Object.assign(Object.assign({}, opts), { method: 'POST', customOptions: Object.assign(Object.assign({}, opts === null || opts === void 0 ? void 0 : opts.customOptions), { body }) }));
return res;
});
}
/**
* get 请求封装
* @param url 请求链接
* @param {QueryType} query 请求 query 参数
* @param opts 配置项
*/
export function get(url, query = '', opts) {
return __awaiter(this, void 0, void 0, function* () {
const _url = url + stringifyQuery(query);
const res = yield request(_url, Object.assign(Object.assign({}, opts), { method: 'GET' }));
return res;
});
}