ionian/src/diff/router.ts

83 lines
No EOL
2.4 KiB
TypeScript

import Koa from 'koa';
import Router from 'koa-router';
import { ContentFile } from '../content/mod';
import { sendError } from '../route/error_handler';
import {DiffManager} from './diff';
import {AdminOnlyMiddleware} from '../permission/permission';
function content_file_to_return(x:ContentFile){
return {path:x.path,type:x.type};
}
export const getAdded = (diffmgr:DiffManager)=> (ctx:Koa.Context,next:Koa.Next)=>{
const ret = diffmgr.getAdded();
ctx.body = ret.map(x=>({
type:x.type,
value:x.value.map(x=>({path:x.path,type:x.type})),
}));
ctx.type = 'json';
}
type PostAddedBody = {
type:string,
path:string,
}[];
function checkPostAddedBody(body: any): body is PostAddedBody{
if(body instanceof Array){
return body.map(x=> 'type' in x && 'path' in x).every(x=>x);
}
return false;
}
export const postAdded = (diffmgr:DiffManager) => async (ctx:Router.IRouterContext,next:Koa.Next)=>{
const reqbody = ctx.request.body;
if(!checkPostAddedBody(reqbody)){
sendError(400,"format exception");
return;
}
const allWork = reqbody.map(op=>diffmgr.commit(op.type,op.path));
const results = await Promise.all(allWork);
ctx.body = {
ok:true,
docs:results,
}
ctx.type = 'json';
}
export const postAddedAll = (diffmgr: DiffManager) => async (ctx:Router.IRouterContext,next:Koa.Next) => {
if (!ctx.is('json')){
sendError(400,"format exception");
return;
}
const reqbody = ctx.request.body as Record<string,unknown>;
if(!("type" in reqbody)){
sendError(400,"format exception: there is no \"type\"");
return;
}
const t = reqbody["type"];
if(typeof t !== "string"){
sendError(400,"format exception: invalid type of \"type\"");
return;
}
await diffmgr.commitAll(t);
ctx.body = {
ok:true
};
ctx.type = 'json';
}
/*
export const getNotWatched = (diffmgr : DiffManager)=> (ctx:Router.IRouterContext,next:Koa.Next)=>{
ctx.body = {
added: diffmgr.added.map(content_file_to_return),
deleted: diffmgr.deleted.map(content_file_to_return),
};
ctx.type = 'json';
}*/
export function createDiffRouter(diffmgr: DiffManager){
const ret = new Router();
ret.get("/list",AdminOnlyMiddleware,getAdded(diffmgr));
ret.post("/commit",AdminOnlyMiddleware,postAdded(diffmgr));
ret.post("/commitall",AdminOnlyMiddleware,postAddedAll(diffmgr));
return ret;
}