start
This commit is contained in:
75
app.js
Normal file
75
app.js
Normal file
@@ -0,0 +1,75 @@
|
||||
import Koa from 'koa';
|
||||
import bodyParser from 'koa-bodyparser';
|
||||
import cors from 'koa-cors';
|
||||
import http from 'http';
|
||||
import { DBModel } from './models/index.js';
|
||||
import registerRoutes from './routes/index.js';
|
||||
import ResponseUtil from './utils/api_response.js';
|
||||
|
||||
class APP {
|
||||
constructor() {
|
||||
this.app = new Koa();
|
||||
this.setupDB();
|
||||
this.setupMiddleware();
|
||||
this.setupRoutes();
|
||||
this.setupFallback();
|
||||
}
|
||||
|
||||
setupDB() {
|
||||
DBModel.init();
|
||||
}
|
||||
|
||||
setupMiddleware() {
|
||||
this.app.use(cors());
|
||||
this.app.use(bodyParser());
|
||||
|
||||
this.app.use(async (ctx, next) => {
|
||||
const start = Date.now();
|
||||
await next();
|
||||
const ms = Date.now() - start;
|
||||
console.log(`${ctx.method} ${ctx.url} - ${ctx.status} - ${ms}ms`);
|
||||
});
|
||||
}
|
||||
|
||||
setupRoutes() {
|
||||
this.app.use(async (ctx, next) => {
|
||||
if (ctx.path === '/') {
|
||||
ResponseUtil.success(ctx, { name: 'attendant-api', version: '1.0.0' });
|
||||
return;
|
||||
}
|
||||
await next();
|
||||
});
|
||||
|
||||
this.app.use(registerRoutes.getRoutes());
|
||||
this.app._router = registerRoutes.router;
|
||||
}
|
||||
|
||||
setupFallback() {
|
||||
this.app.use(async (ctx) => {
|
||||
ctx.status = 404;
|
||||
ctx.body = { code: 404, msg: 'Not Found' };
|
||||
});
|
||||
}
|
||||
|
||||
start(port) {
|
||||
this.server = http.createServer(this.app.callback());
|
||||
this.server.listen(port, () => {
|
||||
console.log(`Server: running on http://localhost:${port}`);
|
||||
});
|
||||
}
|
||||
|
||||
stop() {
|
||||
if (this.server) {
|
||||
this.server.close();
|
||||
this.server = null;
|
||||
console.log('Server stopped');
|
||||
}
|
||||
}
|
||||
|
||||
static createKoaApp() {
|
||||
const instance = new APP();
|
||||
return instance.app;
|
||||
}
|
||||
}
|
||||
|
||||
export { APP };
|
||||
Reference in New Issue
Block a user