Skip to content

Commit

Permalink
0.5.3 ping with sleep + some cleaning
Browse files Browse the repository at this point in the history
  • Loading branch information
jolav committed Oct 8, 2024
1 parent ff34e97 commit 68e7267
Show file tree
Hide file tree
Showing 9 changed files with 115 additions and 75 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
![Active YES](https://img.shields.io/badge/Active-YES-green.svg)
![Version](https://img.shields.io/badge/version-0.5.2-orange.svg)
![Version](https://img.shields.io/badge/version-0.5.3-orange.svg)

# [BETAZONE](https://jolav.github.io/betazone) ![logo](https://github.com/jolav/betazone/blob/master/www/assets/idea64.png?raw=true)

Expand Down
29 changes: 11 additions & 18 deletions server-Node/_config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,13 @@
import { _config } from "./_private.js";
import os from "os";

//import packageJSON from './package.json' with { type: 'json' };
import { readFileSync } from "fs";
const packageJSON = JSON.parse(readFileSync("./package.json"));

const config = {
"version": "0.5.2",
"version": packageJSON.version,
"name": packageJSON.name,
"mode": "dev",
"port": 3000,
};
Expand All @@ -13,29 +18,17 @@ checkMode();

function checkMode() {
const serverName = os.hostname().toLowerCase();

if (!_config.devHosts.includes(serverName)) {
config.mode = _config.mode;
config.port = _config.port;
}
}

export { config };

/* FAKE _private.js
const _config = {
"devHosts": [
"host1",
"host2",
"host3",
"host4",
],
"mode": "production",
"port": 3003,
};
if (config.mode === "dev") {
console.log(config);
}

export {
_config
config
};
*/
9 changes: 0 additions & 9 deletions server-Node/aux.js

This file was deleted.

75 changes: 52 additions & 23 deletions server-Node/betazone.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import express from "express";
import helmet from 'helmet';

import { config } from "./_config.js";
import { logger } from "./middlewares.js";
import { AppError } from "./middlewares.js";
import { mw } from "./middlewares.js";
import { random } from "./random/random.js";
import { tetris } from "./tetris/tetris.js";

Expand All @@ -13,40 +14,68 @@ const app = express();
app.use(helmet());
app.disable('x-powered-by');

app.use(logger);
app.use(mw.logger.bind(mw));

// routes
app.use('/random', random);
app.use("/tetris", tetris);

app.get("/version", function (req, res) {
res
.status(200)
.json({ version: config.version });
mw.sendResult(res, 200, { version: config.version }, false);
});

app.get("/ping", function (req, res) {
res
.status(200)
.json({ ping: "ok" });
app.get("/ping", async function (req, res) {
const start = Date.now();
const min = parseInt(req.query.min) || 0;
const max = parseInt(req.query.max) || 0;
if (min >= max || min < 0 || min > 1000 || max < 1 || max > 1000) {
//console.log(min, max);
mw.sendResult(res, 400, { ping: "badrequest" }, false);
return;
}
await help.sleep(min, max);

const turn = Date.now() - start;
mw.sendResult(res, 200, { ping: turn }, false);
});

// custom 404
app.use(function (req, res) {
console.error('Unavailable Endpoint', req.path);
res.
status(404)
.json({ status: "Unavailable Endpoint " + req.path });
app.use(function notFound(req, res, next) {
next(new AppError(404, "Route Not Found"));
});

// custom error
app.use(function (err, req, res, next) {
console.error(err.stack);
res.
status(500).
json({ status: "Internal Server Error" });
app.use(function errorHandler(err, req, res, next) {
if (!err.isOperational) {
console.error("Unexpected Error:", err.stack || err);
}
const status = err.status || 500;
let message = "Internal Server Error";
if (err.isOperational) {
message = err.message;
}
mw.sendResult(res, status, { "msg": message }, false);
});

app.listen(config.port || 3000, function () {
console.log('Server running on port ', config.port);
app.listen(config.port, function () {
console.log(
'\n*****************************************************\n',
'process.env.pm.id => ', process.env.pm_id + "\n",
'process.pid => ', process.pid + "\n",
'Server', config.name.toUpperCase(),
"version", config.version,
"running on port", config.port, "\n" +
'*****************************************************'
);
});

const help = {
sleep: function (min, max) {
const delay = this.randomInt(min, max);
return new Promise(function (resolve) {
setTimeout(resolve, delay);
});
},
randomInt: function (min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}

};
2 changes: 1 addition & 1 deletion server-Node/ecosystem.config.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

module.exports = {
apps: [{
name: "BetaZone",
name: "betazone",
script: 'betazone.js',
env: {
NODE_ENV: "production",
Expand Down
50 changes: 35 additions & 15 deletions server-Node/middlewares.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,42 @@
/* */

function logger(req, res, next) {
console.log(
getIP(req),
req.method,
req.originalUrl
);
next();
class AppError extends Error {
constructor(status, message) {
super(message);
this.name = 'AppError';
this.status = status;
this.isOperational = true;
Error.captureStackTrace(this, AppError);
}
}

function getIP(req) {
return (
req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress).split(',')[0];
}
const mw = {
logger: function (req, res, next) {
console.log(
this.getIP(req),
req.method,
req.originalUrl
);
next();
},
getIP: function (req) {
return (
req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress).split(',')[0];
},
sendResult: function (res, status, data, pretty) {
if (pretty) {
res.header('Content-Type', 'application/json');
res.status(status).send(JSON.stringify(data, null, 2));
return;
}
res.status(status).json(data);
}
};

export {
logger
AppError,
mw,
};
4 changes: 2 additions & 2 deletions server-Node/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "server-node",
"version": "0.5.2",
"name": "betazone",
"version": "0.5.3",
"description": "server for betazone",
"main": "betazone.js",
"scripts": {
Expand Down
8 changes: 5 additions & 3 deletions server-Node/random/random.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
import express from "express";
const random = express.Router();

import { randomInt } from "../aux.js";

import { createRequire } from "module";
const require = createRequire(import.meta.url);
const surnames = require("./surnames.json");
Expand All @@ -17,4 +15,8 @@ random.get("/name", function (req, res) {
.json({ name: nick });
});

export { random };
export { random };

function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
11 changes: 8 additions & 3 deletions www/apiDoc/apiDoc.html
Original file line number Diff line number Diff line change
Expand Up @@ -64,22 +64,27 @@

<br>


<section id="Ping" class="main-section">
<header class="headerBox">Ping</header>
<span>
<b>Description: </b>Makes a ping to the server<br>
</span>
<span>
<b>HTTP Request: </b>
<code> GET https://m.d100.top/a/ping</code><br>
<code> GET https://m.d100.top/a/ping?min=0&max100</code><br>
<code>min</code> must be between 0-1000<br>
<code>max</code> between 1-1000<br>
<code>max</code>must be greater than <code>min</code><br>
</span>
<span>
<b>Example: </b><br>
<span>&nbsp; -> &nbsp;&nbsp;</span><a href="https://m.d100.top/a/ping">https://m.d100.top/a/ping</a>
<span>&nbsp; -> &nbsp;&nbsp;</span><a
href="https://m.d100.top/a/ping">https://m.d100.top/a/ping?min=0&max=100</a>
</span>
<pre>
{
"ping":"ok"
"ping": 57
}
</pre>
</span>
Expand Down

0 comments on commit 68e7267

Please sign in to comment.