Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# Hello World (Wide) Web

Webserver that shows HTML with "Hello World" and some version information, along with a simple (JSON) API.
Main purpose is to test CI/CD workflows (builds, deployments, …) and tools (Docker, Kubernetes, …) and services.

* no build step
Expand Down Expand Up @@ -36,6 +37,63 @@ cp .env-default .env
docker compose up --build
```

## API

A small API is served with some functions that are usefull to test and debug deployments.

### examples

```bash
curl 'http://localhost:8081/api/time'
# {"now":"2022-12-10T09:27:02.582Z"}

curl --json '{"hello":"world"}' 'http://localhost:8081/api/echo?delay=1000'
# {"echo":{"hello":"world"}}
```

### global query parameters

Global query parameters apply to any API method.

#### `delay`

Adding a `delay` parameter with a number will pause for the given number in miliseconds,
e.g. `?delay=1000` will pause for 1 second before the request is processed.

<!-- NOTE: copied / kept in sync with views/home/section-api.html -->

### methods

<!-- markdownlint-disable MD033 -- allow HTML-->
<table>
<thead>
<tr>
<th>name</th>
<th>method</th>
<th>path</th>
<th>description</th>
</tr>
</thead>
<tbody>
<tr>
<td>config</td>
<td>GET</td>
<td><a href="/api/config">/api/config</a></td>
<td>
<small>config as shown above</code></small>
</td>
</tr>
<tr>
<td>time</td>
<td>GET</td>
<td><a href="/api/time">/api/time</a></td>
<td>
<small>current time, e.g. <code>{"now":"2001-01-01T01:01:01.001Z"}</code></small>
</td>
</tr>
</tbody>
</table>

## Debugging

### default (HTTP) port
Expand Down Expand Up @@ -74,3 +132,18 @@ it just help to identifiy the healthcheck requests in logs.
npm i
npm dev
```

### Tests

Unit tests are run using the native node.js test runner, see <https://nodejs.org/docs/latest-v18.x/api/test.html>.

```bash
npm test
```

When running on node.js v19, watch mode is available:

```bash

npm run watch:test
```
15 changes: 15 additions & 0 deletions lib/parse-duration/parseDuration.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// @ts-check
const ms = require("ms");

/**
* @param {string | string[] | require('qs').ParsedQs | undefined} param duration in seconds or as string with unit (see <https://npm.im/ms>)
* @return {number | undefined} parsed duration in milliseconds or undefined if none could be parsed
*/
function parseDuration(param) {
if (!param || typeof param !== "string") return;
const durationParam = String(Array.isArray(param) ? param[0] : param);
const hasUnit = /\D/.test(durationParam);
return hasUnit ? ms(durationParam) : parseInt(String(param), 10) * 1000;
}

exports.parseDuration = parseDuration;
23 changes: 23 additions & 0 deletions lib/parse-duration/parseDuration.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// @ts-check
const test = require("node:test");
const assert = require("node:assert");
const parseDuration = require("./parseDuration");

const expectationsTable = [
["1", 1000],
["2", 2000],
["999", 999000],
["1ms", 1],
["3ms", 3],
["1s", 1000],
["8s", 8000],
["20m", 1200000],
["8h", 28800000],
["3d", 259200000],
];

expectationsTable.forEach(([input, expected]) => {
test(`parse "${input}" as ${expected}`, () => {
assert.strictEqual(parseDuration(input), expected);
});
});
49 changes: 20 additions & 29 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 7 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,25 @@
},
"scripts": {
"start": "DEBUG='hello-world-web:*' node ./bin/www",
"test": "node --test lib/",
"watch:test": "node --test --watch lib/",
"dev": "DEBUG='hello-world-web:*' nodemon -e html,js,css,json,env -w '**/*' -w .env ./bin/www"
},
"dependencies": {
"cookie-parser": "~1.4.4",
"debug": "~2.6.9",
"dotenv": "^16.0.3",
"express": "~4.18.2",
"morgan": "~1.9.1"
"morgan": "~1.9.1",
"ms": "^2.1.3"
},
"devDependencies": {
"@types/express": "^4.17.15",
"@types/node": "^18.11.18",
"nodemon": "^2.0.20",
"prettier": "^2.8.0"
},
"engines": {
"node": ">=18.x.x"
}
}
44 changes: 41 additions & 3 deletions routes/api/api.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,23 @@
// @ts-check
const express = require("express");
const router = express.Router();
const config = require("../../config");
const { parseDuration } = require("../../lib/parse-duration/parseDuration");
const { getClientInfo } = require("../../lib/client-info/clientInfo");
const config = require("../../config");

const router = express.Router();

router.use(function delayMiddleware(req, res, next) {
const delay = parseDuration(req.query.delay) || 0;
setTimeout(next, delay);
});

/* GET config */
router.get("/config", function (req, res, next) {
restReponse(res, config);
});

/* GET timestamp */
router.get("/time", function (req, res, next) {
router.get("/time", function (req, res) {
const now = new Date();
restReponse(res, "now", now);
});
Expand All @@ -27,6 +34,37 @@ router.all("/client/:field", function (req, res, next) {
restReponse(res, field, client[field] || null);
});

/* POST echo */
router.post("/echo", function (req, res) {
const echo = req.body;
res.json({ echo });
});

/* GET hang */
router.get("/hang", function (req, res) {
while (true) {}
res.json({ message: "hang ended" });
});

/* GET redirect */
if (!process.env.HWW_NO_REDIRECTS) {
router.get("/redirect", function (req, res, next) {
//redirect
});
}

/* GET status */
router.all("/http-status/:number", function (req, res, next) {
const fallbackStatusCode = 499;
let statusCode = fallbackStatusCode;
try {
statusCode = parseInt(req.params.number, 10);
res.status(statusCode).send({ statusCode });
} catch (error) {
res.status(fallbackStatusCode).send({ statusCode: fallbackStatusCode, error });
}
});

module.exports = router;

function restReponse(res, key, data) {
Expand Down