@proteinjs/server 1.6.1 → 1.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -19,7 +19,7 @@ import {
19
19
  getStartupTasks,
20
20
  } from '@proteinjs/server-api';
21
21
  import { loadRoutes, loadDefaultStarRoute } from './loadRoutes';
22
- import { Logger } from '@proteinjs/util';
22
+ import { Logger } from '@proteinjs/logger';
23
23
  import { setNodeModulesPath } from './nodeModulesPath';
24
24
 
25
25
  interface ExtendedIncomingMessage extends IncomingMessage {
@@ -32,7 +32,7 @@ interface ExtendedSocket extends Socket {
32
32
  }
33
33
 
34
34
  const staticContentPath = '/static/';
35
- const logger = new Logger('Server');
35
+ const logger = new Logger({ name: 'Server' });
36
36
  const app = express();
37
37
  const server = new HttpServer(app);
38
38
  export const io = new SocketIOServer(server);
@@ -42,6 +42,7 @@ export async function startServer(config: ServerConfig) {
42
42
  const routes = getRoutes();
43
43
  configureRequests(app);
44
44
  initializeHotReloading(app, config);
45
+ configureSession(app, config);
45
46
  beforeRequest(app, config);
46
47
  loadRoutes(
47
48
  routes.filter((route) => route.useHttp),
@@ -49,8 +50,7 @@ export async function startServer(config: ServerConfig) {
49
50
  config
50
51
  );
51
52
  configureHttps(app); // registering here forces static content to be redirected to https
52
- configureStaticContentRouter(app, config); // registering here prevents sessions from being created on static content requests
53
- configureSession(app, config);
53
+ configureStaticContentRouter(app, config);
54
54
  loadRoutes(
55
55
  routes.filter((route) => !route.useHttp),
56
56
  app,
@@ -69,9 +69,9 @@ export async function startServer(config: ServerConfig) {
69
69
 
70
70
  await runStartupTasks('after server config');
71
71
  if (config.onStartup) {
72
- logger.info(`Starting ServerConfig.onStartup`);
72
+ logger.info({ message: `Starting ServerConfig.onStartup` });
73
73
  await config.onStartup();
74
- logger.info(`Finished ServerConfig.onStartup`);
74
+ logger.info({ message: `Finished ServerConfig.onStartup` });
75
75
  }
76
76
 
77
77
  start(server, config);
@@ -85,15 +85,19 @@ async function runStartupTasks(when: StartupTask['when']) {
85
85
  return;
86
86
  }
87
87
 
88
- logger.info(`Starting ${filteredTasks.length} \`${when}\` startup task${filteredTasks.length > 1 ? 's' : ''}`);
88
+ logger.info({
89
+ message: `Starting ${filteredTasks.length} \`${when}\` startup task${filteredTasks.length > 1 ? 's' : ''}`,
90
+ });
89
91
  await Promise.all(
90
92
  filteredTasks.map(async (task) => {
91
- logger.info(`Starting task: ${task.name}`);
93
+ logger.info({ message: `Starting task: ${task.name}` });
92
94
  await task.run();
93
- logger.info(`Finished task: ${task.name}`);
95
+ logger.info({ message: `Finished task: ${task.name}` });
94
96
  })
95
97
  );
96
- logger.info(`Finished ${filteredTasks.length} \`${when}\` startup task${filteredTasks.length > 1 ? 's' : ''}`);
98
+ logger.info({
99
+ message: `Finished ${filteredTasks.length} \`${when}\` startup task${filteredTasks.length > 1 ? 's' : ''}`,
100
+ });
97
101
  }
98
102
 
99
103
  function configureRequests(app: express.Express) {
@@ -145,7 +149,7 @@ function configureHttps(app: express.Express) {
145
149
  return;
146
150
  }
147
151
 
148
- logger.debug(`Redirecting to https: ${request.headers.host + request.url}`);
152
+ logger.debug({ message: `Redirecting to https: ${request.headers.host + request.url}` });
149
153
  response.redirect('https://' + request.headers.host + request.url);
150
154
  });
151
155
  }
@@ -156,9 +160,9 @@ function configureStaticContentRouter(app: express.Express, config: ServerConfig
156
160
  }
157
161
 
158
162
  app.use(staticContentPath, express.static(config.staticContent.staticContentDir));
159
- logger.info(
160
- `Serving static content on path: ${staticContentPath}, serving from directory: ${config.staticContent.staticContentDir}`
161
- );
163
+ logger.info({
164
+ message: `Serving static content on path: ${staticContentPath}, serving from directory: ${config.staticContent.staticContentDir}`,
165
+ });
162
166
  }
163
167
 
164
168
  function configureSession(app: express.Express, config: ServerConfig) {
@@ -200,7 +204,7 @@ function configureSession(app: express.Express, config: ServerConfig) {
200
204
  function initializeAuthentication(authenticate: (username: string, password: string) => Promise<true | string>) {
201
205
  passport.use(
202
206
  new passportLocal.Strategy(async function (username, password, done) {
203
- logger.info(`Authenticating`);
207
+ logger.info({ message: `Authenticating` });
204
208
  const result = await authenticate(username, password);
205
209
  if (result === true) {
206
210
  return done(null, { username });
@@ -220,17 +224,19 @@ function initializeAuthentication(authenticate: (username: string, password: str
220
224
  }
221
225
 
222
226
  function beforeRequest(app: express.Express, config: ServerConfig) {
223
- let requestCounter: number = 0;
224
227
  if (config.request?.disableRequestLogging == false || typeof config.request?.disableRequestLogging === 'undefined') {
225
- app.use((request: express.Request, response: express.Response, next: express.NextFunction) => {
226
- if (request.path.startsWith('/static') || request.path.startsWith('/favicon.ico')) {
227
- next();
228
- return;
228
+ app.use(async (request: express.Request, response: express.Response, next: express.NextFunction) => {
229
+ if (config.authenticate) {
230
+ await new Promise<void>((resolve, reject) => {
231
+ passport.authenticate('local', function (err, user, info) {
232
+ if (err) {
233
+ reject(err);
234
+ }
235
+
236
+ resolve();
237
+ })(request, response, next);
238
+ });
229
239
  }
230
-
231
- const requestNumber = ++requestCounter;
232
- logger.info(`[#${requestNumber}] Started ${request.originalUrl}`);
233
- response.locals = { requestNumber };
234
240
  next();
235
241
  });
236
242
  }
@@ -244,22 +250,10 @@ function afterRequest(app: express.Express, config: ServerConfig) {
244
250
  if (config.request?.afterRequest) {
245
251
  app.use(config.request.afterRequest);
246
252
  }
247
-
248
- if (config.request?.disableRequestLogging == false || typeof config.request?.disableRequestLogging === 'undefined') {
249
- app.use((request: express.Request, response: express.Response, next: express.NextFunction) => {
250
- if (request.path.startsWith('/static') || request.path.startsWith('/favicon.ico')) {
251
- next();
252
- return;
253
- }
254
-
255
- logger.info(`[#${response.locals.requestNumber}] Finished ${request.originalUrl}`);
256
- next();
257
- });
258
- }
259
253
  }
260
254
 
261
255
  function initializeSocketIO(io: SocketIOServer, app: express.Express) {
262
- const logger = new Logger('SocketIOServer');
256
+ const socketLogger = new Logger({ name: 'SocketIOServer' });
263
257
 
264
258
  // Share session and passport middleware with Socket.IO
265
259
  const wrapMiddleware = (middleware: any) => (socket: any, next: any) => middleware(socket.request, {}, next);
@@ -280,7 +274,7 @@ function initializeSocketIO(io: SocketIOServer, app: express.Express) {
280
274
  // Initialize Socket.IO event handlers
281
275
  io.on('connection', (socket: ExtendedSocket) => {
282
276
  const userInfo = `${socket.request.user} (${socket.id})`;
283
- logger.info(`User connected: ${userInfo}`);
277
+ socketLogger.info({ message: `User connected: ${userInfo}` });
284
278
 
285
279
  // Map this socket to the session id so it can be closed when the session is destroyed
286
280
  const sessionId = socket.request.sessionID;
@@ -289,21 +283,21 @@ function initializeSocketIO(io: SocketIOServer, app: express.Express) {
289
283
  }
290
284
 
291
285
  socket.on('disconnect', (reason) => {
292
- logger.info(`User disconnected: ${userInfo}. Reason: ${reason}`);
286
+ socketLogger.info({ message: `User disconnected: ${userInfo}. Reason: ${reason}` });
293
287
  });
294
288
 
295
289
  socket.on('error', (error) => {
296
- logger.error(`Socket error for user: ${userInfo}. Error:`, error);
290
+ socketLogger.error({ message: `Socket error for user: ${userInfo}`, error });
297
291
  });
298
292
 
299
293
  socket.conn.on('error', (error) => {
300
- logger.error(`Socket connection error for user: ${userInfo}. Error:`, error);
294
+ socketLogger.error({ message: `Socket connection error for user: ${userInfo}`, error });
301
295
  });
302
296
  });
303
297
 
304
298
  // Handle server-level errors
305
- io.engine.on('connection_error', (err) => {
306
- logger.error('Connection error:', err);
299
+ io.engine.on('connection_error', (error) => {
300
+ socketLogger.error({ message: 'Connection error', error });
307
301
  });
308
302
  }
309
303
 
@@ -311,9 +305,9 @@ function start(server: HttpServer, config: ServerConfig) {
311
305
  const port = config.port ? config.port : 3000;
312
306
  server.listen(port, () => {
313
307
  if (process.env.DEVELOPMENT) {
314
- logger.info(`Starting in development mode`);
308
+ logger.info({ message: `Starting in development mode` });
315
309
  }
316
310
 
317
- logger.info(`Server listening on port: ${port}`);
311
+ logger.info({ message: `Server listening on port: ${port}` });
318
312
  });
319
313
  }