Skip to content

Instantly share code, notes, and snippets.

@liuchong
Last active June 21, 2020 19:56
Show Gist options
  • Select an option

  • Save liuchong/54189161ccbc630ffc09f033fabad0a4 to your computer and use it in GitHub Desktop.

Select an option

Save liuchong/54189161ccbc630ffc09f033fabad0a4 to your computer and use it in GitHub Desktop.
const fs = require('fs')
const { spawn } = require('child_process')
const uuid = require('uuid/v1')
const proxy = require('http-proxy-middleware')
class Faker {
constructor ({ schemaStr, schemaPath, port }) {
this.schemaStr = schemaStr
this.schemaPath = schemaPath
this.port = port
this.server = undefined
}
syncSchema () {
if (!this.schemaStr) {
return
}
if (!this.schemaPath) {
this.schemaPath = `/tmp/schema.${uuid()}.graphql`
}
fs.writeFileSync(this.schemaPath, this.schemaStr)
}
startFaker () {
if (!this.schemaPath) {
throw new Error('Schema path not provided')
}
spawn(`graphql-faker`, ['-p', this.port, this.schemaPath], {
detached: false,
stdio: ['ignore', process.stdout, process.stderr]
})
}
runDefault () {
if (this.server) {
return
}
this.server = `http://127.0.0.1:${this.port}`
if (!this.schemaPath) {
this.syncSchema()
}
this.startFaker()
}
applyFaker (app) {
if (!this.server) {
this.runDefault()
}
app.use('/graphql', proxy({ target: this.server, changeOrigin: true }))
app.use('/editor', proxy({ target: this.server, changeOrigin: true }))
app.use('/user-idl', proxy({ target: this.server, changeOrigin: true }))
}
}
module.exports = Faker
module.exports.apply = function apply (
app,
{ schemaStr, schemaPath, port = 9002 }
) {
const faker = new Faker({ schemaStr, schemaPath, port })
faker.applyFaker(app)
}
if (!module.parent) {
new Faker().runDefault()
}
const express = require('express')
const webpack = require('webpack')
const webpackDevMiddleware = require('webpack-dev-middleware')
const webpackHotMiddleware = require('webpack-hot-middleware')
const { schemaPath } = require('schema')
const webpackConfig = require('./webpack.config.js')
const { logger, loggerMiddleware } = require('./scripts/logger')
const Faker = require('./scripts/faker')
const app = express()
const compiler = webpack(webpackConfig)
Faker.apply(app, { schemaPath })
app.use(loggerMiddleware)
app.use(
webpackDevMiddleware(compiler, {
// noInfo: true,
publicPath: webpackConfig.output.publicPath
})
)
app.use(webpackHotMiddleware(compiler))
// Serve the files on port 3000.
app.listen(3000, function () {
logger.info('Example app listening on port 3000!\n')
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment