Skip to content

Instantly share code, notes, and snippets.

@TracyNgot
Last active November 22, 2018 14:09
Show Gist options
  • Save TracyNgot/176c0bc950a09e95da13cbd703318fc8 to your computer and use it in GitHub Desktop.
Save TracyNgot/176c0bc950a09e95da13cbd703318fc8 to your computer and use it in GitHub Desktop.
Mock Server With ExpressJS, TypeScript for your API
import * as express from 'express';
import mockRoutes from './MockRoutes';
import config from '../config/Config';
import proxy = require('http-proxy-middleware');
class Routes {
public router: express.Router = express.Router();
constructor() {
this.config();
}
private config(): void {
this.router.get('/', (req: express.Request, res: express.Response) =>
res.status(200).json({message: 'Welcome to the CLO Mock Server API'})
);
this.router.use('/v1d', proxy(this.filterProxy, {
changeOrigin: true,
target: config.API_URL,
onProxyReq: (proxyReq: any, req: any, res: any) => {
if (req.body) {
let bodyData = JSON.stringify(req.body);
proxyReq.setHeader('Content-Type','application/json');
proxyReq.write(bodyData);
}
}
}));
mockRoutes.forEach(route => {
switch (route.method) {
case 'GET':
this.router.get(route.pathname + '*', (req: express.Request, res: express.Response) =>
res.status(route.status).json(route.responseBody)
);
break;
case 'PUT':
this.router.put(route.pathname + '*', (req: express.Request, res: express.Response) =>
res.status(route.status).json(route.responseBody)
);
break;
case 'POST':
this.router.post(route.pathname + '*', (req: express.Request, res: express.Response) =>
res.status(route.status).json(route.responseBody)
);
break;
case 'DELETE':
this.router.delete(route.pathname + '*', (req: express.Request, res: express.Response) =>
res.status(route.status).json(route.responseBody)
);
break;
default:
break;
}
});
}
private filterProxy(pathname: string, req: express.Request) {
return !mockRoutes.find(route =>
pathname.indexOf(route.pathname) !== -1 && req.method.toUpperCase() === route.method.toUpperCase()
);
}
}
export const routes = new Routes().router;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment