fix(striker-ui-api): organize routes into map

main
Tsu-ba-me 2 years ago
parent aadc84ea70
commit f15391010c
  1. 9
      striker-ui-api/src/app.ts
  2. 3
      striker-ui-api/src/lib/consts/API_ROOT_PATH.ts
  3. 25
      striker-ui-api/src/lib/rrouters.ts
  4. 8
      striker-ui-api/src/routes/index.ts
  5. 3
      striker-ui-api/src/types/MapToRouter.d.ts

@ -1,18 +1,15 @@
import cors from 'cors';
import express from 'express';
import path from 'path';
import API_ROOT_PATH from './lib/consts/API_ROOT_PATH';
import routes from './routes';
import { rrouters } from './lib/rrouters';
const app = express();
app.use(express.json());
app.use(cors());
Object.entries(routes).forEach(([route, router]) => {
app.use(path.join(API_ROOT_PATH, route), router);
});
rrouters(app, routes, { key: 'api' });
rrouters(app, routes, { key: 'echo' });
export default app;

@ -1,3 +0,0 @@
const API_ROOT_PATH = '/api';
export default API_ROOT_PATH;

@ -0,0 +1,25 @@
import { Application, Router } from 'express';
import path from 'path';
import { stdout } from './shell';
export const rrouters = <
A extends Application,
M extends MapToRouter,
R extends Router,
>(
app: A,
union: Readonly<M> | R,
{ key, route = '/' }: { key?: string; route?: string } = {},
) => {
if ('route' in union) {
stdout(`Setting up route ${route}`);
app.use(route, union as R);
} else if (key) {
rrouters(app, union[key], { route: path.posix.join(route, key) });
} else {
Object.entries(union).forEach(([extend, subunion]) => {
rrouters(app, subunion, { route: path.posix.join(route, extend) });
});
}
};

@ -1,5 +1,3 @@
import { Router } from 'express';
import anvilRouter from './anvil';
import commandRouter from './command';
import echoRouter from './echo';
@ -14,10 +12,10 @@ import sshKeyRouter from './ssh-key';
import upsRouter from './ups';
import userRouter from './user';
const routes: Readonly<Record<string, Router>> = {
const routes = {
api: {
anvil: anvilRouter,
command: commandRouter,
echo: echoRouter,
fence: fenceRouter,
file: fileRouter,
host: hostRouter,
@ -28,6 +26,8 @@ const routes: Readonly<Record<string, Router>> = {
'ssh-key': sshKeyRouter,
ups: upsRouter,
user: userRouter,
},
echo: echoRouter,
};
export default routes;

@ -0,0 +1,3 @@
type MapToRouter = {
[uri: string]: MapToRouter | import('express').Router;
};
Loading…
Cancel
Save