import Router, { RouterContext } from 'koa-router' import {LegoNamespaceContainer} from '../core/namespace' const namespaceRouter = new Router() let spaceContainer: LegoNamespaceContainer function throwErrorWhenNamespaceNotFound(spacename: string): void { if (!spaceContainer.has(spacename)) { throw new Error(`命名空间${spacename}不存在`) } } function throwErrorWhenNamespaceFound(spacename: string): void { if (spaceContainer.has(spacename)) { throw new Error(`命名空间${spacename}已存在`) } } async function getNamespaceContentHandler(ctx: RouterContext) { let spacenameList: string[] | undefined = ctx.request.body.spacenameList let namespaceContent: any[] = [] spacenameList = spacenameList || spaceContainer.namespaceList spacenameList.forEach((spacename: string) => { namespaceContent.push( { spacename: spacename, fields: (spaceContainer.get(spacename)).listValue } ) }) ctx.body = ctx.ok(namespaceContent) } /** * body {} * spacename: string */ async function createNamespaceHandler(ctx: RouterContext) { const spacename = ctx.request.body.spacename throwErrorWhenNamespaceFound(spacename) spaceContainer.create(spacename) ctx.body = ctx.ok() } /** * body {} * spacename: string */ async function deleteNamespaceHandler(ctx: RouterContext) { const spaceId = ctx.request.body.spacename throwErrorWhenNamespaceNotFound(spaceId) spaceContainer.delete(spaceId) ctx.body = ctx.ok() } /** * body {} * spacename: string * field: {} * label: string * type: string * key: string */ async function addFieldHandler(ctx: RouterContext) { const {spaceId, field} = ctx.request.body throwErrorWhenNamespaceNotFound(spaceId) const id = spaceContainer.addField(spaceId, field) ctx.body = ctx.ok(id) } /** * body {} * spacename: string * field: {} * label: string * type: string * key: string */ async function modifyFieldHandler(ctx: RouterContext) { const {spacename, id, field} = ctx.request.body throwErrorWhenNamespaceNotFound(spacename) spaceContainer.setField(spacename, id, field) ctx.body = ctx.ok() } async function deleteFieldHandler(ctx: RouterContext) { const {spacename, id} = ctx.request.body throwErrorWhenNamespaceNotFound(spacename) spaceContainer.deleteField(spacename, id) ctx.body = ctx.ok() } namespaceRouter .all('*', async (ctx: RouterContext, next: any) => { if (!spaceContainer) { spaceContainer = new LegoNamespaceContainer(ctx.legoOption.namespaceRoot) } next() }) .get('/getNamespaceContent', getNamespaceContentHandler) .post('/create', createNamespaceHandler) .post('/delete', deleteNamespaceHandler) .post('/addField', addFieldHandler) .post('/modifyField', modifyFieldHandler) .post('/deleteField', deleteFieldHandler) export default namespaceRouter