@opengis/bi
Version:
BI data visualization module
82 lines (74 loc) • 2.43 kB
JavaScript
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import config from '../../config.js';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const rootDir = path.resolve(__dirname, '../..');
const distIndexPath = path.join(rootDir, 'dist', 'index.html');
const distAssetsDir = path.join(rootDir, 'dist', 'assets');
const { disableAuth } = config;
const isProduction = process.env.NODE_ENV === 'production';
async function plugin(fastify) {
// vite server
if (!isProduction) {
const vite = await import('vite');
const viteServer = await vite.createServer({
server: {
middlewareMode: true,
},
});
// hot reload
viteServer.watcher.on('all', (d, t) => {
if (!t.includes('module') && !t.includes('templates')) return;
// console.log(d, t);
viteServer.ws.send({ type: 'full-reload' });
});
// this is middleware for vite's dev servert
fastify.addHook('onRequest', async (req, reply) => {
// const { user } = req.session?.passport || {};
const next = () => new Promise((resolve) => {
viteServer.middlewares(req.raw, reply.raw, () => resolve());
});
await next();
});
fastify.get('*', async () => {});
return;
}
// From Build
fastify.get('*', async (req, reply) => {
// console.log(disableAuth)
if (!req.user && !disableAuth) return reply.redirect('/login');
if (!fs.existsSync(distIndexPath)) {
return reply
.code(503)
.type('text/plain')
.send('index.html not found in dist. Run: npm run build-app');
}
const stream = fs.createReadStream(distIndexPath);
return reply
.headers({ 'Cache-Control': 'public, no-cache' })
.type('text/html')
.send(stream);
});
fastify.get('/assets/:file', async (req, reply) => {
const stream = fs.createReadStream(path.join(distAssetsDir, req.params.file));
const ext = path.extname(req.params.file);
const mime = {
'.js': 'text/javascript',
'.css': 'text/css',
'.woff2': 'application/font-woff',
'.png': 'image/png',
}[ext];
// reply.cacheControl('max-age', '1d');
return mime
? reply
.headers({
'Cache-Control': 'public, max-age=3600',
'Content-Encoding': 'identity',
})
.type(mime)
.send(stream)
: stream;
});
}
export default plugin;