Skip to content

Commit

Permalink
feat: route rewrite
Browse files Browse the repository at this point in the history
  • Loading branch information
couriourc committed Sep 9, 2024
1 parent 49e98a5 commit e928959
Show file tree
Hide file tree
Showing 7 changed files with 40 additions and 24 deletions.
8 changes: 7 additions & 1 deletion example/.simple-mock.yaml
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

root_dir: .
api_dir: apis
static_dir: static
Expand All @@ -11,3 +10,10 @@ debug_log_file_path: ./debug.log
watch:
plugins:
swagger:
path: /swagger
documentation:
title: "Test"

rewrites:
- path: ''
test: ^(index)$ # rewrite index for ''
3 changes: 3 additions & 0 deletions example/apis/api/index.[id].json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"asd": "{{params.id}}"
}
7 changes: 0 additions & 7 deletions example/plugins/peer-stream/index.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,3 @@
const config = require('./signal.json');
const fs = require('fs');
const child_process = require('child_process');
const G_StartUe5Pool = [];
function initUEe5Pool() {

}
export default function({app, logger, option}) {
app.ws('/ws', {
message(ws, message) {
Expand Down
4 changes: 4 additions & 0 deletions src/constants/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,8 @@ debug_log_file_path: ./debug.log
watch:
plugins:
swagger:
rewrites:
- path: ''
test: ^(index)$
`

2 changes: 1 addition & 1 deletion src/core/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ export const cwd = (...p: string[]) => path.resolve(command.getOptionValue('cwd'
// E 配置启动命令信息
const parsedConfig = yaml.parse<IConfigParameter>(await safeRun(() => {
const configFilePath = cwd(DEFAULT_CONFIG.root_dir, configFile);

if (!fs.existsSync(configFilePath)) {
fs.writeFileSync(configFilePath, DEFAULT_MOCK_YAML_CONFIG);
return '';
Expand All @@ -65,4 +64,5 @@ export const config = mergeDeep(DEFAULT_CONFIG, {
static_dir: choice(command.getOptionValue("static-dir"), parsedConfig?.static_dir, DEFAULT_CONFIG.static_dir),
static_route_prefix: choice(command.getOptionValue("static-route-prefix"), parsedConfig?.static_route_prefix, DEFAULT_CONFIG.static_route_prefix),
plugins: parsedConfig?.plugins ?? {},
rewrites: parsedConfig?.rewrites ?? {}
} as Partial<IConfigParameter>);
33 changes: 20 additions & 13 deletions src/core/startup.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import path from "path";
import fs from "fs";
import Logger from "@ptkdev/logger";
import {Glob} from "bun";
import Elysia from "elysia";
import {Table} from "console-table-printer";
Expand All @@ -16,7 +15,7 @@ import process from "process";
import readline from "readline";
//@ts-ignore
import {logger as midLogger} from '@grotto/logysia';
import {getPlugins, initPlugins} from "./plugin-handler.ts";
import {initPlugins} from "./plugin-handler.ts";
import {checkAndInit} from "./config.ts";
import {getLogger} from "../utils/logger.ts";

Expand All @@ -27,15 +26,15 @@ export async function startup(config, cwd) {

// E 相关配置
checkAndInit({resolve, config});
const plugins = await initPlugins({cwd, config, resolve, logger});
const plugins = await initPlugins({config, resolve, logger});
// S 打印日志配置
// 遍历路径信息
const glob = new Glob("./**/*.*");
// 启动服务
const app = new Elysia();
const rewrites = [
[/^index$/, ''],
] as [[RegExp, string]];
const rewrites = config.rewrites.map(({path, test}) => {
return [new RegExp(test), path];
}) as [[RegExp, string]];

const urlRewrite = (url: string, method: string) => {
for (let [reg, final] of rewrites) {
Expand Down Expand Up @@ -65,17 +64,25 @@ export async function startup(config, cwd) {
for await (const file of glob.scan(resolve(config.api_dir))) {
let [_, url, method] = [undefined, '', 'get'];
const group = path.normalize(path.parse(path.normalize(file)).dir).replaceAll(path.sep, '/');
const regBackets = /\[([^}]*)\]/g;

const transformFile = (value: string) =>
regBackets.test(value) ? value.replace(regBackets, (_, s) => `:${s}`) : value;
const transformedFile = transformFile(path.basename(file));
const withMethodParams = /(.*)\.(get|post|patch|head|delete|option|put)\.(.*)$/.exec(transformedFile);

if (withMethodParams) {
[_, url, method] = withMethodParams;
} else {
const route = transformedFile.split('.');
url = route.slice(0, route.length - 1).join('/');
}

app.group(group.replaceAll(".", ""), (app) => {
const withMethodParams = /(.*)\.(get|post|patch|head|delete|option|put)\.(.*)$/.exec(path.basename(file));
if (withMethodParams) {
[_, url, method] = withMethodParams;
} else {
url = path.basename(file).split('.')[0];
}
const finalUrl = urlRewrite(url, method,);
app[method]?.(finalUrl, async (req) => {
let res = Bun.file(resolve(path.join(config.api_dir, file)));
logger.debug(JSON.stringify(pick(req, ['cookie', 'user-agent', 'headers', 'body', 'route', 'query', 'content-type'])));
logger.debug(JSON.stringify(pick(req, ['cookie', 'user-agent', 'headers', "params", 'body', 'route', 'query', 'content-type'])));
switch (path.extname(file)) {
case ".json":
return safeRun(async () => Mock.mock(JSON.parse(Mustache.render(JSON.stringify(await res.json()) as string, req))), Promise.resolve(res));
Expand Down
7 changes: 5 additions & 2 deletions src/presets/plugins/swagger/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import {swagger} from '@elysiajs/swagger';

export default function ({app}) {
app.use(swagger);
export default function ({app, option}) {
console.log(option);
app.use(swagger({
...(option ?? {}),
}));
}

0 comments on commit e928959

Please sign in to comment.