add working fastify server

This commit is contained in:
polv committed 2022-05-07 22:42:40 +07:00
1 parent 066f94188a
commit 2396bbcf12
12 files changed
+3228 -58

No files matched your search

+22 -12
View File
@@ -4,29 +4,39 @@
"version": "1.0.0",
"license": "MIT",
"scripts": {
"dev": "yarn server",
"prod": "yarn build && yarn server:prod",
"build": "vite build && vite build --ssr",
"render": "yarn build && vite-plugin-ssr prerender",
"server": "ts-node ./server",
"server:prod": "cross-env NODE_ENV=production ts-node ./server"
"dev": "yarn ts ./server",
"build": "vite build && vite build --ssr && vite-plugin-ssr prerender",
"ts": "ts-node",
"start": "NODE_ENV=production ts-node ./server"
},
"dependencies": {
"@fastify/static": "^5.0.2",
"fastify": "^3.29.0"
},
"devDependencies": {
"vite": "^2.8.4",
"vite-plugin-ssr": "^0.3.64",
"vue": "^3.2.31",
"@vitejs/plugin-vue": "^2.2.2",
"@vue/compiler-sfc": "^3.2.31",
"@vue/server-renderer": "^3.2.31",
"compression": "^1.7.4",
"cross-env": "^7.0.3",
"express": "^4.17.3",
"vite": "^2.8.4",
"vite-plugin-ssr": "^0.3.64",
"vue": "^3.2.31"
},
"devDependencies": {
"@fastify/compress": "^5.0.0",
"@fastify/express": "^1.1.0",
"@types/compression": "^1.7.2",
"@types/express": "^4.17.13",
"@types/node": "^17.0.19",
"cross-env": "^7.0.3",
"pino-pretty": "^7.6.1",
"ts-node": "^10.5.0",
"typescript": "^4.5.5"
},
"importSort": {
".js, .ts": {
"parser": "typescript",
"style": "module"
}
}
}
+43
View File
@@ -0,0 +1,43 @@
import compression from 'compression'
import express from 'express'
import { createPageRenderer } from 'vite-plugin-ssr'
import { getPath, isProduction, port } from './shared'
export async function expressServer() {
const app = express()
app.use(compression())
let viteDevServer
if (isProduction) {
app.use(express.static(getPath('dist/client')))
} else {
const vite = require('vite')
viteDevServer = await vite.createServer({
root: getPath(),
server: { middlewareMode: 'ssr' },
})
app.use(viteDevServer.middlewares)
}
const renderPage = createPageRenderer({ viteDevServer, isProduction, root: getPath() })
app.get('*', async (req, res, next) => {
const url = req.originalUrl
const pageContextInit = {
url,
}
const pageContext = await renderPage(pageContextInit)
const { httpResponse } = pageContext
if (!httpResponse) return next()
const { body, statusCode, contentType } = httpResponse
res.status(statusCode).type(contentType).send(body)
})
app.listen(port)
console.log(`Server running at http://localhost:${port}`)
}
if (require.main === module) {
expressServer()
}
+36 -32
View File
@@ -1,43 +1,47 @@
import express from 'express'
import compression from 'compression'
import { createPageRenderer } from 'vite-plugin-ssr'
import fastify from 'fastify'
const isProduction = process.env.NODE_ENV === 'production'
const root = `${__dirname}/..`
import { getPath, isDev, port } from './shared'
startServer()
export async function fastifyServer() {
const app = fastify({
logger: {
prettyPrint: isDev
}
})
async function startServer() {
const app = express()
if (isDev) {
const vite = await import('vite')
const { createPageRenderer } = await import('vite-plugin-ssr')
app.use(compression())
let viteDevServer
if (isProduction) {
app.use(express.static(`${root}/dist/client`))
} else {
const vite = require('vite')
viteDevServer = await vite.createServer({
root,
await app.register(import('@fastify/express'))
app.register(import('@fastify/compress'), { global: false })
const viteDevServer = await vite.createServer({
root: getPath(),
server: { middlewareMode: 'ssr' },
})
app.use(viteDevServer.middlewares)
const renderPage = createPageRenderer({ viteDevServer, isProduction: !isDev, root: getPath() })
app.get('*', async (req, res) => {
const url = req.raw.url || req.url
const pageContextInit = {
url,
}
const pageContext = await renderPage(pageContextInit)
const { httpResponse } = pageContext
if (!httpResponse) return
const { body, statusCode, contentType } = httpResponse
res.status(statusCode).type(contentType).compress(body)
})
} else {
app.register(import('@fastify/static'), {
root: getPath('dist/client')
})
}
const renderPage = createPageRenderer({ viteDevServer, isProduction, root })
app.get('*', async (req, res, next) => {
const url = req.originalUrl
const pageContextInit = {
url,
}
const pageContext = await renderPage(pageContextInit)
const { httpResponse } = pageContext
if (!httpResponse) return next()
const { body, statusCode, contentType } = httpResponse
res.status(statusCode).type(contentType).send(body)
})
const port = process.env.PORT || 3000
app.listen(port)
console.log(`Server running at http://localhost:${port}`)
}
if (require.main === module) {
fastifyServer()
}
+10
View File
@@ -0,0 +1,10 @@
import path from 'path'
export const port = Number(process.env['PORT'] || 16272)
export const isProduction = process.env['NODE_ENV'] === 'production'
export const isDev = !isProduction
export function getPath(...segments: string[]) {
return path.join(__dirname, '..', ...segments)
}
+17 -1
View File
@@ -8,7 +8,23 @@
"types": ["vite/client"],
"skipLibCheck": true,
"esModuleInterop": true,
"jsx": "preserve"
"jsx": "preserve",
"noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */
"strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */
"strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
"strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
"strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
"noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */
"useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */
"alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
"noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */
"noUnusedParameters": true, /* Raise an error when a function parameter isn't read */
"exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
"noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
"noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
"noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
"noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
"noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */
},
"ts-node": {
"transpileOnly": true,
File diff suppressed because it is too large. Load diff