generated from yandex-praktikum/client-server-template-with-vite
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
95 lines (75 loc) · 2.54 KB
/
index.ts
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
import 'reflect-metadata'
import dotenv from 'dotenv'
import cors from 'cors'
import * as fs from 'fs'
import * as path from 'path'
dotenv.config({ path: path.join(__dirname, '../..', '.env') })
import express from 'express'
import cookieParser from 'cookie-parser'
import { createProxyMiddleware } from 'http-proxy-middleware'
import { YandexAPIRepository } from './packages/server/repository/YandexAPIRepository'
// import sequelize from './packages/server/sequelize'
import themeRouter from './packages/server/routes/theme'
import ForumRouter from './packages/server/routes/forum'
dotenv.config()
async function startServer() {
const app = express()
app.use(cors())
const port = 3001
//
// sequelize
// .sync()
// .then(() => console.log('Database connected successfully!'))
// .catch((error: Error) => console.error('Unable to connect to the database: ', error))
const distPath = path.dirname(require.resolve('./vercel-dist/index.html'))
const template = fs.readFileSync(path.resolve('./vercel-dist/index.html'), 'utf-8')
app.use(express.json())
app.use(
'/api/v2',
createProxyMiddleware({
changeOrigin: true,
cookieDomainRewrite: {
'*': '',
},
target: 'https://ya-praktikum.tech',
})
)
app.use('/api/theme', themeRouter)
app.use('/api/forum', ForumRouter)
app.get('/api', (_, res) => {
res.json('👋 Howdy from the server :)')
})
app.use('/assets', express.static(path.resolve(distPath, 'assets')))
app.use('*', cookieParser(), async (req, res, next) => {
const url = req.originalUrl
try {
const ssrClientPath = require.resolve('vercel-ssr-dist/ssr.cjs')
const mod = await import(ssrClientPath)
const { render } = mod
const [initialState, appHtml] = await render(url, new YandexAPIRepository(req.headers['cookie']))
const initStateSerialized = JSON.stringify(initialState)
const html = template.replace(`<!--ssr-outlet-->`, appHtml).replace('<!--store-data-->', initStateSerialized)
res.status(200).set({ 'Content-Type': 'text/html' }).end(html)
} catch (e) {
next(e)
}
})
app.listen(port, () => {
console.log(` ➜ 🎸 Server is listening on port: ${port}`)
})
}
startServer()
// import express from 'express'
//
// // Middlewares
// const app = express()
// app.use(express.json())
//
// // Routes
// app.get('/', (_, res) => {
// res.json('👋 Howdy from the server :)')
// })
//
// // connection
// const port = process.env.PORT || 9001
// app.listen(port, () => console.log(`Listening to port ${port}`))