Skip to content

Commit

Permalink
fix(components): [api-group-tree] sort handle not show (#84)
Browse files Browse the repository at this point in the history
* update code

* update code
  • Loading branch information
buqiyuan authored Jun 22, 2022
1 parent e920905 commit f2ba7b9
Show file tree
Hide file tree
Showing 9 changed files with 200 additions and 128 deletions.
6 changes: 3 additions & 3 deletions src/workbench/browser/src/app/app.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ import { NzModalService } from 'ng-zorro-antd/modal';
export class AppComponent {
constructor(
private theme: ThemeService,
private app: AppService,
private remoteService: RemoteService,
private modal: NzModalService
private modal: NzModalService,
private appService: AppService
) {
this.theme.changeTheme();
this.checkRemoteServerConnect();
Expand All @@ -37,7 +37,7 @@ export class AppComponent {
nzClosable: false,
nzOnOk: () => {
clearTimeout(timer);
this.remoteService.switchDataSource();
timer && this.remoteService.switchDataSource();
},
});
}
Expand Down
60 changes: 42 additions & 18 deletions src/workbench/browser/src/app/app.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,50 +3,74 @@ import { Injectable } from '@angular/core';
import type { IpcRenderer } from 'electron';
import { ApiData, ApiMockEntity } from 'eo/workbench/browser/src/app/shared/services/storage/index.model';
import { IndexedDBStorage } from 'eo/workbench/browser/src/app/shared/services/storage/IndexedDB/lib/';
import { RemoteService } from 'eo/workbench/browser/src/app/shared/services/remote/remote.service';

@Injectable({
providedIn: 'root',
})
export class AppService {
private ipcRenderer: IpcRenderer = window.require?.('electron')?.ipcRenderer;

constructor(private indexedDBStorage: IndexedDBStorage) {
constructor(private indexedDBStorage: IndexedDBStorage, private remoteService: RemoteService) {
if (this.ipcRenderer) {
this.ipcRenderer.on('getMockApiList', async (event, req = {}) => {
const sender = event.sender;
console.log('req', req);
const isEnabledMatchType = window.eo?.getModuleSettings?.('eoapi-features.mock.matchType');
// console.log('wo接收到了哇', event, message);
const { mockID } = req.query;
if (Number.isInteger(Number(mockID))) {
try {
const mock = await this.getMockByMockID(Number(mockID));
if (mock.createWay === 'system' && mock.apiDataID) {
const apiData = await this.getApiData(Number(mock.apiDataID));
mock.response =
tree2obj([].concat(apiData.responseBody), { key: 'name', valueKey: 'description' }) || mock.response;
const apiData = await this.getApiData(Number(mock.apiDataID));
if (isEnabledMatchType) {
const result = await this.matchApiData(1, req);
return sender.send('getMockApiList', result);
} else {
mock.response = this.generateResponse(apiData.responseBody) || mock.response;
}
event.sender.send('getMockApiList', mock);
sender.send('getMockApiList', mock);
} catch (error) {
event.sender.send('getMockApiList', {
sender.send('getMockApiList', {
response: {
message: error,
},
});
}
// 是否开启了匹配请求方式
} else if (window.eo?.getModuleSettings?.('eoapi-features.mock.matchType')) {
const apiList = await this.getAllApi(1);
const apiData = apiList.find((n) => n.method === req.method && n.uri.trim() === req.url);
event.sender.send(
'getMockApiList',
apiData
? { response: tree2obj([].concat(apiData.responseBody), { key: 'name', valueKey: 'description' }) }
: { statusCode: 404 }
);
// Whether the matching request mode is enabled
} else if (isEnabledMatchType) {
const response = await this.matchApiData(1, req);
sender.send('getMockApiList', response);
} else {
event.sender.send('getMockApiList', { response: { message: `没有找到ID为${mockID}的mock!` }, url: req.url });
sender.send('getMockApiList', { response: { message: `没有找到ID为${mockID}的mock!` }, url: req.url });
}
});
}
}

/**
* generate response data
* @returns
*/
generateResponse(responseBody: ApiData['responseBody']) {
return tree2obj([].concat(responseBody), { key: 'name', valueKey: 'description' });
}
/**
* match apiData by method and url
* @param {Number} projectID
* @param {Object} req
* @returns {Object}
*/
async matchApiData(projectID = 1, req) {
const apiList = await this.getAllApi(projectID);
const { pathname } = new URL(req.url, this.remoteService.mockUrl);
const apiData = apiList.find((n) => {
const uri = n.uri.trim().startsWith('/') ? n.uri.trim() : `/${n.uri.trim()}`;
return n.method === req.method && uri === pathname;
});
return apiData ? { response: this.generateResponse(apiData.responseBody) } : { statusCode: 404 };
}

/**
* get mock by mockID
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,9 @@ export class ApiDetailMockComponent implements OnInit, OnChanges {

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

async initMockList(apiData: ApiData) {
Expand All @@ -65,20 +67,22 @@ export class ApiDetailMockComponent implements OnInit, OnChanges {
console.log('apiDataID', this.apiData, apiDataID);
const mockRes = await this.getMockByApiDataID(apiDataID);
this.mocklList = mockRes.map((item) => {
item.url = this.getApiUrl(item.uuid);
item.url = this.getApiUrl(item);
return item;
});
}
}

getApiUrl(uuid?: number) {
getApiUrl(mock?: ApiMockEntity) {
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, '/'), 'https://github.com/');
uuid && url.searchParams.set('mockID', uuid + '');
if (mock?.createWay === 'custom' && mock.uuid) {
url.searchParams.set('mockID', mock.uuid + '');
}
return decodeURIComponent(url.toString());
}
/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,4 @@
<button nz-button nzType="primary" (click)="handleSave()">保存</button>
<button nz-button nzType="default" (click)="handleCancel()">取消</button>
</div>
</nz-modal>
</nz-modal>
21 changes: 11 additions & 10 deletions src/workbench/browser/src/app/pages/api/mock/api-mock.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,9 @@ export class ApiMockComponent implements OnInit, OnChanges {

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

async initMockList(apiDataID: number) {
Expand All @@ -96,16 +98,16 @@ export class ApiMockComponent implements OnInit, OnChanges {
return item;
});
}
getApiUrl(apiData?: ApiData) {

getApiUrl(mock?: ApiMockEntity) {
const data = eoFormatRequestData(this.apiData, { env: {} }, 'en-US');
const uri = this.apiTest.transferUrlAndQuery(data.URL, this.apiData.queryParams, {
base: 'query',
replaceType: 'replace',
}).url;
console.log('this.mockUrl', this.mockUrl);
const url = new URL(`${this.mockUrl}/${uri}`.replace(/(?<!:)\/{2,}/g, '/'), 'https://github.com/');
if (apiData || this.isEdit) {
url.searchParams.set('mockID', (apiData || this.currentEditMock).uuid + '');
if (mock?.createWay === 'custom' && mock.uuid) {
url.searchParams.set('mockID', mock.uuid + '');
}
return decodeURIComponent(url.toString());
}
Expand Down Expand Up @@ -225,22 +227,21 @@ export class ApiMockComponent implements OnInit, OnChanges {
}
async handleSave() {
this.isVisible = false;
this.isEdit
? (this.mocklList[this.currentEditMockIndex] = this.currentEditMock)
: this.mocklList.push(this.currentEditMock);

if (this.currentEditMock.createWay === 'system') return;

this.mocklList = [...this.mocklList];
if (this.isEdit) {
await this.updateMock(this.currentEditMock, Number(this.currentEditMock.uuid));
this.message.success('修改成功');
this.mocklList[this.currentEditMockIndex] = this.currentEditMock;
} else {
const result = await this.createMock(this.currentEditMock);
Object.assign(this.currentEditMock, result.data);
this.message.success('新增成功');
this.mocklList.push(this.currentEditMock);
}
this.currentEditMock.url = this.getApiUrl();
this.currentEditMock.url = this.getApiUrl(this.currentEditMock);
this.mocklList = [...this.mocklList];
}
handleCancel() {
this.isVisible = false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,20 @@
},
{
"type": "object",
"title": "扩展",
"title": "Mock",
"order": 2,
"properties": {
"mock.matchType": {
"type": "boolean",
"default": true,
"label": "匹配请求方式",
"description": "开启后,系统会匹配和API文档请求方式(GET、POST...)一致的 Mock"
}
}
},
{
"type": "object",
"title": "插件",
"order": 2,
"properties": {
"extension.autoupdate": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@ const METHOD = ['POST', 'GET', 'PUT', 'DELETE', 'HEAD', 'OPTIONS', 'PATCH'],
REQUEST_BODY_TYPE = ['formData', 'raw', 'json', 'xml', 'binary'];

export const eoFormatRequestData = (data, opts = { env: {} }, locale) => {
const formatUri = (uri, rest=[]) => {
const formatUri = (uri, rest = []) => {
if (!Array.isArray(rest)) {
return uri;
}
let result = uri;
const restByName = rest.reduce((acc, val) => {
if (!val.required || !val.name) {
Expand All @@ -21,6 +24,9 @@ export const eoFormatRequestData = (data, opts = { env: {} }, locale) => {
return result;
};
const formatList = (inArr) => {
if (!Array.isArray(inArr)) {
return [];
}
const result = [];
inArr.forEach((val) => {
if (!val.name) {
Expand Down Expand Up @@ -58,7 +64,7 @@ export const eoFormatRequestData = (data, opts = { env: {} }, locale) => {
checkbox: val.required,
listDepth: val.listDepth || 0,
paramKey: val.name,
files:val.files?.map(val=>val.dataUrl),
files: val.files?.map((val) => val.dataUrl),
paramType: typeMUI[val.type],
paramInfo: val.value === undefined ? val.example : val.value,
});
Expand Down Expand Up @@ -101,7 +107,7 @@ export const eoFormatRequestData = (data, opts = { env: {} }, locale) => {
};
export const eoFormatResponseData = ({ report, history, id }) => {
let { httpCode, ...response } = history.resultInfo;
console.log(report, history, id)
console.log(report, history, id);
response = {
statusCode: httpCode,
...response,
Expand All @@ -117,7 +123,7 @@ export const eoFormatResponseData = ({ report, history, id }) => {
} = {
id: id,
general: report.general,
response: {blobFileName:report.blobFileName,...response},
response: { blobFileName: report.blobFileName, ...response },
report: {
request: {
requestHeaders: report.request.headers.map((val) => ({ name: val.key, value: val.value })),
Expand Down
Loading

0 comments on commit f2ba7b9

Please sign in to comment.