Skip to content

Commit

Permalink
Feat/mock (#83)
Browse files Browse the repository at this point in the history
* 暂存

* update code

* update code

* remove readonly prop

* Feat/mock (#77)

* remove readonly prop

* merge code

* fix: env error

* chore: upgrade indexdb version to v2

* feat: copy mock url

* feat: preview mock

* feat: mock data auto sync apidata

* feat: mock data auto sync apidata

* fix: some thing

* update code

* fix: some thing
  • Loading branch information
buqiyuan authored Jun 20, 2022
1 parent 444b1ca commit e920905
Show file tree
Hide file tree
Showing 14 changed files with 202 additions and 89 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -68,4 +68,4 @@
"node-module-alias": {
"eo": "./out"
}
}
}
76 changes: 38 additions & 38 deletions src/platform/node/mock-server/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import express from 'express';
import type { Response } from 'express';
import portfinder from 'portfinder';
import { createProxyMiddleware } from 'http-proxy-middleware';
// import { createProxyMiddleware } from 'http-proxy-middleware';
import { BrowserView, ipcMain } from 'electron';
import type { Server } from 'http';
import type { AddressInfo } from 'net';
Expand Down Expand Up @@ -30,7 +30,7 @@ export class MockServer {
private server: Server;
private view: BrowserView;
private configuration = new Configuration();
private apiProxy: ReturnType<typeof createProxyMiddleware>;
// private apiProxy: ReturnType<typeof createProxyMiddleware>;
/** mock server url */
private mockUrl = '';

Expand All @@ -43,49 +43,49 @@ export class MockServer {
* create proxy server
*/
private createProxyServer() {
this.apiProxy = createProxyMiddleware({
target: 'http://www.example.org',
changeOrigin: true,
pathFilter: (path) => {
// console.log('pathFilter path', path, path.match('^/(http|https)://'));
return Boolean(path.match('^/(http|https)://'));
},
pathRewrite: (path, req) => {
// console.log('pathRewrite', path, req.url);
return path.replace(req.url, '');
},
router: (req) => {
console.log('router req', req.url);
return req.url.slice(1);
},
});
// this.apiProxy = createProxyMiddleware({
// target: 'http://www.example.org',
// changeOrigin: true,
// pathFilter: (path) => {
// // console.log('pathFilter path', path, path.match('^/(http|https)://'));
// return Boolean(path.match('^/(http|https)://'));
// },
// pathRewrite: (path, req) => {
// // console.log('pathRewrite', path, req.url);
// return path.replace(req.url, '');
// },
// router: (req) => {
// console.log('router req', req.url);
// return req.url.slice(1);
// },
// });

this.app.use(this.apiProxy);
// this.app.use(this.apiProxy);

this.app.all('*', (req, res, next) => {
if (!protocolReg.test(req.url)) {
// match request type
const isMatchType = this.configuration.getModuleSettings<boolean>('eoapi-features.mock.matchType');
if (req.query.mockID || isMatchType) {
this.view.webContents.send('getMockApiList', JSON.parse(jsonStringify(req)));
ipcMain.once('getMockApiList', (event, message) => {
console.log('getMockApiList message', message);
const { response = {}, statusCode = 200 } = message;
res.statusCode = statusCode;
if (res.statusCode === 404) {
this.send404(res, isMatchType);
} else {
res.send(response);
}
next();
});
} else {
this.send404(res, isMatchType);
// if (!protocolReg.test(req.url)) {
// match request type
const isMatchType = this.configuration.getModuleSettings<boolean>('eoapi-features.mock.matchType');
if (req.query.mockID || isMatchType) {
this.view.webContents.send('getMockApiList', JSON.parse(jsonStringify(req)));
ipcMain.once('getMockApiList', (event, message) => {
console.log('getMockApiList message', message);
const { response = {}, statusCode = 200 } = message;
res.statusCode = statusCode;
if (res.statusCode === 404) {
this.send404(res, isMatchType);
} else {
res.send(response);
}
next();
}
});
} else {
this.send404(res, isMatchType);
next();
}
// } else {
// next();
// }
});
}

Expand Down
2 changes: 1 addition & 1 deletion src/workbench/browser/src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ import { HTTP_INTERCEPTORS } from '@angular/common/http';
NgxsModule.forRoot([EnvState]),
],
providers: [
RemoteService,
MessageService,
StorageService,
RemoteService,
IndexedDBStorage,
HttpStorage,
NzMessageService,
Expand Down
14 changes: 9 additions & 5 deletions src/workbench/browser/src/app/pages/api/api.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { Subject, takeUntil } from 'rxjs';
import { Message, MessageService } from '../../shared/services/message';
import { ApiService } from './api.service';
import { StorageService } from '../../shared/services/storage';
import { RemoteService } from 'eo/workbench/browser/src/app/shared/services/remote/remote.service';

@Component({
selector: 'eo-api',
Expand All @@ -29,24 +30,27 @@ export class ApiComponent implements OnInit, OnDestroy {
routerLink: 'test',
title: '测试',
},
{
routerLink: 'mock',
title: 'Mock',
},
];
private destroy$: Subject<void> = new Subject<void>();

constructor(
private route: ActivatedRoute,
private apiService: ApiService,
private messageService: MessageService,
private storage: StorageService
private storage: StorageService,
private remoteService: RemoteService
) {}

ngOnInit(): void {
this.watchChangeRouter();
this.watchApiAction();
this.watchDataSourceChange();
if (this.remoteService.isElectron) {
this.TABS.push({
routerLink: 'mock',
title: 'Mock',
});
}
}
ngOnDestroy() {
this.destroy$.next();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
<eo-api-detail-body [bodyType]="apiData.responseBodyType" [model]="apiData.responseBody"
[jsonRootType]="apiData.responseBodyJsonType"></eo-api-detail-body>
</div>
<div>
<div *ngIf="isElectron">
<p class="api_line">MOCK </p>
<eo-api-detail-mock [apiData]="apiData"></eo-api-detail-mock>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
import { treeToListHasLevel } from '../../../utils/tree/tree.utils';
import { reverseObj } from '../../../utils';
import { StorageService } from '../../../shared/services/storage';
import { RemoteService } from 'eo/workbench/browser/src/app/shared/services/remote/remote.service';

export interface TreeNodeInterface {
key?: string;
Expand All @@ -28,11 +29,14 @@ export interface TreeNodeInterface {
})
export class ApiDetailComponent implements OnInit {
apiData: ApiData | any = {};
get isElectron() {
return this.remoteService.isElectron;
}
CONST = {
BODY_TYPE: reverseObj(ApiBodyType),
JSON_ROOT_TYPE: reverseObj(JsonRootType),
};
constructor(private route: ActivatedRoute, private storage: StorageService) {}
constructor(private route: ActivatedRoute, private storage: StorageService, private remoteService: RemoteService) {}
ngOnInit(): void {
this.route.queryParams.subscribe((params) => {
if (params.uuid) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<eo-table [(model)]="mocklList" [columns]="mockListColumns" [dataModel]="{ name: '', value: '', description: '' }">
<ng-template cell="url" let-scope="scope" let-index="index">
<span nzTooltipTitle="点击复制" nzTooltipPlacement="top" nz-tooltip (click)="copyText(scope.url )">
<span nzTooltipTitle="点击复制" nzTooltipPlacement="top" nz-tooltip (click)="copyText(scope.url )" class="truncate">
{{ scope.url }}
</span>
</ng-template>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Component, OnChanges, Input, SimpleChanges } from '@angular/core';
import { Component, OnChanges, OnInit, Input, SimpleChanges } from '@angular/core';
import { ApiTestService } from 'eo/workbench/browser/src/app/pages/api/test/api-test.service';
import { eoFormatRequestData } from 'eo/workbench/browser/src/app/shared/services/api-test/api-test.utils';
import { RemoteService } from 'eo/workbench/browser/src/app/shared/services/remote/remote.service';
Expand All @@ -7,13 +7,17 @@ import { copyText } from 'eo/workbench/browser/src/app/utils';
import { tree2obj } from 'eo/workbench/browser/src/app/utils/tree/tree.utils';
import { ApiData, ApiMockEntity, StorageRes, StorageResStatus } from '../../../../shared/services/storage/index.model';
import { NzMessageService } from 'ng-zorro-antd/message';
import { messageService } from 'eo/workbench/browser/src/app/shared/services/message/message.service';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { Message } from 'eo/workbench/browser/src/app/shared/services/message';

@Component({
selector: 'eo-api-detail-mock',
templateUrl: './api-detail-mock.component.html',
styleUrls: ['./api-detail-mock.component.scss'],
})
export class ApiDetailMockComponent implements OnChanges {
export class ApiDetailMockComponent implements OnInit, OnChanges {
@Input() apiData: ApiData;
get mockUrl() {
return this.remoteService.mockUrl;
Expand All @@ -30,39 +34,50 @@ export class ApiDetailMockComponent implements OnChanges {
{ title: '创建方式', slot: 'createWay' },
{ title: 'URL', slot: 'url' },
];
private destroy$: Subject<void> = new Subject<void>();
constructor(
private storageService: StorageService,
private apiTest: ApiTestService,
private remoteService: RemoteService,
private message: NzMessageService
) {}

async ngOnInit() {
messageService
.get()
.pipe(takeUntil(this.destroy$))
.subscribe((inArg: Message) => {
switch (inArg.type) {
case 'mockAutoSyncSuccess':
this.initMockList(this.apiData);
}
});
}

async ngOnChanges(changes: SimpleChanges): Promise<void> {
const { apiData } = changes;
if (apiData.currentValue?.uuid) {
this.initMockList(apiData.currentValue);
}

async initMockList(apiData: ApiData) {
if (apiData?.uuid) {
const apiDataID = Number(this.apiData.uuid);
console.log('apiDataID', this.apiData, apiDataID);
const mockRes = await this.getMockByApiDataID(apiDataID);
if (window.eo?.getMockUrl && Array.isArray(mockRes) && mockRes.length === 0) {
const mock = this.createMockObj({ name: '默认 Mock', createWay: 'system' });
const res = await this.createMock(mock);
res.data.url = this.getApiUrl(res.data.uuid);
this.mocklList = [res.data];
} else {
this.mocklList = mockRes.map((item) => {
item.url = this.getApiUrl(item.uuid);
return item;
});
}
this.mocklList = mockRes.map((item) => {
item.url = this.getApiUrl(item.uuid);
return item;
});
}
}

getApiUrl(uuid?: number) {
const data = eoFormatRequestData(this.apiData, { env: {} }, 'en-US');
const uri = this.apiTest.transferUrlAndQuery(data.URL, this.apiData.queryParams, {
base: 'query',
replaceType: 'replace',
}).url;
const url = new URL(`${this.mockUrl}/${uri}`.replace(/(?<!:)\/{2,}/g, '/'));
const url = new URL(`${this.mockUrl}/${uri}`.replace(/(?<!:)\/{2,}/g, '/'), 'https://github.com/');
uuid && url.searchParams.set('mockID', uuid + '');
return decodeURIComponent(url.toString());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@

<div class="mt-[20px]">
<eo-table [(model)]="mocklList" [columns]="mockListColumns" [dataModel]="{ name: '', value: '', description: '' }">
<ng-template cell="name" let-scope="scope" let-index="index">
<div class="truncate w-[120px]">{{scope.name}}</div>
</ng-template>
<ng-template cell="url" let-scope="scope" let-index="index">
<span nzTooltipTitle="点击复制" nzTooltipPlacement="top" nz-tooltip (click)="copyText(scope.url )">
<span nzTooltipTitle="点击复制" nzTooltipPlacement="top" nz-tooltip (click)="copyText(scope.url )" class="truncate">
{{ scope.url }}
</span>
</ng-template>
Expand All @@ -29,7 +32,7 @@
<div class="w-full main-content">
<form nz-form nzLayout="vertical">
<nz-form-item>
<nz-form-label nzFor="currentEditMock.name">Mock名称</nz-form-label>
<nz-form-label nzFor="currentEditMock.name">Mock 名称</nz-form-label>
<nz-form-control>
<input nz-input name="name" type="text" [(ngModel)]="currentEditMock.name"
[readonly]="currentEditMock.createWay=== 'system'" />
Expand Down
Loading

0 comments on commit e920905

Please sign in to comment.