ソースを参照

chore: mock and eslint

daigang 3 年 前
コミット
f58d6a7d75
8 ファイル変更60 行追加155 行削除
  1. 1 1
      .eslintrc.js
  2. 0 56
      mock/index.js
  3. 37 30
      mock/mock-server.js
  4. 4 3
      mock/proxy.js
  5. 0 0
      mock/routes/program/index.js
  6. 0 0
      mock/routes/schedule/index.js
  7. 18 0
      mock/routes/utils.js
  8. 0 65
      mock/utils.js

+ 1 - 1
.eslintrc.js

@@ -7,7 +7,7 @@ module.exports = {
   env: {
     browser: true,
     node: true,
-    es6: true,
+    es6: true
   },
   extends: ['plugin:vue/recommended', 'eslint:recommended'],
 

+ 0 - 56
mock/index.js

@@ -1,56 +0,0 @@
-const Mock = require('mockjs')
-const { param2Obj } = require('./utils')
-
-const program = require('./program')
-const schedule = require('./schedule')
-
-const mocks = [
-  ...program,
-  ...schedule
-]
-
-// for front mock
-// please use it cautiously, it will redefine XMLHttpRequest,
-// which will cause many of your third-party libraries to be invalidated(like progress event).
-function mockXHR () {
-  // mock patch
-  // https://github.com/nuysoft/Mock/issues/300
-  Mock.XHR.prototype.proxy_send = Mock.XHR.prototype.send
-  Mock.XHR.prototype.send = function () {
-    if (this.custom.xhr) {
-      this.custom.xhr.withCredentials = this.withCredentials || false
-
-      if (this.responseType) {
-        this.custom.xhr.responseType = this.responseType
-      }
-    }
-    this.proxy_send(...arguments)
-  }
-
-  function XHR2ExpressReqWrap (respond) {
-    return function (options) {
-      let result = null
-      if (respond instanceof Function) {
-        const { body, type, url } = options
-        // https://expressjs.com/en/4x/api.html#req
-        result = respond({
-          method: type,
-          body: JSON.parse(body),
-          query: param2Obj(url)
-        })
-      } else {
-        result = respond
-      }
-      return Mock.mock(result)
-    }
-  }
-
-  for (const i of mocks) {
-    Mock.mock(new RegExp(i.url), i.type || 'get', XHR2ExpressReqWrap(i.response))
-  }
-}
-
-module.exports = {
-  mocks,
-  mockXHR
-}

+ 37 - 30
mock/mock-server.js

@@ -1,21 +1,13 @@
-const chokidar = require('chokidar')
-const bodyParser = require('body-parser')
-const chalk = require('chalk')
+const fs = require('fs')
 const path = require('path')
+const chalk = require('chalk')
+const chokidar = require('chokidar')
+const express = require('express')
 const Mock = require('mockjs')
-const router = require('express').Router()
+const router = express.Router()
 
 const mockDir = path.join(process.cwd(), 'mock')
 
-function unregisterRoutes () {
-  Object.keys(require.cache).forEach(i => {
-    if (i.includes(mockDir)) {
-      delete require.cache[require.resolve(i)]
-    }
-  })
-}
-
-// for mock server
 function responseFake(url, type, respond) {
   return {
     url: new RegExp(`${url}`),
@@ -28,23 +20,43 @@ function responseFake(url, type, respond) {
 }
 
 function register (router) {
-  const proxyCount = require('./proxy').register(router)
+  require('./proxy').register(router)
 
-  const { mocks } = require('./index.js')
-  const mocksForServer = mocks.map(route => {
-    return responseFake(route.url, route.type, route.response)
-  })
-  for (const mock of mocksForServer) {
-    router[mock.type](mock.url, mock.response)
+  router.use(express.json())
+  router.use(express.urlencoded({
+    extended: true
+  }))
+
+  const routes = []
+  try {
+    fs.readdirSync(path.join(__dirname, 'routes')).forEach(file => {
+      const mocks = require(`./routes/${file}`)
+      if (Array.isArray(mocks)) {
+        routes.push(...mocks)
+      }
+    })
+  } catch (e) {
+    console.log('no mock routes', e)
   }
+  routes.forEach(route => {
+    const { type, url, response } = responseFake(route.url, route.type, route.response)
+    router[type](url, response)
+  })
+}
+
+function unregister () {
+  router.stack = []
+
+  // clear routes cache
+  Object.keys(require.cache).forEach(i => {
+    if (i.includes(mockDir)) {
+      delete require.cache[require.resolve(i)]
+    }
+  })
 }
 
 module.exports = app => {
   app.use(process.env.VUE_APP_BASE_API, router)
-  app.use(bodyParser.json())
-  app.use(bodyParser.urlencoded({
-    extended: true
-  }))
   register(router)
 
   // watch files, hot reload mock server
@@ -54,13 +66,8 @@ module.exports = app => {
   }).on('all', (event, path) => {
     if (event === 'change' || event === 'add') {
       try {
-        router.stack = []
-
-        // clear routes cache
-        unregisterRoutes()
-
+        unregister()
         register(router)
-
         console.log(chalk.magentaBright(`\n > Mock Server hot reload success! changed ${path}`))
       } catch (error) {
         console.log(chalk.redBright(error))

+ 4 - 3
mock/proxy.js

@@ -1,6 +1,6 @@
 const proxy = require('express-http-proxy')
 
-const use = true
+const use = false
 
 const base_url = process.env.VUE_APP_BASE_API
 const minioKey = process.env.VUE_APP_MINIO.replace(base_url, '')
@@ -23,11 +23,12 @@ module.exports = {
       // router.use('/scheduling-config', createProxy('http://10.180.90.6:18887', true))
       // router.use('/scheduling-plugin-device', createProxy('http://10.180.90.6:18887', true))
       // router.use('/release-history', createProxy('http://10.180.90.6:18887', true))
-      router.use('/apkUpgradeFile', createProxy('http://10.180.90.6:8889', true))
-      router.use('/apkUpgradePolicy', createProxy('http://10.180.90.6:8889', true))
+      // router.use('/apkUpgradeFile', createProxy('http://10.180.90.6:8889', true))
+      // router.use('/apkUpgradePolicy', createProxy('http://10.180.90.6:8889', true))
       // router.use('/device', createProxy('http://10.180.90.27:8891', true))
       // router.use('/sysLog', createProxy('http://10.180.91.61:8890', true))
       // router.use('/minio-data', createProdProxy('http://10.180.88.84:8094'))
+      // router.use('/content', createProdProxy('http://liangke00.home.langchao.com:8081', true))
       router.use('/', createProxy(gate))
     }
   }

+ 0 - 0
mock/program/index.js → mock/routes/program/index.js


+ 0 - 0
mock/schedule/index.js → mock/routes/schedule/index.js


+ 18 - 0
mock/routes/utils.js

@@ -0,0 +1,18 @@
+const fs = require('fs')
+
+function getDB (type) {
+  try {
+    return JSON.parse(fs.readFileSync(`${__dirname}/${type}/db.json`))
+  } catch (e) {
+    return []
+  }
+}
+
+function saveDB (type, db) {
+  fs.writeFileSync(`${__dirname}/${type}/db.json`, JSON.stringify(db))
+}
+
+module.exports = {
+  getDB,
+  saveDB
+}

+ 0 - 65
mock/utils.js

@@ -1,65 +0,0 @@
-const fs = require('fs')
-const path = require('path')
-
-/**
- * @param {string} url
- * @returns {Object}
- */
-function param2Obj(url) {
-  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
-  if (!search) {
-    return {}
-  }
-  const obj = {}
-  const searchArr = search.split('&')
-  searchArr.forEach(v => {
-    const index = v.indexOf('=')
-    if (index !== -1) {
-      const name = v.substring(0, index)
-      const val = v.substring(index + 1, v.length)
-      obj[name] = val
-    }
-  })
-  return obj
-}
-
-/**
- * This is just a simple version of deep copy
- * Has a lot of edge cases bug
- * If you want to use a perfect deep copy, use lodash's _.cloneDeep
- * @param {Object} source
- * @returns {Object}
- */
-function deepClone(source) {
-  if (!source && typeof source !== 'object') {
-    throw new Error('error arguments', 'deepClone')
-  }
-  const targetObj = source.constructor === Array ? [] : {}
-  Object.keys(source).forEach(keys => {
-    if (source[keys] && typeof source[keys] === 'object') {
-      targetObj[keys] = deepClone(source[keys])
-    } else {
-      targetObj[keys] = source[keys]
-    }
-  })
-  return targetObj
-}
-
-function getDB (type) {
-  try {
-    return JSON.parse(fs.readFileSync(`./mock/${type}/db.json`))
-  } catch (e) {
-    return []
-  }
-}
-
-function saveDB (type, db) {
-  fs.writeFileSync(`./mock/${type}/db.json`, JSON.stringify(db))
-}
-
-module.exports = {
-  param2Obj,
-  deepClone,
-  getDB,
-  saveDB
-}