Pārlūkot izejas kodu

FCM Express Backend: added static logo endpoint GET /logo.png

Christian Kahlau 3 gadi atpakaļ
vecāks
revīzija
eb08c2059e
1 mainītis faili ar 27 papildinājumiem un 4 dzēšanām
  1. 27 4
      fcm/express/src/index.ts

+ 27 - 4
fcm/express/src/index.ts

@@ -7,6 +7,8 @@ import path from 'path';
 
 dotenv.config();
 
+const STATIC_WEB_DIR = 'public';
+
 (async () => {
   try {
     const gcmSettings = JSON.parse(
@@ -59,9 +61,24 @@ dotenv.config();
       }
     });
 
-    server.use('/', express.static('public'));
+    server.get('/logo.png', async (req, res, next) => {
+      try {
+        const files = await fsp.readdir(STATIC_WEB_DIR, { encoding: 'utf-8' });
+        const logo = files.find(file => file.includes('logo') && file.endsWith('.png'));
+
+        if (!logo) {
+          throw { type: 'http', message: 'File not found', status: 404 };
+        }
+
+        res.sendFile(path.resolve(STATIC_WEB_DIR, logo));
+      } catch (err) {
+        next(err);
+      }
+    });
+
+    server.use('/', express.static(STATIC_WEB_DIR));
 
-    server.use('**', express.static(path.join('public', 'index.html')));
+    server.use('**', express.static(path.join(STATIC_WEB_DIR, 'index.html')));
 
     server.use((err: any, req: Request, res: Response, next: NextFunction) => {
       let log = false;
@@ -70,8 +87,14 @@ dotenv.config();
         log = true;
         res.status(err.status ?? err.response?.status ?? 500).send(err.message);
       } else {
-        log = true;
-        res.status(500).send(JSON.stringify(err));
+        const keys = Object.keys(err);
+
+        if (keys.includes('type') && err.type === 'http') {
+          res.status(err.status).send(err.message);
+        } else {
+          log = true;
+          res.status(500).send(JSON.stringify(err));
+        }
       }
 
       if (log) console.error('[ERROR] Webservice ErrorHandler caught:', err);