Skip to content

Commit

Permalink
fix: various changes
Browse files Browse the repository at this point in the history
  • Loading branch information
clabroche committed Feb 13, 2024
1 parent 1982e7f commit 06e6241
Show file tree
Hide file tree
Showing 58 changed files with 1,600 additions and 683 deletions.
2 changes: 1 addition & 1 deletion common/express-error-handler/src/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const { default: HTTPError } = require('@clabroche/common-express-http-error');
const HTTPError = require('@clabroche/common-express-http-error');
const logger = require('@clabroche/common-express-logger');
const errorCodes = require('./errorCodes');

Expand Down
2 changes: 1 addition & 1 deletion common/express-error-handler/src/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ jest.mock('@clabroche/common-express-logger', () => {
error: jest.fn().mockImplementation(() => mockError),
};
});
const { default: HTTPError } = require('@clabroche/common-express-http-error');
const HTTPError = require('@clabroche/common-express-http-error');
const ErrorHandler = require('./index');

const mockRes = {
Expand Down
4 changes: 2 additions & 2 deletions common/express-http-error/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
"description": "",
"private": true,
"repository": "https://github.com/clabroche/stack-monitor",
"main": "src/index.ts",
"types": "src/index.ts",
"main": "src/index.js",
"types": "src/index.js",
"scripts": {
"test": "echo \"no test\""
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,30 +1,24 @@
import dayjs from 'dayjs';
import { v4 as uuid } from 'uuid';
const dayjs = require('dayjs');
const { v4: uuid } = require('uuid');

export const statusMessage = {
module.exports.statusMessage = {
403: 'Not allowed',
404: 'Resource not found',
500: 'We cannot respond to your request for moment. Contact support for more information',
};

class HTTPError extends Error {
public message: string;

public code: number;

public errorId: string;

public date: string;

public originalMessage: string;

public originalStack?: string;

public details?: string;

/**
*
* @param {string} message
* @param {number} code
* @param {string} errorId
* @param {string} date
* @param {string} stack
*/
constructor(
message: string,
code?: number,
message,
code = 500,
errorId = uuid(),
date = dayjs().format('YYYY-MM-DD HH:mm:ss'),
stack = '',
Expand All @@ -34,11 +28,11 @@ class HTTPError extends Error {
this.errorId = errorId;
this.date = date;
this.message = process.env.NODE_ENV === 'production'
? statusMessage[this.code] || message?.toString() || message
: message?.toString() || message || statusMessage[this.code];
? module.exports.statusMessage[this.code] || message?.toString() || message
: message?.toString() || message || module.exports.statusMessage[this.code];
this.originalMessage = message;
this.originalStack = stack || new Error().stack;
}
}

export default HTTPError;
module.exports = HTTPError;
3 changes: 3 additions & 0 deletions common/express-http-error/src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const HTTPError = require('./HTTPError');

module.exports = HTTPError;
3 changes: 0 additions & 3 deletions common/express-http-error/src/index.ts

This file was deleted.

13 changes: 11 additions & 2 deletions common/express-logger/src/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const uuid = require('uuid').v4;
const dayjs = require('dayjs');
const pathfs = require('path');
const { default: HTTPError } = require('@clabroche/common-express-http-error');
const HTTPError = require('@clabroche/common-express-http-error');
const pino = require('pino');

dayjs.locale('fr');
Expand Down Expand Up @@ -82,15 +82,24 @@ module.exports = {
return conf;
},
info(obj) {
if (process.env.NODE_ENV !== 'DEV') return;
const date = dayjs().format('YYYY-MM-DD HH:mm:ss');
const data = JSON.stringify({ date, ...obj });
conf.infoLogger.info(data);
},
/** @param {HTTPError | Error | string} err */
error(err) {
if (!conf) throw new Error('Logger not inited');
const errorId = uuid();
const date = dayjs().format('YYYY-MM-DD HH:mm:ss');
if (process.env.NODE_ENV !== 'DEV') {
console.log(err?.message || err);
return {
errorId,
date,
};
}

if (!conf) throw new Error('Logger not inited');
let message = '';
if (typeof err === 'string') message = err;
else if (err instanceof HTTPError) message = err.originalMessage;
Expand Down
1 change: 1 addition & 0 deletions common/express/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"@clabroche/common-express-error-handler": "workspace:*",
"@clabroche/common-express-health-check": "workspace:*",
"@clabroche/common-express-logger": "workspace:*",
"@clabroche/common-socket-server": "workspace:*",
"@clabroche/common-swagger": "workspace:*",
"compression": "^1.7.4",
"cookie-parser": "^1.4.6",
Expand Down
70 changes: 41 additions & 29 deletions common/express/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@ const fs = require('fs');
const context = require('@clabroche/common-context').init;
const healthCheck = require('@clabroche/common-express-health-check');
const helmet = require('helmet').default;
const path = require('path');
const cookieParser = require('cookie-parser');
const compression = require('compression');
const pino = require('pino');
const pinoHttp = require('pino-http');
const http = require('http');
const Socket = require('@clabroche/common-socket-server');

require('express-async-errors');

Expand All @@ -26,8 +27,10 @@ module.exports = {
* corsConf?: import('cors').CorsOptions,
* beforeAll?: () => any,
* afterAll?: () => any,
* controllers?: import('express').RequestHandler,
* staticController?: import('express').RequestHandler,
* socket?: boolean,
* onListening?: (server: http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>) => any,
* controllers?: () => import('express').RequestHandler,
* staticController?: string,
* additionalSwaggerPaths?: string[]
* noGreetings?: boolean,
* apiPrefix?: string
Expand All @@ -44,9 +47,11 @@ module.exports = {
corsConf = {},
beforeAll = () => {},
afterAll = () => {},
controllers = () => {},
onListening = () => {},
controllers = () => () => {},
staticController = undefined,
noGreetings = false,
socket = false,
additionalSwaggerPaths = [],
apiPrefix = '/api',
bodyLimit = '50mb',
Expand All @@ -63,6 +68,12 @@ module.exports = {
console.log(`v${appVersion} started, listening on port ${port}.`);

const app = express();

const server = http.createServer(app);
if (socket) {
console.log('Enable socket...');
Socket.sockets.connect(server, '*', '/socket.io');
}
app.use(helmet(
helmetConf,
));
Expand All @@ -88,22 +99,26 @@ module.exports = {
logger.init({
path: pathfs.resolve(baseUrl, 'logs-express'),
});
const accessLogger = pinoHttp.default({
autoLogging: {
ignore: (req) => !!(req.url?.endsWith('/health')),
},
logger: logger.getConf().accessLogger,
serializers: {
req: pino.stdSerializers.wrapRequestSerializer((r) => {
r.headers = {
...r.headers,
cookie: '',
authorization: '',
};
return r;
}),
},
});
let accessLogger = (req, res, next) => next();
if (process.env.NODE_ENV === 'DEV') {
console.log('Dev mode detected, enable access logger');
accessLogger = pinoHttp.default({
autoLogging: {
ignore: (req) => !!(req.url?.endsWith('/health')),
},
logger: logger.getConf().accessLogger,
serializers: {
req: pino.stdSerializers.wrapRequestSerializer((r) => {
r.headers = {
...r.headers,
cookie: '',
authorization: '',
};
return r;
}),
},
});
}
console.log('Enable swagger...');
app.use(swagger);
await initSwagger({
Expand All @@ -115,18 +130,14 @@ module.exports = {
console.log('Apply additional routes...');
app.use(context);

app.use(apiPrefix, accessLogger, controllers);
if (staticController) {
app.use('/', accessLogger, express.static(staticController));
}
app.use(apiPrefix, accessLogger, controllers());
if (!noGreetings) {
app.get('/', (req, res) => res.json({ appName, appVersion }));
}

if (staticController) {
app.use(accessLogger, staticController);
app.use(accessLogger, (req, res) => {
res.sendFile(path.resolve(__dirname, 'public', 'index.html'));
});
}

console.log('Enable error handling...');
app.use(require('@clabroche/common-express-error-handler')());

Expand All @@ -137,7 +148,8 @@ module.exports = {
await beforeAll();

console.log('Launch...');
const server = app.listen(port, async () => {
server.on('listening', () => onListening(server));
server.listen(port, async () => {
console.log('<h1>✓ Launched</h1>');
});
server.on('close', async () => {
Expand Down
7 changes: 0 additions & 7 deletions common/socket-front/src/API.js

This file was deleted.

1 change: 1 addition & 0 deletions common/socket-front/src/Socket.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export default {
init(url, id, path, auth) {
return new Promise((resolve, reject) => {
const socket = io(url, { path });
this.socket = socket;
socket.on('connect', () => socket.emit('socket:register', id, auth, (response) => {
if (response.result === 'ok') {
resolve(socket);
Expand Down
2 changes: 0 additions & 2 deletions common/socket-front/src/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import APILib from './API';
import SocketLib from './Socket';

export const API = APILib;
export const Socket = SocketLib;
19 changes: 19 additions & 0 deletions common/socket-server/src/CustomObservable.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
function CustomObservable() {
/** @type {GenericFunction[]} */
this.funcs = [];
}
/** @param {GenericFunction} fun */
CustomObservable.prototype.subscribe = function (fun) {
this.funcs.push(fun);
};

/** @param {any[]} value */
CustomObservable.prototype.next = function (...value) {
this.funcs.forEach((f) => f(...value));
};

module.exports = CustomObservable;

/**
* @typedef {(...args: any[]) => any} GenericFunction
*/
13 changes: 13 additions & 0 deletions common/socket-server/src/sockets.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
const { Server } = require('socket.io');
const CustomObservable = require('./CustomObservable');

/** @type {Record<string, CustomObservable>} */
const events = {};

module.exports = {
/** @type {Server | null} */
Expand All @@ -8,6 +12,10 @@ module.exports = {
this.io.to(room).emit(channel, ...data);
}
},
on: (event, cb) => {
if (!events[event]) events[event] = new CustomObservable();
events[event].subscribe(cb);
},
/**
*
* @param {*} server
Expand All @@ -23,6 +31,11 @@ module.exports = {
methods: ['GET', 'POST'],
},
});
this.io.on('connection', (_socket) => {
_socket.onAny((event, ...data) => {
events[event]?.next(_socket, ...data);
});
});
this.io.on('connect', (socket) => {
socket.on('socket:register', async (id, auth, callback) => {
try {
Expand Down
1 change: 1 addition & 0 deletions fronts/app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
},
"devDependencies": {
"@clabroche/common-retrigger-all-build": "workspace:*",
"@clabroche/common-socket-front": "workspace:*",
"@clabroche/common-typings": "workspace:*",
"@clabroche/modules-plugins-loader-front": "workspace:*",
"@fortawesome/fontawesome-free": "^6.5.1",
Expand Down
2 changes: 1 addition & 1 deletion fronts/app/src/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ body {
margin: 0;
width: 100vw;
height: 100vh;
background-color: #eee;
background-color: #f2f4f7;
color: #4c4c4c;
font-size: 0.9em;
font-family: JOST, sans-serif;
Expand Down
Loading

0 comments on commit 06e6241

Please sign in to comment.