UNPKG

ae-biu

Version:

Born For AE, Born To Do

81 lines (70 loc) 2.05 kB
#!/usr/bin/env node // @flow import program from 'commander' import fs from 'fs' import path from 'path' import isEqual from 'lodash/isEqual' import enableDestroy from 'server-destroy' import logger from './utils/logger' import { mockDir } from './utils/paths' import clearConsole from './utils/clear-console' /** * Usage */ program .usage('[options]') .option('-p, --port', 'Mock server port, default is 9000') .option('-w, --watch', 'Watch db.json change, default is false') .parse(process.argv) // padding console.log() // options const port = (+program.args[0]) || 9000 const watch = program.watch // must require in here const createServer = require('./config/mock-server.config') const dbPath = path.resolve(mockDir, 'db.json') // start server let app let db const start = () => { db = JSON.parse(fs.readFileSync(dbPath, { encoding: 'utf8' })) app = createServer().listen(port, () => { logger.info(`Mock Server now running at http://0.0.0.0:${port}\n`) }) enableDestroy(app) } start() // from https://github.com/typicode/json-server/blob/master/src/cli/run.js#L199 if (watch) { logger.info('Watching database...\n') let readError = false fs.watch(mockDir, (event, file) => { if (file) { const watchedFile = path.resolve(mockDir, file) if (watchedFile === dbPath) { let obj try { obj = JSON.parse(fs.readFileSync(watchedFile, { encoding: 'utf8' })) if (readError) { logger.info(`Read error has been fixed :)\n`) readError = false } } catch (e) { readError = true logger.error(`Error reading ${watchedFile}\n`) console.error(e.message) return } // Compare .json file content with in memory database const isDatabaseDifferent = !isEqual(obj, db) if (isDatabaseDifferent) { clearConsole() logger.info(`database has changed, reloading...\n`) app && app.destroy() start() } } } }) }