@opengis/bi
Version:
BI data visualization module
70 lines (63 loc) • 1.96 kB
JavaScript
import fs from 'fs';
import path from 'path';
import config from '../../config.js';
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');
const stream = fs.createReadStream('dist/index.html');
return reply
.headers({ 'Cache-Control': 'public, no-cache' })
.type('text/html')
.send(stream);
});
fastify.get('/assets/:file', async (req, reply) => {
const stream = fs.createReadStream(`dist/assets/${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;