-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
56 lines (46 loc) · 1.34 KB
/
server.js
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
import express from 'express';
import cors from 'cors';
import movies from './movies.json' assert { type: 'json' }; // Let node server know that this is a json.
import fs from 'fs';
import { INITIAL_HTML } from './dist/index.js';
const app = express();
const port = 3000;
app.use(cors());
app.use(express.static('dist'));
const getFilteredMovies = ({ movies = [], query = '' }) => {
return query ? movies.
filter((movie) => movie.title.toLowerCase().includes(query.toLowerCase())) :
[];
}
app.get('/', (req, res) => {
fs.readFile('index.html', (error, file) =>
res.send(file.toString().replaceAll(
'<!--app-->',
INITIAL_HTML['/']
))
);
})
app.get('/search', (req, res) => {
fs.readFile('index.html', (error, file) => {
const { query: { query } } = req;
const initialData = getFilteredMovies({ movies, query });
res.send(file.toString().replaceAll(
'<!--app-->',
`
<script>window.__INITIAL_DATA__ = ${JSON.stringify({ movies: initialData })}</script>
${
INITIAL_HTML['/search']({
movies: initialData
})
}
`
))}
);
})
app.get('/api/search', (req, res) => {
const { query: { query } } = req;
res.send(getFilteredMovies({ movies, query }));
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
})