| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- const fs = require('fs').promises
- const path = require('path')
- const Koa = require('koa')
- const { pathToRegexp } = require('path-to-regexp')
- const cors = require('@koa/cors')
- const logger = require('koa-logger')
- const { Random, mock } = require('mockjs')
- const randexp = require('randexp').randexp
- const installSerializers = require('./serializers')
- const PORT = 4000
- const DATA_ROOT = 'api'
- const app = new Koa()
- Random.extend({
- phone: () => randexp(/^1[345798][0-9]{9}$/)
- })
- installSerializers(Random, mock)
- app.use(cors())
- app.use(logger())
- app.use(async (ctx) => {
- const request = ctx.request
- const method = request.method.toLowerCase()
- const pathname = request.path
- const routes = await traverseDir(DATA_ROOT)
- const matchedRoute = routes.find((route) => {
- const regexp = pathToRegexp(`/${route}`.replace(/\/_/g, '/:'))
- return regexp.test(pathname)
- })
- if (matchedRoute) {
- const filePath = path.join(__dirname, matchedRoute, `${method}.json`)
- const rawData = await fs.readFile(filePath)
- // ctx.append('authorization', 'basic test-token')
- ctx.body = mock(JSON.parse(rawData))
- } else {
- ctx.throw(404, `pathname or method not found: ${method} ${pathname}`)
- }
- })
- app.listen(PORT)
- // eslint-disable-next-line no-console
- console.log(`mock start at http://localhost:${PORT} port`)
- /**
- * list all dir path
- * @param {string} dir root path
- */
- async function traverseDir(dir) {
- const basePath = path.join(__dirname, `${dir}`)
- const fileList = await fs.readdir(basePath)
- const allFiles = []
- let hasCurrentDir = false
- for (const filename of fileList) {
- const filepath = path.join(basePath, filename)
- const stat = await fs.lstat(filepath)
- const unixFilePath = `${dir}/${filename}`
- if (stat.isDirectory()) {
- const subFiles = await traverseDir(unixFilePath)
- allFiles.push(...subFiles)
- } else if (!hasCurrentDir) {
- hasCurrentDir = true
- allFiles.push(dir)
- }
- }
- return allFiles
- }
|