Skip to content

Commit

Permalink
feat: 支持 es2015
Browse files Browse the repository at this point in the history
  • Loading branch information
zjxxxxxxxxx committed Apr 5, 2023
1 parent 73ac18d commit b66176f
Show file tree
Hide file tree
Showing 19 changed files with 438 additions and 58 deletions.
5 changes: 4 additions & 1 deletion .github/workflows/release.yml
Expand Up @@ -26,6 +26,9 @@ jobs:
- name: Install
run: pnpm i

- name: Create releaselog
run: pnpm releaselog

- name: Check prerelease
id: prerelease
uses: actions/github-script@v6
Expand All @@ -40,7 +43,7 @@ jobs:
with:
tag_name: ${{ github.ref }}
release_name: Release ${{ github.ref }}
body_path: 'CHANGELOG.md'
body_path: 'RELEASELOG.md'
prerelease: ${{ steps.prerelease.outputs.result }}

- name: Build Release Asset
Expand Down
3 changes: 3 additions & 0 deletions .gitignore
Expand Up @@ -23,3 +23,6 @@ coverage

# eslint
.eslintcache

# release
RELEASELOG.md
1 change: 1 addition & 0 deletions .prettierignore
@@ -0,0 +1 @@
CHANGELOG.md
10 changes: 2 additions & 8 deletions CHANGELOG.md
@@ -1,24 +1,18 @@
# 2.0.0-beta.0 (2023-04-04)


### Bug Fixes

* 清理 url 前面多余的斜线 ([666a942](https://github.com/zjx0905/axios-miniprogram/commit/666a9427d3c9bfbd96def9e112d5183acdf08d84))


### Features

* 增强默认参数系列化器 ([0cfb3e1](https://github.com/zjx0905/axios-miniprogram/commit/0cfb3e1ff04b69896ba43ffcb6abba5fb61ad48a))
* 支持合并自定义配置 ([4409a57](https://github.com/zjx0905/axios-miniprogram/commit/4409a5720ba1e58a4c218ee67f71d5f05beee6a8)), closes [#38](https://github.com/zjx0905/axios-miniprogram/issues/38)
* 支持京东小程序 ([0d1d21f](https://github.com/zjx0905/axios-miniprogram/commit/0d1d21fc66eb202463ef2baaa174b0f60276035e))
* 支持自定义配置 ([b15b31e](https://github.com/zjx0905/axios-miniprogram/commit/b15b31ee55217f11e08713ce02dd7ab21732fba1))


### BREAKING CHANGES

* axios.get('url',{obj:{v1:1,v2:2}}) -> fetch: 'url?obj={"val":1,"v2":2}'
变为
axios.get('url',{obj:{v1:1,v2:2}}) -> fetch: 'url?obj[v1]=1&obj[v2]=2'



变为
axios.get('url',{obj:{v1:1,v2:2}}) -> fetch: 'url?obj[v1]=1&obj[v2]=2'
11 changes: 4 additions & 7 deletions package.json
Expand Up @@ -2,8 +2,8 @@
"name": "axios-miniprogram",
"version": "2.0.0-beta.0",
"description": "基于 Promise 的 HTTP 请求库,适用于各大小程序平台。",
"main": "dist/axios-miniprogram.esm.js",
"module": "dist/axios-miniprogram.cjs.js",
"main": "dist/axios-miniprogram.cjs.js",
"module": "dist/axios-miniprogram.esm.js",
"types": "dist/axios-miniprogram.d.ts",
"type": "module",
"files": [
Expand All @@ -25,17 +25,14 @@
},
"homepage": "https://github.com/zjx0905/axios-miniprogram#readme",
"license": "MIT",
"engines": {
"node": ">=16",
"pnpm": ">=7"
},
"scripts": {
"cz": "czg",
"build": "esno scripts/build.ts",
"build:asset": "esno scripts/build-asset.ts",
"release": "esno scripts/release.ts",
"publish:ci": "esno scripts/publish.ts",
"changelog": "conventional-changelog -p angular -i CHANGELOG.md -s",
"releaselog": "esno scripts/releaselog.ts",
"upload:asset": "esno scripts/upload-asset.ts",
"test": "vitest run",
"test:watch": "vitest",
Expand Down Expand Up @@ -94,4 +91,4 @@
]
}
}
}
}
1 change: 1 addition & 0 deletions rollup.config.js
Expand Up @@ -45,6 +45,7 @@ function buildConfig(format) {
: esbuildPlugin({
tsconfig: path.resolve(__dirname, 'tsconfig.json'),
sourceMap: output.sourcemap,
target: 'es2015',
minify: true,
}),
],
Expand Down
34 changes: 31 additions & 3 deletions scripts/publish.ts
@@ -1,18 +1,46 @@
import fs from 'node:fs';
import consola from 'consola';
import { exec, getPkgJSON } from './utils';
import { exec, pkgPath, getPkgJSON } from './utils';

const { version } = getPkgJSON();
const pkg = getPkgJSON();

main();

function main() {
consola.info('Generate publish pkg');
generatePublishPkg();

let command = 'npm publish --access public';

const preid = version.match(/\d-(.+)\.\d$/)?.[1];
const preid = pkg.version.match(/\d-(.+)\.\d$/)?.[1];
if (preid) {
command += ` --tag ${preid}`;
}

consola.info('Publish NPM');
exec(command);
}

function generatePublishPkg() {
const publishPkg = {};

[
'name',
'version',
'description',
'main',
'module',
'types',
'files',
'repository',
'keywords',
'author',
'bugs',
'homepage',
'license',
].forEach((key) => {
publishPkg[key] = pkg[key];
});

fs.writeFileSync(pkgPath, JSON.stringify(publishPkg, null, 2) + '\n');
}
28 changes: 28 additions & 0 deletions scripts/releaselog.ts
@@ -0,0 +1,28 @@
import fs from 'node:fs';
import path from 'node:path';
import readline from 'node:readline';
import { __dirname, getPkgJSON } from './utils';

const changelogPath = path.resolve(__dirname, 'CHANGELOG.md');
const releaselogPath = path.resolve(__dirname, 'RELEASELOG.md');
const { version } = getPkgJSON();
const versionRE = new RegExp(`^# \\[?${version}\\]?`);

main();

async function main() {
const changelog = readline.createInterface({
input: fs.createReadStream(changelogPath),
crlfDelay: Infinity,
});

let releaselog = '';
for await (const line of changelog) {
if (line.startsWith('# ') && !versionRE.test(line)) {
break;
}
releaselog += `${line}\n`;
}

fs.writeFileSync(releaselogPath, releaselog);
}
25 changes: 6 additions & 19 deletions src/adapter.ts
Expand Up @@ -2,7 +2,6 @@ import {
isEmptyArray,
isFunction,
isPlainObject,
isString,
isUndefined,
} from './helpers/isTypes';
import { assert, throwError } from './helpers/error';
Expand Down Expand Up @@ -152,7 +151,7 @@ export function getAdapterDefault(): AxiosAdapter | undefined {
try {
const tryGetPlatform = tryGetPlatforms.shift();

if (isPlainObject((platform = tryGetPlatform?.()))) {
if (isPlainObject((platform = tryGetPlatform!()))) {
platform = revisePlatformApiNames(platform);
}
} catch (err) {
Expand All @@ -169,13 +168,11 @@ export function getAdapterDefault(): AxiosAdapter | undefined {

export function createAdapter(platform: AxiosPlatform): AxiosAdapter {
assert(isPlainObject(platform), 'platform 不是一个 object');
assert(isFunction(platform.request), 'platform.request 不是一个 function');
assert(isFunction(platform.upload), 'platform.upload 不是一个 function');
assert(isFunction(platform.download), 'platform.download 不是一个 function');
assert(isFunction(platform.request), 'request 不是一个 function');
assert(isFunction(platform.upload), 'upload 不是一个 function');
assert(isFunction(platform.download), 'download 不是一个 function');

function adapterDefault(
config: AxiosAdapterRequestConfig,
): AxiosAdapterTask | void {
function adapter(config: AxiosAdapterRequestConfig): AxiosAdapterTask | void {
const baseOptions = transformOptions(config);

switch (config.type) {
Expand All @@ -201,16 +198,6 @@ export function createAdapter(platform: AxiosPlatform): AxiosAdapter {
upload: AxiosAdapterUpload,
baseOptions: AxiosAdapterBaseOptions,
): AxiosAdapterTask | void {
assert(isPlainObject(baseOptions.data), 'data 不是一个 object');
assert(
isString(baseOptions.data?.fileName),
'data.fileName 不是一个 string',
);
assert(
isString(baseOptions.data?.filePath),
'data.filePath 不是一个 string',
);

const { fileName, filePath, fileType, ...formData } =
baseOptions.data as AxiosRequestFormData;
const options = {
Expand Down Expand Up @@ -306,7 +293,7 @@ export function createAdapter(platform: AxiosPlatform): AxiosAdapter {
}
}

return adapterDefault;
return adapter;
}

export function isPlatform(value: unknown): value is AxiosPlatform {
Expand Down
2 changes: 1 addition & 1 deletion src/axios.ts
Expand Up @@ -20,7 +20,7 @@ export interface AxiosInstance extends Axios {
export interface AxiosStatic extends AxiosInstance {
Axios: AxiosConstructor;
defaults: AxiosRequestConfig & {
headers: Required<AxiosRequestHeaders> & { common?: AnyObject };
headers?: AxiosRequestHeaders & { common?: AnyObject };
};
CancelToken: CancelTokenConstructor;
create(defaults?: AxiosRequestConfig): AxiosInstance;
Expand Down
10 changes: 4 additions & 6 deletions src/core/Axios.ts
Expand Up @@ -243,19 +243,17 @@ export default class Axios {
config: AxiosRequestConfig,
): Promise<AxiosResponse<TData>> {
const requestConfig = mergeConfig(this.defaults, config);
const { request, response } = this.interceptors;

let promiseRequest = Promise.resolve(requestConfig);

this.interceptors.request.forEach(({ resolved, rejected }) => {
request.forEach(({ resolved, rejected }) => {
promiseRequest = promiseRequest.then(
resolved,
rejected,
) as Promise<AxiosRequestConfig>;
}, 'reverse');

}, true);
let promiseResponse = promiseRequest.then(dispatchRequest);

this.interceptors.response.forEach(({ resolved, rejected }) => {
response.forEach(({ resolved, rejected }) => {
promiseResponse = promiseResponse.then(resolved, rejected) as Promise<
AxiosResponse<unknown>
>;
Expand Down
12 changes: 3 additions & 9 deletions src/core/InterceptorManager.ts
Expand Up @@ -36,15 +36,9 @@ export default class InterceptorManager<T = unknown> {
delete this.interceptors[id];
}

public forEach(executor: InterceptorExecutor, reverse?: 'reverse'): void {
let interceptors: Interceptor<any>[] = Object.keys(this.interceptors).map(
(id) => this.interceptors[id],
);

if (reverse === 'reverse') {
interceptors = interceptors.reverse();
}

public forEach(executor: InterceptorExecutor, reverse?: boolean): void {
let interceptors: Interceptor<any>[] = Object.values(this.interceptors);
if (reverse) interceptors = interceptors.reverse();
interceptors.forEach(executor);
}
}
8 changes: 5 additions & 3 deletions src/core/dispatchRequest.ts
Expand Up @@ -44,9 +44,11 @@ export default function dispatchRequest<TData = unknown>(
.catch((reason: unknown) => {
if (!isCancel(reason)) {
throwIfCancellationRequested(config);
const response = (reason as AnyObject)?.response;
if (isPlainObject(response)) {
transformer(response as AxiosResponse<TData>);
if (isPlainObject(reason)) {
const { response } = reason;
if (isPlainObject(response)) {
transformer(response as AxiosResponse<TData>);
}
}
}
throw config.errorHandler?.(reason) ?? reason;
Expand Down
55 changes: 55 additions & 0 deletions test/adapter.platform.test.ts
@@ -0,0 +1,55 @@
import { describe, test, expect, beforeEach, afterEach, vi } from 'vitest';
import { getAdapterDefault } from 'src/adapter';

const platforms = [
'uni',
'wx',
'my',
'swan',
'tt',
'qq',
'qh',
'ks',
'dd',
'jd',
'unknown',
];

describe.each(platforms)('src/adapter.ts', (p) => {
beforeEach(() => {
vi.stubGlobal(p, {
request: vi.fn(),
uploadFile: vi.fn(),
downloadFile: vi.fn(),
});
});

afterEach(() => {
vi.unstubAllGlobals();
});

test('应该可以获取到默认的平台适配器', () => {
const a = getAdapterDefault();
if (p !== 'unknown') {
expect(a).toBeTypeOf('function');
(expect(a).property('name') as any).toBe('adapter');
} else {
// unknown 未知平台
expect(a).toBeUndefined();
}
});
});

describe.each(platforms)('src/adapter.ts', (p) => {
beforeEach(() => {
vi.stubGlobal(p, {});
});

afterEach(() => {
vi.unstubAllGlobals();
});

test('应该获取不到默认的平台适配器', () => {
expect(getAdapterDefault()).toBeUndefined();
});
});

0 comments on commit b66176f

Please sign in to comment.