Skip to content

pencil(uniapp):demo #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 18, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 127 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,15 @@ httpClient.get<CommonResponse>('/')

# Custom Backend (UniApp)
```typescript
import { HttpClient } from 'rx-http-kit';
import {
HttpClient, HttpBackend, HttpRequest, HttpEvent, HttpHeaders,
HttpHeaderResponse, HttpStatusCode,
HttpResponse,HttpErrorResponse,HttpModule,HttpInterceptingHandler,HttpInterceptor,HttpHandler,HttpResponseBase
} from 'rx-http-kit';
import { catchError, mergeMap, Observable, Observer, of, throwError } from "rxjs";
import { Storage } from '@util/storage';
import {Config} from '@config'

export class UniBackend extends HttpBackend {
handle(req: HttpRequest<any>): Observable<HttpEvent<any>> {
return new Observable((observer: Observer<HttpEvent<any>>) => {
Expand All @@ -66,7 +74,7 @@ export class UniBackend extends HttpBackend {
data: req.body,
method: req.method as any,
withCredentials: req.withCredentials,
header: req,
header: req.headers.toObject(),
success: (result: UniApp.RequestSuccessCallbackResult) => {
let status = result.statusCode;
const _header = new HttpHeaders(result.header);
Expand Down Expand Up @@ -119,6 +127,119 @@ export class UniBackend extends HttpBackend {
}
}

export class MyInterceptor implements HttpInterceptor{

getAdditionalHeaders(headers: HttpHeaders) {
const AspMap = {
'zh-Hans': 'zh-Hans',
en: 'en',
};
const LangMap = {
'zh-Hans': 'zh-CN',
en: 'en-US',
};

const SysLangMap = {
'zh-CN': 'zh-Hans',
zh: 'zh-Hans',
zh_CN: 'zh-Hans',
'en-US': 'en',
en: 'en',
};
const offset = new Date().getTimezoneOffset() / 60;
let systemLanguage: any;
// #ifdef H5
systemLanguage = navigator.language;
// #endif
// #ifdef MP-WEIXIN
systemLanguage = uni.getSystemInfoSync().language;
// #endif
let defaultLuang = Storage.getItemSync(Config.i18nLocal) || SysLangMap[systemLanguage] || SysLangMap.zh_CN;

return {
'.aspnetcore.culture': AspMap[defaultLuang],
'accept-language': LangMap[defaultLuang],
'.Timezone-Offset': offset >= 0 ? `+${offset}` : `${offset}`,
Authorization: `Bearer ${Storage.getItemSync('token') || ''}`
};
}

intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
console.log("🚀 ~ file: rx-http.ts ~ line 112 ~ MyInterceptor ~ req", req)
let url = req.url;
if (
!/assets\//.test(url) &&
!url.startsWith('https://') &&
!url.startsWith('http://')
) {
const baseUrl= Config.baseUrl!;
url =
baseUrl +
(baseUrl.endsWith('/') && url.startsWith('/') ? url.substring(1) : url);
}

const newReq = req.clone({
url,
setHeaders: this.getAdditionalHeaders(req.headers)
});
console.log("🚀 ~ file: rx-http.ts ~ line 129 ~ MyInterceptor ~ newReq", newReq)
return next.handle(newReq).pipe(
mergeMap((ev) => {
// Normalization
if (ev instanceof HttpResponseBase) {
return this.handleData(ev, newReq, next);
}
// Next
return of(ev);
}),
catchError((err: HttpErrorResponse) => this.handleData(err, newReq, next))
);
}

private handleData(ev: HttpResponseBase, req: HttpRequest<any>, next: HttpHandler): Observable<any> {
switch (ev.status) {
case 200:
if (ev instanceof HttpResponse) {
const body = ev.body;
if (body) {
return of(
new HttpResponse({
body: (body?.result ? body?.result : body) || null,
headers: ev.headers,
status: ev.status,
statusText: ev.statusText,
url: ev.url as any
})
);
}
}
break;
case 401:
break;
case 403:
case 404:
case 500:
break;
default:
if (ev instanceof HttpErrorResponse) {
console.warn(
'未可知错误,大部分是由于后端不支持跨域CORS或无效配置引起'
ev
);
}
break;
}
if (ev instanceof HttpErrorResponse) {
return throwError(()=> ev);
} else {
return of(ev);
}
}
}

export class HttpUniModule implements HttpModule {
httpInterceptor: HttpInterceptingHandler;
constructor(private handler: HttpInterceptor[] = []) {
Expand All @@ -132,6 +253,10 @@ export class HttpUniModule implements HttpModule {
return new HttpClient(this.httpInterceptor);
}
}



export const RxHttpClient = new HttpUniModule([new MyInterceptor()]).getHttpClient();
```

# Interception
Expand Down
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "rx-http-kit",
"version": "1.0.11",
"version": "1.0.13",
"description": "HTTP Client Development Kit based by rxjs",
"main": "lib/index.js",
"module": "lib/index.es.js",
Expand All @@ -17,6 +17,8 @@
"ci": "pnpm install --no-frozen-lockfile && pnpm run rollup && pnpm link ./",
"test:compile": "tsc -p ./tsconfig-test.json",
"test:server": "pnpm run test:compile && forever start test/dist/server.js",
"test:server:stop": "forever stop test/dist/server.js",
"test:local:server": "pnpm run test:compile && node test/dist/server.js",
"test:mocha": "mocha 'test/dist/*.spec.js'",
"test": "pnpm run test:server && pnpm run test:mocha",
"types": "tsc -p ./tsconfig.types.json",
Expand Down
1 change: 1 addition & 0 deletions test/interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ export class MyInterceptor implements HttpInterceptor {
url,
setHeaders: this.getAdditionalHeaders(req.headers)
});
console.log("🚀 ~ file: interceptor.ts ~ line 131 ~ MyInterceptor ~ newReq", newReq)
return next.handle(newReq).pipe(
mergeMap((ev) => {
// Normalization
Expand Down
5 changes: 4 additions & 1 deletion test/node.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,10 @@ describe('HttpXHR2Module', function () {
'/200',
{ id: '123456' },
{
params: { name: 'jack' }
params: { name: 'jack' },
headers: {
abc: 'sdfasdf'
}
}
),
httpClient.delete<CommonResponse>('/200', {
Expand Down
3 changes: 2 additions & 1 deletion test/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ app
console.log(
'🚀 ~ file: server.ts ~ line 41 ~ app.listen ~ request',
req.method,
req.url
req.url,
req.headers
);
})
.once('listening', (stream) => {
Expand Down
2 changes: 1 addition & 1 deletion types/packages/headers.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,6 @@ export declare class HttpHeaders {
*/
forEach(fn: (name: string, values: string[]) => void): void;
toObject(): {
[key: string]: string[];
[key: string]: string;
};
}