Skip to content
This repository has been archived by the owner on Oct 23, 2024. It is now read-only.

Commit

Permalink
Merge pull request #70 from BonnierNews/feature/es6
Browse files Browse the repository at this point in the history
Convert to ES6 module
  • Loading branch information
MattiasOlla authored Jul 16, 2024
2 parents f3c3f51 + 49bbaa8 commit 79ebfc5
Show file tree
Hide file tree
Showing 34 changed files with 151 additions and 219 deletions.
File renamed without changes.
1 change: 0 additions & 1 deletion .python-version

This file was deleted.

12 changes: 5 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
# LU Server

![Node.js CI](https://github.com/BonnierNews/lu-server/actions/workflows/nodejs.yml/badge.svg)

The base server for lu apps

## usage

```
const express = require("express");
const {buildApp, shutdownHandler} = require("lu-server");
```js
import express from "express";
import { buildApp, shutdownHandler } from "lu-server";

const routes = express.Router();
routes.get("/", (req, res) => res.status(200).send("Hello World!"));
const app = buildApp(routes);
Expand All @@ -26,7 +28,3 @@ process.on("SIGTERM", async () => {
}
});
```

## Version notes:
v1.x supports node 8,10 (but works at least to node 14)
v2.x supports node 12,14,16
27 changes: 12 additions & 15 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
"use strict";

const express = require("express");
const http = require("http");
const https = require("https");
const bodyParser = require("body-parser");
const middleware = require("./lib/middleware.js");
const routes = require("./lib/routes.js");
const config = require("exp-config");
const sigtermHandler = require("./lib/handle-sigterm");

function init() {
import express from "express";
import http from "http";
import https from "https";
import bodyParser from "body-parser";
import config from "exp-config";

import middleware from "./lib/middleware.js";
import routes from "./lib/routes.js";
import { initHandleSigterm } from "./lib/handle-sigterm.js";

export default function init() {
const app = express();

app.disable("x-powered-by");
Expand All @@ -26,7 +25,7 @@ function init() {

process.env.TZ = "Europe/Stockholm";
if (config.luServerShutdown) {
sigtermHandler.initHandleSigterm();
initHandleSigterm();
}

app.use(middleware);
Expand All @@ -42,5 +41,3 @@ function appendRawBody(req, res, next) {
});
next();
}

module.exports = init;
26 changes: 15 additions & 11 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
"use strict";
import config from "exp-config";

const config = require("exp-config");
const notFoundHandler = require("./lib/notFoundHandler");
const errorHandler = require("./lib/errorHandler");
const shutdownHandler = require("./lib/shutdownHandler");
const sigtermHandler = require("./lib/handle-sigterm");
import notFoundHandler from "./lib/notFoundHandler.js";
import errorHandler from "./lib/errorHandler.js";
import appBuilder from "./app.js";
import shutdownHandler from "./lib/shutdownHandler.js";
import sigtermHandler from "./lib/handle-sigterm.js";
import errorHelper from "./lib/render-error.js";
import validator from "./lib/validator.js";

function buildApp(routes) {
const app = require("./app")();
export function buildApp(routes) {
const app = appBuilder();
if (routes) {
app.use(routes);
}
Expand All @@ -20,10 +22,12 @@ function buildApp(routes) {
return app;
}

module.exports = {
export { shutdownHandler, sigtermHandler, errorHelper, validator };

export default {
buildApp,
shutdownHandler,
sigtermHandler,
errorHelper: require("./lib/render-error"),
validator: require("./lib/validator"),
errorHelper,
validator,
};
17 changes: 0 additions & 17 deletions lib/buildApp.js

This file was deleted.

11 changes: 4 additions & 7 deletions lib/errorHandler.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
"use strict";
import config from "exp-config";
import util from "util";
import { logger } from "lu-logger";

const config = require("exp-config");
const util = require("util");
const { logger } = require("lu-logger");

function errorHandler(err, req, res, next) {
export default function errorHandler(err, req, res, next) {
const correlationId = req.correlationId;
if (!err) return next();
let errorMessage = err instanceof Error ? err.toString() : JSON.stringify(err);
Expand All @@ -29,4 +27,3 @@ function errorHandler(err, req, res, next) {

res.status(500).json({ errors, meta: req.debugMeta });
}
module.exports = errorHandler;
22 changes: 12 additions & 10 deletions lib/handle-sigterm.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"use strict";
const config = require("exp-config");
const { logger } = require("lu-logger");
const uuid = require("uuid");
import config from "exp-config";
import { logger } from "lu-logger";
import * as uuid from "uuid";

let shuttingDown = false;
let shuttingDownDebugMeta;
// Should match kubernetes readiness. Configure in .ohoyconf and they will be exposed as env
Expand All @@ -11,7 +11,7 @@ const periodSeconds = asNum(config.READINESSCHECK_PERIODSECONDS, 6);
let stopConsumers = () => Promise.resolve();
let terminateServer = () => Promise.resolve();

function initHandleSigterm() {
export function initHandleSigterm() {
logger.info(`initiating sigterm handler, failureThreshold ${failureThreshold}, periodSeconds ${periodSeconds}`);
let secondsMultiplier = 1000;
let sigtermEvent = "SIGTERM";
Expand Down Expand Up @@ -54,21 +54,23 @@ function asNum(val, fallback) {
return num;
}

function registerConsumerShutdown(callback) {
export function registerConsumerShutdown(callback) {
stopConsumers = callback;
}
function registerServerTerminator(terminator) {

export function registerServerTerminator(terminator) {
terminateServer = terminator;
}

function isShuttingDown() {
export function isShuttingDown() {
return shuttingDown;
}

function shutdownDebugMeta() {
export function shutdownDebugMeta() {
return shuttingDownDebugMeta;
}
module.exports = {

export default {
initHandleSigterm,
registerConsumerShutdown,
registerServerTerminator,
Expand Down
6 changes: 1 addition & 5 deletions lib/is-health-or-metric-request.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@
"use strict";

function isHealthOrMetricRequest(req) {
export default function isHealthOrMetricRequest(req) {
return req.path.startsWith("/_") || req.path.startsWith("/metrics");
}

module.exports = isHealthOrMetricRequest;
22 changes: 10 additions & 12 deletions lib/log-middleware.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
"use strict";
const uuid = require("uuid");
const config = require("exp-config");
const isHealthOrMetricRequest = require("./is-health-or-metric-request");
const { logger } = require("lu-logger");
import * as uuid from "uuid";
import config from "exp-config";
import { logger } from "lu-logger";
import camelcase from "camelcase";

import isHealthOrMetricRequest from "./is-health-or-metric-request.js";

const debugPrefix = "x-debug-meta";
const camelcase = require("camelcase");

function setCorrelationId(req, res, next) {
export function setCorrelationId(req, res, next) {
let correlationId =
req.get("correlation-id") || req.get("x-correlation-id") || req.get(`${debugPrefix}-correlation-id`) || req.body.meta?.correlationId;
if (!correlationId) {
Expand All @@ -20,7 +21,7 @@ function setCorrelationId(req, res, next) {
return next();
}

function setDebugMeta(req, res, next) {
export function setDebugMeta(req, res, next) {
const meta = { correlationId: req.correlationId };
for (const header of Object.keys(req.headers)) {
if (header.startsWith(debugPrefix) && header !== `${debugPrefix}-correlation-id`) {
Expand All @@ -46,7 +47,4 @@ function debugKey(header) {
return camelcase(header.replace(prefixRegExp, ""));
}

module.exports = {
setCorrelationId,
setDebugMeta,
};
export default { setCorrelationId, setDebugMeta };
8 changes: 3 additions & 5 deletions lib/metrics.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
"use strict";

const { pushClient, cloudRunResourceProvider } = require("@bonniernews/gcp-push-metrics");
const { logger } = require("lu-logger");
import { pushClient, cloudRunResourceProvider } from "@bonniernews/gcp-push-metrics";
import { logger } from "lu-logger";

const client = pushClient({ logger, resourceProvider: cloudRunResourceProvider });

Expand Down Expand Up @@ -42,7 +40,7 @@ const httpIncomingRequestErrorsTotal = client.counter({
},
});

module.exports = {
export default {
httpIncomingRequestsTotal,
httpIncomingRequestsInProgress,
httpIncomingRequestDurationSeconds,
Expand Down
21 changes: 10 additions & 11 deletions lib/middleware.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
"use strict";
import express from "express";
import config from "exp-config";
import luLogger, { logger } from "lu-logger";

const express = require("express");
const config = require("exp-config");
const { setCorrelationId, setDebugMeta } = require("./log-middleware");
const { logger, debugMeta } = require("lu-logger");
const isHealthOrMetricRequest = require("./is-health-or-metric-request");
const requestMetrics = require("./request-metrics");
const statusShutdown = require("./status-middleware-when-shutting-down");
import { setCorrelationId, setDebugMeta } from "./log-middleware.js";
import isHealthOrMetricRequest from "./is-health-or-metric-request.js";
import requestMetrics from "./request-metrics.js";
import statusShutdown from "./status-middleware-when-shutting-down.js";

function hasData(obj) {
return obj && Object.keys(obj).length;
Expand Down Expand Up @@ -43,10 +42,10 @@ function accessLog(req, res, next) {
next();
}

const router = express.Router(); // eslint-disable-line new-cap
export const router = express.Router(); // eslint-disable-line new-cap
router.use(setCorrelationId);
router.use(setDebugMeta);
router.use(debugMeta.initMiddleware((req) => req.debugMeta));
router.use(luLogger.debugMeta.initMiddleware((req) => req.debugMeta));
router.use(requestMetrics);
if (config.requestLogging) {
router.use(accessLog);
Expand All @@ -56,4 +55,4 @@ if (config.luServerShutdown) {
logger.info("inited statusShutdown middleware");
}

module.exports = router;
export default router;
6 changes: 1 addition & 5 deletions lib/notFoundHandler.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
"use strict";

function notFoundHandler(req, res) {
export default function notFoundHandler(req, res) {
return res.status(404).json({
errors: [
{
Expand All @@ -13,5 +11,3 @@ function notFoundHandler(req, res) {
meta: req.debugMeta,
});
}

module.exports = notFoundHandler;
14 changes: 4 additions & 10 deletions lib/render-error.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
"use strict";

function render404(res, detail, pointer) {
export function render404(res, detail, pointer) {
const error = {
title: "Not found",
status: "not_found",
Expand All @@ -10,7 +8,7 @@ function render404(res, detail, pointer) {
return renderError(res, 404, error);
}

function render409(res, body, pointer, detail) {
export function render409(res, body, pointer, detail) {
return renderError(
res,
409,
Expand All @@ -24,16 +22,12 @@ function render409(res, body, pointer, detail) {
);
}

function renderError(res, code, error, body = {}) {
export function renderError(res, code, error, body = {}) {
return res.status(code).json({
...body,
errors: [ error ],
meta: { correlationId: res.get("correlation-id") },
});
}

module.exports = {
render404,
render409,
renderError,
};
export default { render404, render409, renderError };
15 changes: 8 additions & 7 deletions lib/request-metrics.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
"use strict";
import config from "exp-config";
import fs from "fs";
import { join } from "path";

const metrics = require("./metrics");
const statusCodeRegex = /^[^2-3]/g;
const callingAppName = require(`${process.cwd()}/package.json`).name;
const config = require("exp-config");
import metrics from "./metrics.js";

const callingAppName = JSON.parse(fs.readFileSync(join(process.cwd(), "package.json"))).name;

module.exports = requestMetrics;
const statusCodeRegex = /^[^2-3]/g;

const ignoredPaths = [ "_alive", "_status", "metrics" ];

function requestMetrics(req, res, next) {
export default function requestMetrics(req, res, next) {
if (ignored(req.path)) return next();

const appName = getAppName();
Expand Down
7 changes: 3 additions & 4 deletions lib/routes.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
"use strict";
import express from "express";

const express = require("express");
const alive = require("./routes/alive.js");
import alive from "./routes/alive.js";

const router = express.Router(); // eslint-disable-line new-cap
router.get("/_alive", alive);
router.head("/_alive", alive);

module.exports = router;
export default router;
Loading

0 comments on commit 79ebfc5

Please sign in to comment.