ionian/src/server.ts
2021-02-22 23:08:44 +09:00

82 lines
No EOL
2.8 KiB
TypeScript

import Koa from 'koa';
import Router from 'koa-router';
import {get_setting} from './setting';
import {connectDB} from './database';
import {Watcher} from './diff'
import { createReadStream, readFileSync } from 'fs';
import getContentRouter from './route/contents';
import { createKnexContentsAccessor } from './db/contents';
import bodyparser from 'koa-bodyparser';
import {error_handler} from './route/error_handler';
import {UserMiddleWare,createLoginMiddleware, isAdminFirst, getAdmin, LogoutMiddleware} from './login';
import {createInterface as createReadlineInterface} from 'readline';
//let Koa = require("koa");
async function main(){
let settings = get_setting();
let db = await connectDB();
const userAdmin = await getAdmin(db);
if(await isAdminFirst(userAdmin)){
const rl = createReadlineInterface({input:process.stdin,output:process.stdout});
rl.setPrompt("put admin password : ");
rl.prompt();
const pw = await new Promise((res:(data:string)=>void,err)=>{
rl.on('line',(data)=>res(data));
});
userAdmin.reset_password(pw);
}
let app = new Koa();
app.use(bodyparser());
app.use(error_handler);
app.use(UserMiddleWare);
//app.use(ctx=>{ctx.state['setting'] = settings});
const index_html = readFileSync("index.html");
let router = new Router();
let watcher = new Watcher(settings.path[0]);
await watcher.setup([]);
const serveindex = (url:string)=>{
router.get(url, (ctx)=>{ctx.type = 'html'; ctx.body = index_html;})
}
serveindex('/');
serveindex('/doc/:rest(.*)');
serveindex('/search');
serveindex('/login');
const static_file_server = (path:string,type:string) => {
router.get('/'+path,async (ctx,next)=>{
ctx.type = type; ctx.body = createReadStream(path);
})}
static_file_server('dist/css/style.css','css');
static_file_server('dist/js/bundle.js','js');
static_file_server('dist/js/bundle.js.map','text');
const content_router = getContentRouter(createKnexContentsAccessor(db));
router.use('/content',content_router.routes());
router.use('/content',content_router.allowedMethods());
router.post('/user/login',createLoginMiddleware(db));
router.post('/user/logout',LogoutMiddleware);
let mm_count = 0;
app.use(async (ctx,next)=>{
console.log(`==========================${mm_count++}`);
const fromClient = ctx.state['user'] === undefined ? ctx.ip : ctx.state['user'].username;
console.log(`${fromClient} : ${ctx.method} ${ctx.url}`);
await next();
//console.log(`404`);
});
app.use(router.routes());
app.use(router.allowedMethods());
console.log("start server");
app.listen(settings.port,settings.localmode ? "127.0.0.1" : "0.0.0.0");
return app;
}
main();