Added a preprocessor and transferred demo to it

This commit is contained in:
Kawanaao 2023-12-06 15:38:39 +02:00
parent 280dcf2d2d
commit e96a298d21
No known key found for this signature in database
GPG key ID: 5B7A8DDCE861E7DC
9 changed files with 42 additions and 4395 deletions

View file

@ -1,7 +0,0 @@
{
"POST": {
"constellation/devices": {},
"constellation/connect": {},
"constellation/block": {}
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,128 +0,0 @@
import { Request, Response } from "express"
import { resolve } from "path"
import { readFileSync } from "fs"
import querystring from "querystring"
import jsonServer from "json-server"
import traverse from "traverse"
const PROXY_PORT = process.env.PROXY_PORT || 9000
const definedDB: Record<string, any> = JSON.parse(readFileSync(resolve(__dirname, "db.json"), {
encoding: "utf8"
}))
const autoDB = genDB(definedDB)
const dbPaths = Object.keys(autoDB)
// TODO: Reference types do not work at the ["$return", data] level
// A possible solution is to replace filter with map and custom behavior for get, post and put
// defining them to interact with the parent object
const definedRoutes: Record<string, string> = JSON.parse(readFileSync(resolve(__dirname, "routes.json"), {
encoding: "utf8"
}))
const autoRoutes = dbPaths
.filter(path => path.includes("."))
.map(path => ({
origin: "/" + path.replace(/\./g, "/"),
destination: "/" + path
}))
.reduce((acc, bind) => (acc[bind.origin] = bind.destination, acc), {} as Record<string, string>)
const routes = Object.assign({}, autoRoutes, definedRoutes)
const proxyServer = jsonServer.create()
const middlewares = jsonServer.defaults()
const rewriter = jsonServer.rewriter(routes)
const router = jsonServer.router(autoDB, {
foreignKeySuffix: "Id"
})
// @ts-ignore
router.render = (req: Request, res: Response) => {
if (typeof res.locals.data["_comment"] === "string" && res.locals.data["_comment"].toLowerCase().includes("todo"))
return res.sendStatus(404)
else if ("$return" in res.locals.data)
res.locals.data = res.locals.data["$return"];
else if (res.locals.data[0] === "$return")
res.locals.data = res.locals.data[1]
switch (req.method) {
case "GET":
res.locals.result = res.locals.data
break
case "PUT": case "POST": default:
res.locals.result = req.body
break
}
const query = querystring.parse(req.url)
if (query["_inline"] && Array.isArray(res.locals.result) && res.locals.result.length === 1)
res.locals.result = res.locals.result.at(0)
return res.jsonp({
data: res.locals.result,
status: "ok"
})
}
proxyServer.use(jsonServer.bodyParser)
proxyServer.use(middlewares)
proxyServer.use("/api", rewriter)
proxyServer.use("/api", (req, res, next) => {
const query = querystring.stringify(req.query as Record<string, any>)
const dbKey = req.path
.replace("/", "")
.replace(/\//g, ".")
if (autoDB[dbKey])
req.url = `/${dbKey}${query ? "?" : ""}${query}`
next()
})
proxyServer.use("/api", router)
proxyServer.listen(PROXY_PORT, () => console.info(`JSON proxy is running on ${PROXY_PORT} port`))
type JSONValue = string | number | boolean | JSONObject | JSONArray
interface JSONObject extends Record<string, JSONValue> { }
interface JSONArray extends Array<JSONValue> { }
function genDB(initialDB: JSONObject, skipRoot: boolean = true): Record<string, JSONValue> {
return traverse(initialDB)
.reduce(function (acc: Record<string, any>, node) {
if (skipRoot && this.isRoot)
return acc
const currentPath = this.path.join(".").replace(/\.\$return/g, "")
acc[currentPath] = isObject(node) ? node : {
$return: node
}
if (Array.isArray(node)) {
node
.filter(isObject)
.map(childNode => [
Object.values(childNode),
genDB(childNode, false)
] as const)
.forEach(([values, childNodeDB]) =>
values
.filter(value => !!value && typeof value === "string" && !value.includes("."))
.forEach(value => Object.keys(childNodeDB).forEach(childNodePath =>
acc[`${currentPath}.${value}${childNodePath && "." || ""
}${childNodePath}`.replace(/\//g, ".")] = childNodeDB[childNodePath]
))
)
}
return acc
}, {})
}
function isObject(value: unknown): value is Record<string, any> {
return typeof value === 'object' && value !== null
}
// Проитерировать ключи обьекта
// сделать из них путь к базовому обьекту

View file

@ -1,10 +0,0 @@
{
"/servapps/:container/logs": "/servapps/demo/logs",
"/servapps/:id/secure/:res": "/servapps/demo/secure",
"/servapps/:id/manage/:action": "/servapps/demo/manage",
"/volume/:name": "/volumes/Volumes/:name",
"/network/:name": "/networks/:name",
"/servapps/:id/networks": "/servapps/:id/NetworkSettings",
"/test/:id": "/servapps?Id=:id",
"/servapps/:containerId/network/:networkId": "/servapps/:containerId/networks"
}

View file

@ -208,8 +208,6 @@ let uploadImage = (file, name) => {
}));
};
const isDemo = import.meta.env.MODE === 'demo';
let auth = _auth;
let users = _users;
let config = _config;
@ -218,21 +216,22 @@ let market = _market;
let constellation = _constellation;
let metrics = _metrics;
if(isDemo) {
auth = authDemo;
users = usersDemo;
config = configDemo;
docker = dockerDemo;
market = marketDemo;
getStatus = indexDemo.getStatus;
newInstall = indexDemo.newInstall;
isOnline = indexDemo.isOnline;
checkHost = indexDemo.checkHost;
getDNS = indexDemo.getDNS;
uploadImage = indexDemo.uploadImage;
constellation = constellationDemo;
metrics = metricsDemo;
}
// #!if demo
auth = authDemo;
users = usersDemo;
config = configDemo;
docker = dockerDemo;
market = marketDemo;
getStatus = indexDemo.getStatus;
newInstall = indexDemo.newInstall;
isOnline = indexDemo.isOnline;
checkHost = indexDemo.checkHost;
getDNS = indexDemo.getDNS;
uploadImage = indexDemo.uploadImage;
constellation = constellationDemo;
metrics = metricsDemo;
// #!endif
export {
auth,

12
package-lock.json generated
View file

@ -110,7 +110,8 @@
"webpack-bundle-analyzer": "^4.10.1",
"webpack-cli": "^5.1.4",
"webpack-dev-server": "^4.15.1",
"webpack-merge": "^5.10.0"
"webpack-merge": "^5.10.0",
"webpack-preprocessor-loader": "^1.3.0"
},
"peerDependencies": {
"@mui/base": "^5.0.0-beta.3",
@ -16805,6 +16806,15 @@
"node": ">=10.0.0"
}
},
"node_modules/webpack-preprocessor-loader": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/webpack-preprocessor-loader/-/webpack-preprocessor-loader-1.3.0.tgz",
"integrity": "sha512-wvHkDvgU9lhKQ1OWIJsawPBT/0wr+J7dwC7DHy0KtmXR/thGOAWbKEErGeJ2aXGSpwgqQTolIRoETlwMzocK1g==",
"dev": true,
"engines": {
"node": ">=6.11.5"
}
},
"node_modules/webpack-sources": {
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-3.2.3.tgz",

View file

@ -84,7 +84,7 @@
],
"scripts": {
"client": "vite",
"webpack:setup-env": "cross-env useProduction=$npm_config_use_production withReport=$npm_config_with_report analyzeDeps=$npm_config_analyze_deps",
"webpack:setup-env": "cross-env isDemo=$npm_config_demo useProduction=$npm_config_use_production withReport=$npm_config_with_report analyzeDeps=$npm_config_analyze_deps",
"webpack:build": "npm run webpack:setup-env -- webpack --config webpack.prod.js --progress",
"webpack:serve": "npm run webpack:setup-env -- webpack serve --open --config webpack.dev.js",
"start": "env COSMOS_CONFIG_FOLDER=/mnt/e/work/Cosmos-Server/zz_test_config/ CONFIG_FILE=./config_dev.json EZ=UTC ACME_STAGING=true build/cosmos",
@ -162,6 +162,7 @@
"webpack-bundle-analyzer": "^4.10.1",
"webpack-cli": "^5.1.4",
"webpack-dev-server": "^4.15.1",
"webpack-merge": "^5.10.0"
"webpack-merge": "^5.10.0",
"webpack-preprocessor-loader": "^1.3.0"
}
}
}

View file

@ -4,8 +4,9 @@ const { join } = require("path")
const MiniCssExtractPlugin = require("mini-css-extract-plugin")
const HtmlWebpackPlugin = require("html-webpack-plugin")
const withReport = process.env.withReport ? true : false
const analyzeDeps = process.env.analyzeDeps ? true : false
const isDemo = !!process.env.isDemo
const withReport = !!process.env.withReport
const analyzeDeps = !!process.env.analyzeDeps
module.exports = {
entry: join(__dirname, "client/src/index"),
@ -26,9 +27,13 @@ module.exports = {
rules: [
{
test: /\.(ts|js|mjs|cjs)x?$/i,
use: {
loader: "babel-loader",
},
use: [
"babel-loader",
{
loader: "webpack-preprocessor-loader",
options: { params: { demo: isDemo } }
},
],
exclude: /node_modules/,
},
{

View file

@ -16,7 +16,7 @@ module.exports = merge(process.env.useProduction ? webpackProd : webpackCommon,
static: resolve(__dirname, "static"),
proxy: {
"/cosmos/api": {
target: `http://${process.env.PROXY_HOST || "localhost"}:${process.env.PROXY_PORT}`,
target: "http://localhost:9000",
logLevel: "debug",
secure: false,
ws: true