Skip to content

Commit

Permalink
Abstrat using network library
Browse files Browse the repository at this point in the history
split axios into seperate package
  • Loading branch information
seriouslag committed Apr 11, 2024
1 parent 10dfab4 commit 59dd525
Show file tree
Hide file tree
Showing 54 changed files with 13,682 additions and 5,828 deletions.
2 changes: 2 additions & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
dist
**/dist
**/node_modules
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,6 @@ coverage
junit.xml

dist
.DS_Store
.DS_Store

.yarn/cache
Binary file added .yarn/install-state.gz
Binary file not shown.
768 changes: 768 additions & 0 deletions .yarn/releases/yarn-3.1.1.cjs

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions .yarnrc.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
nodeLinker: node-modules

yarnPath: .yarn/releases/yarn-3.1.1.cjs
31 changes: 18 additions & 13 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
module.exports = {
verbose: true,
roots: [
'src',
'<rootDir>/packages',
],
preset: 'ts-jest',
transform: {
Expand All @@ -13,18 +13,23 @@ module.exports = {
},
},
moduleFileExtensions: ['js', 'ts'],
modulePaths: [
'<rootDir>/src',
],
testEnvironment: 'node',
coverageProvider: 'v8',
reporters: ['jest-junit', 'default'],
coverageReporters: ['cobertura', 'html', 'lcov'],
coverageDirectory: 'coverage',
setupFiles: ['./jest-setup.js'],
collectCoverageFrom: [
'src/**/*.{js,ts}',
'!src/examples/**/*',
testEnvironment: 'node',
coverageProvider: 'v8',
reporters: ['jest-junit', 'default'],
coverageReporters: ['cobertura', 'html', 'lcov'],
coverageDirectory: 'coverage',
setupFiles: ['./jest-setup.js'],
collectCoverageFrom: [
'packages/**/*.{js,ts}',
'!packages/httpclient/src/examples/**/*',
],
testPathIgnorePatterns: ['/out/', '/node_modules/'],
modulePaths: [
'<rootDir>/packages/',
],
moduleNameMapper: {
'^@seriouslag/(.*)$': [
'<rootDir>/packages/$1/src/',
],
},
};
20 changes: 20 additions & 0 deletions lerna.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"$schema": "http://json.schemastore.org/lerna",
"version": "independent",
"npmClient": "yarn",
"useWorkspaces": true,
"changelogPreset": "angular",
"command": {
"publish": {
"ignoreChanges": [
"*.md",
"*.test.*"
],
"message": "chore(release): publish"
},
"bootstrap": {}
},
"packages": [
"packages/*"
]
}
39 changes: 15 additions & 24 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
{
"name": "@seriouslag/httpclient",
"version": "0.0.17",
"name": "@seriouslag/httpclient_monorepo",
"version": "0.0.1",
"description": "Typed wrapper HttpClient for axios",
"main": "dist/index.umd.js",
"browser": "dist/index.umd.min.js",
"types": "dist/index.d.ts",
"private": true,
"scripts": {
"build": "rollup -c",
"build": "lerna run build",
"lint": "eslint ./src",
"package": "yarn build && lerna publish --canary",
"publish": "lerna publish",
"test:unit": "jest",
"test:coverage": "jest --coverage"
},
Expand All @@ -33,23 +33,10 @@
"bugs": {
"url": "https://github.com/seriouslag/HttpClient/issues"
},
"files": [
"dist",
"src",
"package.json",
"tsconfig.json",
"tsconfig.build.json",
"README.md",
"LICENSE"
"workspaces": [
"packages/*"
],
"homepage": "https://github.com/seriouslag/HttpClient#readme",
"dependencies": {
"@babel/runtime": "^7.17.2",
"axios": "~0.26.0"
},
"peerDependencies": {
"axios": "~0.26.0"
},
"devDependencies": {
"@babel/core": "^7.17.5",
"@babel/plugin-transform-runtime": "^7.17.0",
Expand All @@ -70,8 +57,12 @@
"rollup-plugin-node-builtins": "^2.1.2",
"rollup-plugin-node-globals": "^1.4.0",
"rollup-plugin-terser": "^7.0.2",
"rollup-plugin-typescript2": "^0.31.2",
"ts-jest": "^27.1.3",
"typescript": "^4.5.5"
"rollup-plugin-typescript2": "^0.31.1",
"ts-jest": "^27.1.1",
"typescript": "^4.5.4"
},
"packageManager": "[email protected]",
"dependencies": {
"lerna": "^4.0.0"
}
}
51 changes: 51 additions & 0 deletions packages/httpclient-axios/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
{
"name": "@seriouslag/httpclient-axios",
"version": "0.0.1",
"private": true,
"description": "Typed wrapper HttpClient for axios",
"main": "dist/index.umd.js",
"browser": "dist/index.umd.min.js",
"types": "dist/index.d.ts",
"scripts": {
"build": "rollup -c"
},
"contributors": [
{
"name": "Landon Gavin",
"email": "[email protected]",
"url": "https://landongavin.dev"
}
],
"repository": {
"type": "git",
"url": "git+https://github.com/seriouslag/HttpClient.git"
},
"keywords": [
"httpClient",
"typescript",
"axios",
"fetch"
],
"author": "[email protected]",
"license": "MIT",
"bugs": {
"url": "https://github.com/seriouslag/HttpClient/issues"
},
"files": [
"dist",
"src",
"package.json",
"tsconfig.json",
"tsconfig.build.json",
"README.md",
"LICENSE"
],
"homepage": "https://github.com/seriouslag/HttpClient#readme",
"dependencies": {
"@seriouslag/httpclient": "^0.0.16",
"axios": "~0.24.0"
},
"peerDependencies": {
"axios": "~0.24.0"
}
}
74 changes: 74 additions & 0 deletions packages/httpclient-axios/rollup.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import typescript from 'rollup-plugin-typescript2';
import NodeBuiltins from 'rollup-plugin-node-builtins';
import NodeGlobals from 'rollup-plugin-node-globals';
import resolve from '@rollup/plugin-node-resolve';
import babel from '@rollup/plugin-babel';
import { terser } from 'rollup-plugin-terser';
import pkg from './package.json';

const typescriptPlugin = typescript({
tsconfig: 'tsconfig.build.json',
});

const nodeBuiltins = NodeBuiltins();
const nodeGlobalsPlugin = NodeGlobals();
const external = [/@babel\/runtime/, 'axios', ...Object.keys(pkg.dependencies), ...Object.keys(pkg.peerDependencies)];

const babelPlugin = babel({
extensions: ['.js', '.ts'],
babelHelpers: 'runtime',
exclude: 'node_module/**',
babelrc: true,
plugins: [
'@babel/plugin-transform-runtime'
],
presets: [
'@babel/preset-env', {},
],
});

export default [
// UMD
{
external,
input: 'src/index.ts',
output: {
file: 'dist/index.umd.js',
format: 'umd',
name: 'HttpClient-axios',
indent: false,
globals: {
axios: 'axios',
},
},
plugins: [
typescriptPlugin,
nodeBuiltins,
nodeGlobalsPlugin,
babelPlugin,
resolve({ preferBuiltins: true }),
],
},
// UMD minified
{
external,
input: 'src/index.ts',
output: {
file: 'dist/index.umd.min.js',
format: 'umd',
name: 'HttpClient-axios',
indent: false,
globals: {
axios: 'axios',
},
},
plugins: [
typescriptPlugin,
nodeBuiltins,
nodeGlobalsPlugin,
babelPlugin,
resolve({ preferBuiltins: true }),
terser(),
],
},
];
86 changes: 86 additions & 0 deletions packages/httpclient-axios/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import axios, { AxiosInstance, AxiosRequestConfig } from 'axios';
import { Request, RequestConfig, HttpResponse, IHttpClientAdaptor, Logger, ABORT_MESSAGE, AbortError, HttpHeader } from '@seriouslag/httpclient';

export class AxiosRequest<T = unknown> implements Request<T> {
constructor (private client: AxiosInstance, private config: RequestConfig, private axiosConfig: AxiosRequestConfig) { }

public async do (): Promise<HttpResponse<T>> {
const { CancelToken } = axios;

const { noGlobal, cancelToken } = this.config;
const client = noGlobal ? axios.create() : this.client;
const source = CancelToken.source();

let hasResolvedRequest = false;
let hasCanceled = false;
// bind cancel token
if (cancelToken) {
// if signal is already aborted then cancel the axios source
if (cancelToken.signal.aborted) {
hasCanceled = true;
source.cancel(ABORT_MESSAGE);
throw new AbortError(ABORT_MESSAGE);
}
cancelToken.signal.addEventListener('abort', () => {
// do not cancel if already canceled
if (hasCanceled)
return;
// do not cancel if request is already resolved
if (hasResolvedRequest)
return;
// if signal is aborted then cancel the axios source
source.cancel(ABORT_MESSAGE);
hasCanceled = true;
});
}

const response = await client.request<T>({
...this.axiosConfig, cancelToken: source.token,
});
hasResolvedRequest = true;
const formattedResponse: HttpResponse<T> = {
data: response.data,
headers: response.headers ?? {},
status: response.status,
statusText: response.statusText,
};
return formattedResponse;
}
}

export class AxiosHttpClientAdaptor implements IHttpClientAdaptor {

private client: AxiosInstance;

constructor (options: AxiosRequestConfig = {}, private logger?: Logger) {
this.client = axios.create(options);
}

public buildRequest<T = unknown> (config: RequestConfig) {

const { headers, data, responseType, responseEncoding, url, method, params } = config;

const axiosConfig: AxiosRequestConfig = {
url, method, headers, data, params, responseType,
// never have axios throw and error. Return request.
validateStatus: () => true,
};
// axios for some reason does not allow the responseEncoding to be set
if (responseEncoding)
(axiosConfig as any).responseEncoding = responseEncoding;

const request = new AxiosRequest<T>(this.client, config, axiosConfig);
return request;
}

/** Add header to each HTTP request for this instance */
public addGlobalApiHeader (header: HttpHeader) {
const headers: Record<string, any> = this.client.defaults.headers!; // default headers always exist
headers.common[header.name] = header.value;
}

/** Add headers to each HTTP request for this instance */
public addGlobalApiHeaders (headers: HttpHeader[]) {
headers.forEach((header) => this.addGlobalApiHeader(header));
}
}
24 changes: 24 additions & 0 deletions packages/httpclient-axios/tsconfig.base.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"incremental": true,
"composite": true,
"noEmit": false,
"baseUrl": "src",
"rootDir": "src",
"outDir": "dist",
"paths": {
"@seriouslag/*": [
"../../*"
]
}
},
"include": [
"./src/**/*.ts"
],
"exclude": [
"./**/*.test.*",
"dist/**/*",
"node_modules/**/*"
]
}
Loading

0 comments on commit 59dd525

Please sign in to comment.