-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathserver.ts
More file actions
167 lines (138 loc) · 5.45 KB
/
Copy pathserver.ts
File metadata and controls
167 lines (138 loc) · 5.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
import { APP_BASE_HREF } from '@angular/common';
import { CommonEngine, isMainModule } from '@angular/ssr/node';
import express from 'express';
import { fileURLToPath } from 'node:url';
import { dirname, join, resolve } from 'node:path';
import { REQUEST } from '@angular/core';
import AppServerModule from './src/main.server';
import { BASE_URL } from './src/app/shared/base-url.token';
import { expressjwt } from 'express-jwt';
import cookieParser from 'cookie-parser';
import session from 'express-session';
import cors from 'cors';
import * as fs from 'node:fs';
import * as routes from './server/routes';
import * as insertions from './server/new-insert';
import authentication from './server/authentication';
// The Express app is exported so that it can be used by serverless Functions.
export function app(): express.Express {
// Config
const CONFIG_FOLDER = join(process.cwd(), 'config');
const config = JSON.parse(fs.readFileSync(join(CONFIG_FOLDER, 'amazon.json'), 'utf8'));
const server = express().disable('x-powered-by').use(cookieParser());
// Rewrite /demo paths to base paths to avoid routing issues and SSR deadlocks
server.use((req, res, next) => {
if (req.url.startsWith('/demo/')) {
req.url = req.url.replace(/^\/demo/, '');
} else if (req.url === '/demo') {
req.url = '/';
}
next();
});
const serverDistFolder = dirname(fileURLToPath(import.meta.url));
const browserDistFolder = resolve(serverDistFolder, '../browser');
const indexHtml = join(serverDistFolder, 'index.server.html');
const commonEngine = new CommonEngine({ allowedHosts: ['localhost', '127.0.0.1'] });
// Basic express session
server.use(
session({
secret: config.session.secret,
saveUninitialized: false,
resave: true
})
);
const jwtCheck = expressjwt({
algorithms: ['HS256'],
secret: config.jwt.secret,
getToken: (req: express.Request) => {
if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
return req.headers.authorization.split(' ')[1];
}
if (req.cookies && req.cookies.SIO_SESSION) {
return req.cookies.SIO_SESSION;
}
return null;
},
});
server.set('view engine', 'html');
server.set('views', browserDistFolder);
server.use(express.json({ limit: '5mb' }));
server.use(express.urlencoded({ extended: false }));
server.use(cors({
origin: ['http://localhost:4200', 'http://localhost:3000', 'http://127.0.0.1:4200', 'http://127.0.0.1:3000'],
credentials: true,
}));
// Check jwt token for these routes
server.use('/api/user', jwtCheck);
// Authentication routes for local, google and facebook
server.use('/auth', authentication());
/* - Express Rest API endpoints - */
server.get('/api/customer', routes.getCustomer);
server.get('/api/shop/:page', routes.getAllProducts);
server.get( '/api/product/:productId', routes.getProductById);
server.get('/api/user/cart', routes.authMiddleware, routes.getFromCart);
server.get('/api/user/cart/count', routes.authMiddleware, routes.getCartCount);
server.get('/api/user/checkout', routes.authMiddleware, routes.getCheckoutInfo);
server.get('/api/user/orders', routes.authMiddleware, routes.getUserOrders);
server.get('/api/user/order/:id', routes.authMiddleware, routes.getOrderById);
server.get('/api/user/settings', routes.authMiddleware, routes.getUserInfo);
server.delete('/api/user/cart/remove/:id', routes.authMiddleware, routes.removeFromCart);
server.post('/api/user/checkout/confirm', routes.authMiddleware, routes.checkoutConfirm);
server.post('/api/user/cart/add', routes.authMiddleware, routes.addToCart);
server.post('/api/user/update', routes.authMiddleware, routes.updateProfile);
server.post('/api/user/laptop', routes.authMiddleware, insertions.newLaptop);
// Serve static files from /browser
server.get('**', express.static(browserDistFolder, {
maxAge: '1y',
index: 'index.html',
}));
// All regular routes use the Angular engine
server.get('**', (req, res, next) => {
console.log(`[Express] [${new Date().toISOString()}] Starting SSR render for ${req.url}`);
const { protocol, originalUrl, headers } = req;
commonEngine
.render({
bootstrap: AppServerModule,
documentFilePath: indexHtml,
url: `${protocol}://${headers.host}${originalUrl}`,
publicPath: browserDistFolder,
providers: [
{ provide: APP_BASE_HREF, useValue: '/demo/' },
{ provide: REQUEST, useValue: req },
{ provide: BASE_URL, useValue: `${protocol}://${headers.host}/demo` }
],
})
.then((html) => {
console.log(`[Express] [${new Date().toISOString()}] Finished SSR render for ${req.url}`);
res.send(html);
})
.catch((err) => next(err));
});
// For jwt token errors
server.use((
err: Error & { name?: string; status?: number },
_req: express.Request,
res: express.Response,
next: express.NextFunction
) => {
if (err.name === 'StatusError') {
res.status(err.status || 500).send(err.message);
} else {
next(err);
}
});
return server;
}
export const reqHandler = app();
function run(): void {
const port = process.env['PORT'] || 3000;
// Start up the Node server
const server = app();
server.listen(port, () => {
console.log(`Node Express server listening on http://localhost:${port}`);
});
}
if (isMainModule(import.meta.url)) {
run();
}
export * from './src/main.server';