-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
155 lines (129 loc) · 3.97 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
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
import { Redis } from '@upstash/redis';
import path, { resolve } from 'path';
import express from 'express';
import { createServer as createViteServer } from 'vite';
import sortFiles from './sortFiles.js';
import createMakePage from './serverHelper/createMakePage.js';
import { getEntries, excludeRoutePath } from './serverHelper/helper.js';
import tailwindcss from 'tailwindcss';
import autoprefixer from 'autoprefixer';
import { readFileSync } from 'fs';
import dotenv from 'dotenv';
dotenv.config();
const postsData = JSON.parse(readFileSync('./src/posts.json', 'utf-8')).posts;
const redis = new Redis({
url: process.env.UPSTASH_REDIS_REST_URL,
token: process.env.UPSTASH_REDIS_REST_TOKEN,
});
const __dirname = path.dirname(new URL(import.meta.url).pathname);
const isDev = process.env.NODE_ENV !== 'production';
let vite;
if (isDev) {
vite = await createViteServer({
css: {
postcss: {
plugins: [tailwindcss, autoprefixer], // 미리 import한 플러그인 사용
},
},
server: {
middlewareMode: 'ssr',
hmr: true,
},
root: process.cwd(),
resolve: {
alias: {
'@': '/src',
},
},
});
}
async function createServer() {
const entries = getEntries();
const app = express();
if (!isDev) {
app.use('/dist', express.static(path.resolve(__dirname, 'dist')));
}
app.use('/assets', express.static(path.resolve(__dirname, 'assets')));
const sortedRouteList = sortFiles(Object.keys(entries));
app.get(`/api/views/:id`, async (req, res, next) => {
const id = req.params.id.replace(/^ko\./, '');
const views = (await redis.hincrby('views', id, 1)) ?? 0;
const item = postsData.find(item => item.id === id);
const result = { ...item, views };
res
.status(200)
.set({ 'Content-Type': 'application/json' })
.end(JSON.stringify(result));
});
app.get(`/api/blog/list`, async (req, res, next) => {
const sortedPosts = postsData.sort(
(a, b) => new Date(b.date) - new Date(a.date)
);
const allViews = (await redis.hgetall('views')) || {};
const sortedPostsWithView = sortedPosts.map(item => {
return {
...item,
view: allViews[item.id] || 0,
};
});
res
.status(200)
.set({ 'Content-Type': 'application/json' })
.end(JSON.stringify(sortedPostsWithView));
});
sortedRouteList.forEach(key => {
const pathSplit = key.split('.');
const newPathSplit = pathSplit.slice(0, pathSplit.length - 1);
const expressPath = newPathSplit
.map(item => (item === 'index' ? '' : item))
.filter(item => item)
.join('/');
app.get(`/${expressPath.replace(/_/g, ':')}`, async (req, res, next) => {
if (excludeRoutePath(req.params)) {
next();
return;
}
const protocol = req.protocol;
const host = req.get('host');
const origin = `${protocol}://${host}`;
const props = { id: key, params: req.params, query: req.query, origin };
let finalHtml = '';
try {
const pageIns = createMakePage({ key, req, props, isDev, vite });
finalHtml = await pageIns.run();
} catch (e) {
isDev && vite.ssrFixStacktrace(e);
console.error(e, e.stack);
const pageIns = createMakePage({
key: 'oops',
req,
props,
isDev,
vite,
});
finalHtml = await pageIns.runOops();
}
res.status(200).set({ 'Content-Type': 'text/html' }).end(finalHtml);
});
});
if (isDev) {
app.use(vite.middlewares);
} else {
// 404 Handler
app.use(async (req, res, next) => {
const pageIns = createMakePage({
key: 'notfound',
req,
props: {},
isDev: false,
});
const finalHtml = await pageIns.run404();
res.status(404).set({ 'Content-Type': 'text/html' }).end(finalHtml);
next();
});
}
app.listen(3000, () => {
console.log('Server is running at http://localhost:3000');
});
}
createServer();