Skip to content

Commit

Permalink
add rest mock client plugin for test
Browse files Browse the repository at this point in the history
  • Loading branch information
maskerliu committed Jan 3, 2025
1 parent 7b76722 commit bbc5faa
Show file tree
Hide file tree
Showing 16 changed files with 282 additions and 118 deletions.
25 changes: 12 additions & 13 deletions .build-scripts/runner.dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,8 @@ function startMain(): Promise<void> {
if (process.platform === "win32") {
const pid = electronProc.pid
exec(`TASKKILL /F /IM electron.exe`, (err, data) => {
if (err) console.log(err)
else console.log(chalk['green']("kill pid: " + pid + " success!"))
if (err) console.log(chalk.bgRed.white(err))
else console.log(chalk.bgRedBright.whiteBright(` kill pid: ${pid} success!`.padEnd(process.stdout.columns - 20, ' ')))
electronProc = null
startElectron()
manualRestart = false
Expand All @@ -122,16 +122,11 @@ function startMain(): Promise<void> {
function startElectron() {

let args = [
// '--trace-warnings',
// '--inspect=5858',
// '--experimental-worker',
// '--experimental-wasm-threads',
// '--unhandled-rejections=strict',
path.join(dirname, '../dist/electron/main.cjs')
]

if (process.platform !== 'linux') {
args.push('--remote-debugging-port=9223', '--experimental-wasm-bulk-memory')
// args.push('--remote-debugging-port=9223', '--experimental-wasm-bulk-memory')
} else {
args.push('--no-sandbox')
}
Expand All @@ -144,12 +139,16 @@ function startElectron() {
}

electronProc = spawn('electron', args, {
stdio: ['inherit', 'inherit', 'inherit'],
detached: false,
stdio: 'inherit',
shell: process.platform === 'win32'
})
electronProc.stdout?.on('data', data => { consoleLog('Electron', data, 'blue') })
electronProc.stderr?.on('data', data => { consoleLog('Electron', data, 'red') })
electronProc.on('close', () => { if (!manualRestart) process.exit() })
// electronProc.stdout.on('data', data => { consoleLog('Electron', data, 'blue') })
// electronProc.stderr.on('data', data => { consoleLog('Electron', data, 'red') })
electronProc.on('close', (code) => {
console.log(chalk.bgYellow.blue(` Electron Process Closed[${code}]`.padEnd(process.stdout.columns - 20, ' ')))
if (!manualRestart) process.exit()
})
}

function consoleLog(proc: string, data: any, color?: string) {
Expand All @@ -172,7 +171,7 @@ function consoleLog(proc: string, data: any, color?: string) {
}

async function start() {
console.log(chalk.bgGreen.white(' getting ready...'.padEnd(process.stdout.columns - 20, ' ')))
console.log(chalk.bgGreen.yellowBright(' getting ready...'.padEnd(process.stdout.columns - 20, ' ')))

try {
let ips = getLocalIPs()
Expand Down
4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,10 @@
"cors": "^2.8.5",
"express": "^4.21.1",
"express-fileupload": "^1.5.1",
"formidable": "^3.5.2",
"inversify": "^6.0.3",
"json-bigint": "^1.0.0",
"multer": "^1.4.4",
"pouchdb-adapter-leveldb": "^9.0.0",
"pouchdb-find": "^9.0.0",
"pouchdb-node": "^9.0.0",
Expand All @@ -56,8 +58,10 @@
"@types/express": "^5.0.0",
"@types/express-fileupload": "^1.5.1",
"@types/express-serve-static-core": "^5.0.0",
"@types/formidable": "^3.4.5",
"@types/json-bigint": "^1.0.4",
"@types/minimist": "^1.2.5",
"@types/multer": "^1.4.6",
"@types/node": "22.7.7",
"@types/pouchdb": "^6.4.2",
"@types/pouchdb-find": "^7.3.3",
Expand Down
58 changes: 19 additions & 39 deletions src/main/MainApp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,37 +30,27 @@ export default class MainApp {

constructor() {
this.iconDir = IS_DEV ? path.join(__dirname, '../../icons') : path.join(__dirname, './static')
let ext = ''
switch (os.platform()) {
case 'win32':
ext = 'ico'
break
case 'darwin':
case 'linux':
ext = 'png'
break
}
let ext = os.platform() == 'win32' ? 'ico' : 'png'
this.trayIconFile = path.join(this.iconDir, `icon.${ext}`)
this.mainServer.bootstrap()
}

public async startApp() {
console.log(os.platform(), os.release(), process.version, process.electron)
app.disableHardwareAcceleration()
app.commandLine.appendSwitch('disable-features', 'OutOfBlinkCors')
app.commandLine.appendSwitch('ignore-certificate-errors')
app.commandLine.appendSwitch('disable-gpu')
app.commandLine.appendSwitch('disable-software-rasterizer')

if (process.env.NODE_ENV == 'development') {
app.commandLine.appendSwitch('trace-deprecation')
app.commandLine.appendSwitch('trace-warnings')
app.commandLine.appendSwitch('experimental-worker')
app.commandLine.appendSwitch('experimental-wasm-threads')
app.commandLine.appendSwitch('inspect', '5858')
app.commandLine.appendSwitch('unhandled-rejections', 'strict')
app.commandLine.appendSwitch('trace-deprecation')
app.commandLine.appendSwitch('inspect', '5858')
}

app.commandLine.appendSwitch('disable-features', 'OutOfBlinkCors')
app.commandLine.appendSwitch('ignore-certificate-errors')
app.commandLine.appendSwitch('disable-gpu')
// app.commandLine.appendSwitch('disable-software-rasterizer')
app.disableHardwareAcceleration()

if (os.platform() == 'linux' && os.userInfo().username == 'root') {
app.commandLine.appendSwitch('disable-chromium-sandbox')
app.commandLine.appendSwitch('disable-gpu-sandbox')
Expand Down Expand Up @@ -134,6 +124,7 @@ export default class MainApp {
titleBarOverlay: { color: "#f8f8f800", symbolColor: "black" },
trafficLightPosition: { x: os.platform() == 'darwin' ? 1030 : 10, y: 10 },
webPreferences: {
offscreen: false,
webSecurity: false,
devTools: true, //process.env.NODE_ENV == 'development',
nodeIntegration: true,
Expand All @@ -144,7 +135,6 @@ export default class MainApp {

this.mainWindow = new BrowserWindow(winOpt)
this.mainWindow.loadURL(this.winURL)
this.mainWindow.webContents.frameRate = 30
this.mainWindow.setVibrancy('window')

this.mainWindow.on('resize', () => {
Expand All @@ -171,16 +161,16 @@ export default class MainApp {
icon: path.join(this.iconDir, 'ic-rule.png'),
label: '用例管理',
click: () => {
this.mainWindow.show()
this.mainWindow.webContents.send(ElectronAPICMD.OpenMockRuleMgr)
this.mainWindow?.show()
this.mainWindow?.webContents.send(ElectronAPICMD.OpenMockRuleMgr)
}
},
{
icon: path.join(this.iconDir, 'ic-setting.png'),
label: '设置',
click: () => {
this.mainWindow.show()
this.mainWindow.webContents.send(ElectronAPICMD.OpenSettings)
this.mainWindow?.show()
this.mainWindow?.webContents.send(ElectronAPICMD.OpenSettings)
}
},
{
Expand Down Expand Up @@ -251,7 +241,6 @@ export default class MainApp {
private initIPCService() {

ipcMain.handle(ElectronAPICMD.Relaunch, (_) => {
console.log(process.resourcesPath)
if (fse.pathExistsSync(path.join(process.resourcesPath, 'update.asar'))) {
const logPath = app.getPath('logs')
const out = fs.openSync(path.join(logPath, 'out.log'), 'a')
Expand Down Expand Up @@ -313,19 +302,7 @@ export default class MainApp {
}

async fullUpdate(version: Version) {
let ext = ''
switch (os.platform()) {
case 'win32':
ext = 'exe'
break
case 'darwin':
ext = 'zip'
break
case 'linux':
ext = 'AppImage'
break
}

let ext = os.platform() == 'linux' ? 'AppImage' : os.platform() == 'darwin' ? 'zip' : 'exe'
let downloadDir = path.join(USER_DATA_DIR, 'update', `installer-${version.version}.${ext}`)
if (os.platform() == 'linux') downloadDir.replace(/ /g, "\\ ")

Expand Down Expand Up @@ -385,7 +362,10 @@ export default class MainApp {
// https://github.com/electron-userland/electron-builder/issues/1129
const errorCode = (e as NodeJS.ErrnoException).code
console.log(
`Cannot run installer: error code: ${errorCode}, error message: "${e.message}", will be executed again using elevate if EACCES, and will try to use electron.shell.openItem if ENOENT`
`Cannot run installer:
error code: ${errorCode},
error message: "${e.message}",
will be executed again using elevate if EACCES, and will try to use electron.shell.openItem if ENOENT`
)
if (errorCode === "UNKNOWN" || errorCode === "EACCES") {
callUsingElevation()
Expand Down
22 changes: 10 additions & 12 deletions src/main/MainServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import axios, { AxiosRequestConfig, HttpStatusCode, Method } from 'axios'
import compression from 'compression'
import cors, { CorsOptions } from 'cors'
import express, { Application, Request, Response } from 'express'
import fileUpload from 'express-fileupload'
// import fileUpload from 'express-fileupload'
import fs from 'fs'
import { Server } from 'http'
import path from 'path'
Expand Down Expand Up @@ -105,23 +105,21 @@ export class MainServer {
this.httpApp.use(express.urlencoded({ limit: '50mb', extended: true, parameterLimit: 50000 }))
this.httpApp.use(express.text({ type: 'application/json', limit: '50mb' }))
this.httpApp.use(express.json())
this.httpApp.use(fileUpload())
// this.httpApp.use(fileUpload())

this.httpApp.use('/appmock', this.appmockRouter.router)

this.httpApp.use('/mapi', this.mapiRouter.router)

this.httpApp.use('/mediaproxy', (req: any, resp: Response) => {
this.proxyCorsMedia(req, resp)
})
this.httpApp.use('/mediaproxy', this.proxyCorsMedia)
this.httpApp.use('/_proxy', (req, resp: Response) => this.proxyService.handleRequest(req, resp))

this.httpApp.all('*', (req: any, resp: Response) => { this.handleRequest(req, resp) })
this.httpApp.all('*', (req: any, resp: Response) => this.handleRequest(req, resp))
}

private async startHttpServer() {
let HTTP: any
let baseDir = process.env.NODE_ENV == 'development' ? '' : __dirname + '/'
// console.log(this.buildConfig, baseDir)
if (this.buildConfig.protocol == 'https') {
HTTP = await import('https')
var key = fs.readFileSync(baseDir + 'cert/private.key')
Expand Down Expand Up @@ -151,9 +149,8 @@ export class MainServer {

this.httpServer.listen(
this.commonService.serverConfig.port,
'0.0.0.0',
() => {
console.log(`--启动本地代理Http服务[${this.commonService.serverConfig.port}]`)
console.log(` http server bootstrap[${this.commonService.serverConfig.port}]`)
let config = this.commonService.serverConfig
config.portValid = true
this.commonService.saveServerConfig(config)
Expand All @@ -163,17 +160,18 @@ export class MainServer {
}

private handleRequest(req: any, resp: Response) {
if (/^\/appmock\//.test(req.path)) return
// if (/^\/appmock\//.test(req.path)) return
if (/^\/burying-point\//.test(req.path)) {
let buf = []
req.on('data', (data: any) => { buf.push(data) })
req.on('end', () => {
req.rawbody = Buffer.concat(buf)
this.proxyService.handleStatRequest(req, resp)
})
} else {
this.proxyService.handleRequest(req, resp)
}
// else {
// this.proxyService.handleRequest(req, resp)
// }
}

private async proxyCorsMedia(req: Request, resp: Response) {
Expand Down
18 changes: 0 additions & 18 deletions src/main/MainUpdater.ts

This file was deleted.

5 changes: 1 addition & 4 deletions src/main/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

'use strict'
import { install } from 'source-map-support'
import path from 'path'
import { install } from 'source-map-support'
import MainApp from './MainApp'

install()
Expand All @@ -11,8 +11,5 @@ if (process.env.NODE_ENV !== 'development') {
}

process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true'


let mainApp = new MainApp()

mainApp.startApp()
48 changes: 33 additions & 15 deletions src/main/router/BaseRouter.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import express, { Request, Response, Router } from "express"
import formidable from 'formidable'
import JSONBig from 'json-bigint'
import multer from 'multer'
import { BizCode, BizContext, BizFail, BizResponse, UserDevice, UserNetwork } from "../../common/base.models"

const BIZ_HEADER_TOKEN = 'x-token'
Expand Down Expand Up @@ -30,6 +32,17 @@ export interface ApiInfo {
params?: Array<ParamInfo>
}

const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '/tmp/my-uploads')
},
filename: function (req, file, cb) {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
cb(null, file.fieldname + '-' + uniqueSuffix)
}
})
const upload = multer({ storage: storage })

export abstract class BaseRouter {

private _router: Router
Expand Down Expand Up @@ -122,13 +135,7 @@ export abstract class BaseRouter {
scheme = regArr[0].trim() // Mozilla/5.0
const os = regArr[1].trim().substring(1, regArr[1].length - 1).split(';')[0] // (Windows NT 10.0; Win64; x64)
const [brand, _] = regArr[4].trim().split(' ') // Chrome/131.0.0.0 Safari/537.36
console.log(scheme, os, platform)
deviceInfo = {
os,
version: '',
brand,
model: ''
}
deviceInfo = { os, version: '', brand, model: '' }
} else {
let regArr = ua.match(/[0-9A-Za-z\/\.\s:-]+/g)
scheme = regArr[0]
Expand Down Expand Up @@ -175,15 +182,30 @@ export abstract class BaseRouter {
}

protected parseBody(req: Request, name: string) {
let contentType = req.headers['content-type']
let [contentType, charset, _] = req.headers['content-type'].match(/[\da-zA-Z\:\/\-\=]+/g)
let body: any
if (contentType.indexOf('multipart/form-data') !== -1) {
console.log(contentType, charset, req.path)
if (contentType == 'multipart/form-data') {

const form = formidable({ multiples: true })
try {

form.parse(req, (err, fields, files) => {

if (err) {
console.error(err)
return
}
console.log(fields, files)
})
console.log(name, req.files)
body = JSONBig.parse(req.body[name]) // try parse as JSON object
console.log('parseBody', body)
} catch (err) {
console.log(err)
body = req.body[name] // just as plain text
}
} else if (contentType.indexOf('application/json') !== -1) {
} else if (contentType == 'application/json') {
body = JSONBig.parse(req.body)
} else {
body = null
Expand All @@ -192,8 +214,4 @@ export abstract class BaseRouter {
return body
}

}




}
Loading

0 comments on commit bbc5faa

Please sign in to comment.