]> Untitled Git - lemmy-ui.git/blob - src/server/index.tsx
Fetching site data first to get UserService / my_user. Fixes #66
[lemmy-ui.git] / src / server / index.tsx
1 // import cookieParser = require('cookie-parser');
2 import serialize from 'serialize-javascript';
3 import express from 'express';
4 import { StaticRouter } from 'inferno-router';
5 import { renderToString } from 'inferno-server';
6 import { matchPath } from 'inferno-router';
7 import path from 'path';
8 import { App } from '../shared/components/app';
9 import { IsoData } from '../shared/interfaces';
10 import { routes } from '../shared/routes';
11 import IsomorphicCookie from 'isomorphic-cookie';
12 import { lemmyHttp, setAuth } from '../shared/utils';
13 import { GetSiteForm } from 'lemmy-js-client';
14 import process from 'process';
15 import { Helmet } from 'inferno-helmet';
16 import { initializeSite } from '../shared/initialize';
17
18 const server = express();
19 const port = 1234;
20
21 server.use(express.json());
22 server.use(express.urlencoded({ extended: false }));
23 server.use('/static', express.static(path.resolve('./dist')));
24
25 // server.use(cookieParser());
26
27 server.get('/*', async (req, res) => {
28   const activeRoute = routes.find(route => matchPath(req.path, route)) || {};
29   const context = {} as any;
30   let auth: string = IsomorphicCookie.load('jwt', req);
31
32   let getSiteForm: GetSiteForm = {};
33   setAuth(getSiteForm, auth);
34
35   let promises: Promise<any>[] = [];
36
37   // Get site data first
38   let site = await lemmyHttp.getSite(getSiteForm);
39   initializeSite(site);
40
41   if (activeRoute.fetchInitialData) {
42     promises.push(...activeRoute.fetchInitialData(auth, req.path));
43   }
44
45   let routeData = await Promise.all(promises);
46
47   // Redirect to the 404 if there's an API error
48   if (routeData[0] && routeData[0].error) {
49     console.log(`Route error: ${routeData[0].error}`);
50     return res.redirect('/404');
51   }
52
53   let acceptLang = req.headers['accept-language']
54     ? req.headers['accept-language'].split(',')[0]
55     : 'en';
56   let lang = !!site.my_user
57     ? site.my_user.lang == 'browser'
58       ? acceptLang
59       : 'en'
60     : acceptLang;
61
62   let isoData: IsoData = {
63     path: req.path,
64     site,
65     routeData,
66     lang,
67   };
68
69   const wrapper = (
70     <StaticRouter location={req.url} context={isoData}>
71       <App site={isoData.site} />
72     </StaticRouter>
73   );
74   if (context.url) {
75     return res.redirect(context.url);
76   }
77
78   const root = renderToString(wrapper);
79   const helmet = Helmet.renderStatic();
80
81   res.send(`
82            <!DOCTYPE html>
83            <html ${helmet.htmlAttributes.toString()} lang="en">
84            <head>
85            <script>window.isoData = ${serialize(isoData)}</script>
86
87            ${helmet.title.toString()}
88            ${helmet.meta.toString()}
89
90            <!-- Required meta tags -->
91            <meta name="Description" content="Lemmy">
92            <meta charset="utf-8">
93            <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
94
95            <!-- Web app manifest -->
96            <link rel="manifest" href="/static/assets/manifest.webmanifest">
97
98            <!-- Icons -->
99            <link rel="shortcut icon" type="image/svg+xml" href="/static/assets/icons/favicon.svg" />
100            <link rel="apple-touch-icon" href="/static/assets/icons/apple-touch-icon.png" />
101
102            <!-- Styles -->
103            <link rel="stylesheet" type="text/css" href="/static/styles/styles.css" />
104
105            <!-- Current theme and more -->
106            ${helmet.link.toString()}
107            </head>
108
109            <body ${helmet.bodyAttributes.toString()}>
110              <noscript>
111                <div class="alert alert-danger rounded-0" role="alert">
112                  <b>Javascript is disabled. Actions will not work.</b>
113                </div>
114              </noscript>
115
116              <div id='root'>${root}</div>
117              <script defer src='/static/js/client.js'></script>
118            </body>
119          </html>
120 `);
121 });
122 let Server = server.listen(port, () => {
123   console.log(`http://localhost:${port}`);
124 });
125
126 /**
127  * Used to restart server by fuseBox
128  */
129 export async function shutdown() {
130   Server.close();
131   Server = undefined;
132 }
133
134 process.on('SIGINT', () => {
135   console.info('Interrupted');
136   process.exit(0);
137 });