mock平台

app.js 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. process.env.NODE_PATH = __dirname;
  2. require('module').Module._initPaths();
  3. const yapi = require('./yapi.js');
  4. const commons = require('./utils/commons');
  5. yapi.commons = commons;
  6. const dbModule = require('./utils/db.js');
  7. yapi.connect = dbModule.connect();
  8. const mockServer = require('./middleware/mockServer.js');
  9. require('./plugin.js');
  10. const websockify = require('koa-websocket');
  11. const websocket = require('./websocket.js');
  12. const storageCreator = require('./utils/storage')
  13. require('./utils/notice')
  14. const Koa = require('koa');
  15. const koaStatic = require('koa-static');
  16. // const bodyParser = require('koa-bodyparser');
  17. const koaBody = require('koa-body');
  18. const router = require('./router.js');
  19. global.storageCreator = storageCreator;
  20. let indexFile = process.argv[2] === 'dev' ? 'dev.html' : 'index.html';
  21. const app = websockify(new Koa());
  22. app.proxy = true;
  23. yapi.app = app;
  24. // app.use(bodyParser({multipart: true}));
  25. app.use(koaBody({ multipart: true, jsonLimit: '2mb', formLimit: '1mb', textLimit: '1mb' }));
  26. app.use(mockServer);
  27. app.use(router.routes());
  28. app.use(router.allowedMethods());
  29. websocket(app);
  30. app.use(async (ctx, next) => {
  31. if (/^\/(?!api)[a-zA-Z0-9\/\-_]*$/.test(ctx.path)) {
  32. ctx.path = '/';
  33. await next();
  34. } else {
  35. await next();
  36. }
  37. });
  38. app.use(async (ctx, next) => {
  39. if (ctx.path.indexOf('/prd') === 0) {
  40. ctx.set('Cache-Control', 'max-age=8640000000');
  41. if (yapi.commons.fileExist(yapi.path.join(yapi.WEBROOT, 'static', ctx.path + '.gz'))) {
  42. ctx.set('Content-Encoding', 'gzip');
  43. ctx.path = ctx.path + '.gz';
  44. }
  45. }
  46. await next();
  47. });
  48. app.use(koaStatic(yapi.path.join(yapi.WEBROOT, 'static'), { index: indexFile, gzip: true }));
  49. app.listen(yapi.WEBCONFIG.port);
  50. commons.log(
  51. `服务已启动,请打开下面链接访问: \nhttp://127.0.0.1${
  52. yapi.WEBCONFIG.port == '80' ? '' : ':' + yapi.WEBCONFIG.port
  53. }/`
  54. );