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
+3223 -53

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
{
"semi": true,
"arrowParens": "always",
"singleQuote": true,
"trailingComma": "all"
}
+20
View File
@@ -0,0 +1,20 @@
{
"editor.tabSize": 2,
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"[vue]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"[html]": {
"editor.defaultFormatter": "vscode.html-language-features",
"editor.formatOnSave": true
},
"sort-imports.on-save": true
}
+8
View File
@@ -16,6 +16,8 @@
"dependencies": { "dependencies": {
"@fastify/cors": "^7.0.0", "@fastify/cors": "^7.0.0",
"fastify": "^3.29.0", "fastify": "^3.29.0",
"fastify-vite": "^3.0.0-beta.16",
"fastify-vite-vue": "^3.0.0-beta.3",
"gray-matter": "^4.0.3", "gray-matter": "^4.0.3",
"js-yaml": "^4.1.0", "js-yaml": "^4.1.0",
"jsonschema-definer": "^1.3.2", "jsonschema-definer": "^1.3.2",
@@ -29,5 +31,11 @@
"ts-node-dev": "^1.1.8", "ts-node-dev": "^1.1.8",
"tsconfig-paths": "^4.0.0", "tsconfig-paths": "^4.0.0",
"typescript": "^4.6.4" "typescript": "^4.6.4"
},
"importSort": {
".js, .ts": {
"parser": "typescript",
"style": "module"
}
} }
} }
+1 -2
View File
@@ -1,4 +1,3 @@
import fastifyCors from '@fastify/cors';
import fastify from 'fastify'; import fastify from 'fastify';
import kanjiRouter from './router/kanji'; import kanjiRouter from './router/kanji';
@@ -14,7 +13,7 @@ async function main() {
prettyPrint: isDev, prettyPrint: isDev,
}, },
}); });
app.register(fastifyCors); app.register(import('@fastify/cors'));
app.register(kanjiRouter, { app.register(kanjiRouter, {
prefix: '/api/kanji', prefix: '/api/kanji',
+8 -1
View File
@@ -1,3 +1,10 @@
{ {
"extends": "../../tsconfig.json" "extends": "../../tsconfig.json",
"ts-node": {
"transpileOnly": true,
"compilerOptions": {
"module": "CommonJS",
"noImplicitAny": false
}
}
} }
File diff suppressed because it is too large. Load diff
+22 -12
View File
@@ -4,29 +4,39 @@
"version": "1.0.0", "version": "1.0.0",
"license": "MIT", "license": "MIT",
"scripts": { "scripts": {
"dev": "yarn server", "dev": "yarn ts ./server",
"prod": "yarn build && yarn server:prod", "build": "vite build && vite build --ssr && vite-plugin-ssr prerender",
"build": "vite build && vite build --ssr", "ts": "ts-node",
"render": "yarn build && vite-plugin-ssr prerender", "start": "NODE_ENV=production ts-node ./server"
"server": "ts-node ./server",
"server:prod": "cross-env NODE_ENV=production ts-node ./server"
}, },
"dependencies": { "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", "@vitejs/plugin-vue": "^2.2.2",
"@vue/compiler-sfc": "^3.2.31", "@vue/compiler-sfc": "^3.2.31",
"@vue/server-renderer": "^3.2.31", "@vue/server-renderer": "^3.2.31",
"compression": "^1.7.4", "compression": "^1.7.4",
"cross-env": "^7.0.3",
"express": "^4.17.3", "express": "^4.17.3",
"vite": "^2.8.4", "@fastify/compress": "^5.0.0",
"vite-plugin-ssr": "^0.3.64", "@fastify/express": "^1.1.0",
"vue": "^3.2.31"
},
"devDependencies": {
"@types/compression": "^1.7.2", "@types/compression": "^1.7.2",
"@types/express": "^4.17.13", "@types/express": "^4.17.13",
"@types/node": "^17.0.19", "@types/node": "^17.0.19",
"cross-env": "^7.0.3",
"pino-pretty": "^7.6.1",
"ts-node": "^10.5.0", "ts-node": "^10.5.0",
"typescript": "^4.5.5" "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()
}
+31 -27
View File
@@ -1,43 +1,47 @@
import express from 'express' import fastify from 'fastify'
import compression from 'compression'
import { createPageRenderer } from 'vite-plugin-ssr'
const isProduction = process.env.NODE_ENV === 'production' import { getPath, isDev, port } from './shared'
const root = `${__dirname}/..`
startServer() export async function fastifyServer() {
const app = fastify({
logger: {
prettyPrint: isDev
}
})
async function startServer() { if (isDev) {
const app = express() const vite = await import('vite')
const { createPageRenderer } = await import('vite-plugin-ssr')
app.use(compression()) await app.register(import('@fastify/express'))
app.register(import('@fastify/compress'), { global: false })
let viteDevServer const viteDevServer = await vite.createServer({
if (isProduction) { root: getPath(),
app.use(express.static(`${root}/dist/client`))
} else {
const vite = require('vite')
viteDevServer = await vite.createServer({
root,
server: { middlewareMode: 'ssr' }, server: { middlewareMode: 'ssr' },
}) })
app.use(viteDevServer.middlewares) app.use(viteDevServer.middlewares)
}
const renderPage = createPageRenderer({ viteDevServer, isProduction, root }) const renderPage = createPageRenderer({ viteDevServer, isProduction: !isDev, root: getPath() })
app.get('*', async (req, res, next) => { app.get('*', async (req, res) => {
const url = req.originalUrl const url = req.raw.url || req.url
const pageContextInit = { const pageContextInit = {
url, url,
} }
const pageContext = await renderPage(pageContextInit) const pageContext = await renderPage(pageContextInit)
const { httpResponse } = pageContext const { httpResponse } = pageContext
if (!httpResponse) return next() if (!httpResponse) return
const { body, statusCode, contentType } = httpResponse const { body, statusCode, contentType } = httpResponse
res.status(statusCode).type(contentType).send(body) res.status(statusCode).type(contentType).compress(body)
})
} else {
app.register(import('@fastify/static'), {
root: getPath('dist/client')
}) })
}
const port = process.env.PORT || 3000
app.listen(port) 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"], "types": ["vite/client"],
"skipLibCheck": true, "skipLibCheck": true,
"esModuleInterop": 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": { "ts-node": {
"transpileOnly": true, "transpileOnly": true,
File diff suppressed because it is too large. Load diff