UNPKG

pageclip

Version:
109 lines (96 loc) 2.33 kB
'use strict' const http = require('http') module.exports = class MockServer { constructor () { this.port = 18181 this.server = http.createServer(this.handleRequest.bind(this)) } getUrl () { return `http://localhost:${this.port}` } listen () { this.server.listen(this.port) } close (callback) { this.server.close(callback) } handleRequest (req, res) { return Routes[req.method.toLowerCase()][req.url](req, res) } } let Routes = { put: { '/data/default': function (req, res) { putData('default', req, res) }, '/data/abucket': function (req, res) { putData('abucket', req, res) }, '/data/fail': function (req, res) { failData('fail', req, res) } }, get: { '/data/default': function (req, res) { getData('default', req, res) }, '/data/abucket': function (req, res) { getData('abucket', req, res) }, '/data/fail': function (req, res) { failData('fail', req, res) } } } function failData (form, req, res) { getBody(req).then((body) => { let out = {errors: [{message: 'nope'}], req: { body, form, method: req.method, headers: req.headers }} res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' }) res.end(`${JSON.stringify(out)}\n`) }) } function putData (form, req, res) { getBody(req).then((body) => { let out = {data: 'ok', form, req: { body, form, method: req.method, headers: req.headers }} res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' }) res.end(`${JSON.stringify(out)}\n`) }) } function getData (form, req, res) { let items = [ {thing: 1}, {thing: 2} ] getBody(req).then((body) => { let out = {data: items, form, req: { body, form, method: req.method, headers: req.headers }} res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' }) res.end(`${JSON.stringify(out)}\n`) }) } function getBody (req) { return new Promise(function (resolve) { let body = [] req .on('data', (chunk) => body.push(chunk)) .on('end', () => { body = Buffer.concat(body).toString().trim() body = body ? JSON.parse(body) : null resolve(body) }) }) }