Last active
November 16, 2019 04:25
-
-
Save syuji-higa/1e324ee5f5576effe93d4a5c1f1869c9 to your computer and use it in GitHub Desktop.
Node.js - API mock server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
const Koa = require('koa') | |
const cors = require('@koa/cors') | |
const Router = require('koa-router') | |
const bodyparser = require('koa-bodyparser') | |
require('colors') | |
const app = new Koa() | |
const router = new Router() | |
const wait = (time) => { | |
return new Promise((resolve) => { | |
setTimeout(() => resolve(), time) | |
}) | |
} | |
const error = (status, ctx) => { | |
switch (status) { | |
case 400: { | |
ctx.status = 400 | |
ctx.body = { | |
errors: [ | |
{ | |
code: '400', | |
message: 'Faild Error' | |
} | |
], | |
message: '400 Faild Error' | |
} | |
break | |
} | |
case 404: { | |
ctx.status = 404 | |
ctx.body = { | |
errors: [ | |
{ | |
code: '404', | |
message: 'Not Found Error' | |
} | |
], | |
message: '404 Not Found Error' | |
} | |
break | |
} | |
case 500: { | |
ctx.status = 500 | |
ctx.body = { | |
errors: [ | |
{ | |
code: '500', | |
message: 'Server Error' | |
} | |
], | |
message: '500 Server Error' | |
} | |
break | |
} | |
} | |
} | |
router.get('/sample', async (ctx, next) => { | |
const { method, url, body } = ctx.request | |
console.log(`[${method}: ${url}]`.yellow) | |
const _options = { method, url } | |
if (body) { | |
console.log('[REQ]'.yellow) | |
console.log(body) | |
_options.data = body | |
} | |
await wait(500) | |
ctx.set('Content-Type', 'application/json') | |
// 200 | |
ctx.status = 200 | |
ctx.body = { | |
id: 0, | |
value: 'sample' | |
} | |
// error(400, ctx) | |
if(ctx.status === 200) { | |
console.log('[RES]'.yellow) | |
} else { | |
console.log('[ERR]'.yellow) | |
} | |
console.log(ctx.body) | |
await next() | |
}) | |
app | |
.use(cors()) | |
.use(bodyparser()) | |
.use(router.routes()) | |
.use(router.allowedMethods()) | |
const server = app.listen('8080', '127.0.0.1', () => { | |
const host = server.address().address | |
const port = server.address().port | |
console.log('listening at http://%s:%s', host, port) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment