Commit 00dc315a authored by rockyl's avatar rockyl

init

parents
Pipeline #283941 failed with stages
in 0 seconds
# Created by .ignore support plugin (hsz.mobi)
### Node template
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# TypeScript v1 declaration files
typings/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
.env.test
# parcel-bundler cache (https://parceljs.org/)
.cache
# next.js build output
.next
# nuxt.js build output
.nuxt
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
interface FetchApiOptions {
apiHost?: string;
fetch?: Function;
}
interface FetchApiOptions {
host?: string;
params?: any;
headers?: any;
method?: 'get' | 'post';
credentials?: 'omit' | 'same-origin' | 'include';
contentType?: string;
errMessage?: string;
}
export declare function setup(options: FetchApiOptions): void;
export declare function fetchApi(uri: string, { host, params, headers, method, credentials, contentType, errMessage, }?: FetchApiOptions): Promise<any>;
export {};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const querystringify_1 = require("querystringify");
class ApiError extends Error {
constructor(name, code, message, details) {
super();
this.code = 0;
this.details = '';
if (name) {
this.name = name;
}
if (code) {
this.code = code;
}
if (message) {
this.message = message;
}
if (details) {
this.details = details;
}
}
}
let _options = {};
function setup(options) {
_options = options;
}
exports.setup = setup;
async function fetchApi(uri, { host = '', params, headers = {}, method = 'get', credentials = 'include', contentType = 'json', errMessage, } = {}) {
let url = host +
(uri.startsWith('http') || uri.startsWith('//') ? uri : (_options.apiHost || '') + uri);
const options = {
method,
headers: Object.assign({}, headers),
credentials,
};
if (params) {
if (method.toLowerCase() === 'post') {
switch (contentType) {
case 'form-data':
let formData = new FormData();
for (let key in params) {
let value = params[key];
if (value instanceof File) {
formData.append(key, value, value.name);
}
else {
formData.append(key, value);
}
}
options.body = formData;
break;
case 'form':
options.headers['Content-Type'] = 'application/x-www-form-urlencoded';
options.body = querystringify_1.stringify(params);
break;
case 'json':
options.headers['Content-Type'] = 'application/json';
options.body = JSON.stringify(params);
break;
}
}
else {
url += url.indexOf('?') < 0 ? '?' : '';
url += (url.endsWith('?') ? '' : '&') + querystringify_1.stringify(params);
}
}
try {
let fetchMethod = _options.fetch || fetch;
const response = await fetchMethod(url, options);
const respText = await response.text();
if (response.status === 310) {
location.href = respText;
}
let jsonObj = JSON.parse(respText);
if (jsonObj.code === 0) {
return jsonObj.data;
}
return Promise.reject(new ApiError('call api failed', jsonObj.code, errMessage, jsonObj.msg));
}
catch (e) {
return Promise.reject(e);
}
}
exports.fetchApi = fetchApi;
//# sourceMappingURL=index.js.map
\ No newline at end of file
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;AAMA,mDAAyC;AAKzC,MAAM,QAAS,SAAQ,KAAK;IAI3B,YAAY,IAAY,EAAE,IAAa,EAAE,OAAgB,EAAE,OAAgB;QAC1E,KAAK,EAAE,CAAC;QAJT,SAAI,GAAW,CAAC,CAA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,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;QACnC,IAAI,OAAO,CAAC,IAAI,KAAK,CAAC,EAAE;YACvB,OAAO,OAAO,CAAC,IAAI,CAAC;SAEpB;QAED,OAAO,OAAO,CAAC,MAAM,CACpB,IAAI,QAAQ,CAAC,iBAAiB,EAAE,OAAO,CAAC,IAAI,EAAE,UAAU,EAAE,OAAO,CAAC,GAAG,CAAC,CACtE,CAAC;KACF;IAAC,OAAO,CAAC,EAAE;QACX,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;KACzB;AACF,CAAC;AAzED,4BAyEC"}
\ No newline at end of file
{
"name": "fetch-api",
"version": "1.0.0",
"main": "out/index.js",
"types": "out/index.d.ts",
"license": "MIT",
"dependencies": {
"@types/querystringify": "^2.0.0",
"querystringify": "^2.1.1"
}
}
/**
* Created by rockyl on 2019-09-19.
*
* 封装fetch请求
*/
import {stringify} from 'querystringify';
/**
* api错误
*/
class ApiError extends Error {
code: number = 0;
details: string = '';
constructor(name: string, code?: number, message?: string, details?: string) {
super();
if (name) {
this.name = name;
}
if (code) {
this.code = code;
}
if (message) {
this.message = message;
}
if (details) {
this.details = details;
}
}
}
/**
* 总配置
*/
interface FetchApiOptions {
apiHost?: string;
fetch?: Function;
}
/**
* 请求参数
*/
interface FetchApiOptions {
/**
* 域名
* @default ''
*/
host?: string;
/**
* 请求参数
* @default null
*/
params?: any;
/**
* 头部参数
* @default null
*/
headers?: any;
/**
* 请求方法
* @default 'get'
*/
method?: 'get' | 'post';
/**
* 携带凭证类型
* @default 'include'
*/
credentials?: 'omit' | 'same-origin' | 'include';
/**
* 返回类型
* @default 'json'
*/
contentType?: string;
/**
* 附加错误信息
* @default null
*/
errMessage?: string;
}
let _options: FetchApiOptions = {};
/**
* 配置
* @param options
*/
export function setup(options: FetchApiOptions) {
_options = options;
}
/**
* 请求接口
* @param uri string
* @param options FetchApiOptions
*/
export async function fetchApi(
uri: string,
{
host = '',
params,
headers = {},
method = 'get',
credentials = 'include',
contentType = 'json',
errMessage,
}: FetchApiOptions = {},
) {
let url =
host +
(uri.startsWith('http') || uri.startsWith('//') ? uri : (_options.apiHost || '') + uri);
const options: any = {
method,
headers: {...headers},
credentials,
};
if (params) {
if (method.toLowerCase() === 'post') {
switch (contentType) {
case 'form-data':
let formData = new FormData();
for (let key in params) {
let value = params[key];
if (value instanceof File) {
formData.append(key, value, value.name);
} else {
formData.append(key, value);
}
}
options.body = formData;
break;
case 'form':
options.headers['Content-Type'] = 'application/x-www-form-urlencoded';
options.body = stringify(params);
break;
case 'json':
options.headers['Content-Type'] = 'application/json';
options.body = JSON.stringify(params);
break;
}
} else {
url += url.indexOf('?') < 0 ? '?' : '';
url += (url.endsWith('?') ? '' : '&') + stringify(params);
}
}
try {
let fetchMethod = _options.fetch || fetch;
const response = await fetchMethod(url, options);
const respText = await response.text();
if (response.status === 310) {
//客户端重定向,用于跨域重定向
location.href = respText;
}
let jsonObj = JSON.parse(respText);
if (jsonObj.code === 0) {
return jsonObj.data;
// return Promise.resolve(jsonObj.data) ;
}
return Promise.reject(
new ApiError('call api failed', jsonObj.code, errMessage, jsonObj.msg),
);
} catch (e) {
return Promise.reject(e);
}
}
{
"compileOnSave": true,
"compilerOptions": {
"target": "es2017",
"noImplicitAny": false,
"removeComments": true,
"noEmitOnError": true,
"noEmitHelpers": true,
"module": "commonjs",
"experimentalDecorators": true,
"sourceMap": true,
"watch": true,
"outDir": "out/",
"declaration": true,
"lib": [
"es5",
"es6",
"es7",
"dom",
"es2015.promise"
]
},
"include": [
"src"
],
"exclude": [
"node_modules"
]
}
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1
"@types/querystringify@^2.0.0":
version "2.0.0"
resolved "https://registry.npm.taobao.org/@types/querystringify/download/@types/querystringify-2.0.0.tgz#d1eab3214ee2b57c3bd7eba0ab94b231028522fb"
integrity sha1-0eqzIU7itXw71+ugq5SyMQKFIvs=
querystringify@^2.1.1:
version "2.1.1"
resolved "https://registry.npm.taobao.org/querystringify/download/querystringify-2.1.1.tgz#60e5a5fd64a7f8bfa4d2ab2ed6fdf4c85bad154e"
integrity sha1-YOWl/WSn+L+k0qsu1v30yFutFU4=
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment