stackpress
Version:
Incept is a content management framework.
69 lines (68 loc) • 2.54 kB
JavaScript
import { IncomingMessage, ServerResponse } from 'node:http';
import reactus, { Server as ReactusServer } from 'reactus';
import Status from '@stackpress/lib/Status';
export function config(server) {
const cwd = server.config.path('server.cwd', process.cwd());
const options = server.config.path('view.engine', {});
const engine = reactus(ReactusServer.configure({
...options,
cwd,
production: false
}));
server.register('reactus', engine);
server.view.render = (action, props) => engine.render(action, props);
server.view.engine = async (action, req, res, ctx) => {
const status = Status.get(res.code || 200);
res.setStatus(status.code, status.status);
const noview = ctx.config.path('view.noview', 'json');
if (res.redirected
|| req.data.has(noview)
|| typeof res.body === 'string')
return;
const props = ctx.config.path('view.props', {});
const session = await ctx.resolve('me', req);
const html = await ctx.view.render(action, {
data: { ...props, ...res.data() },
session: session.results,
request: {
url: {
hash: req.url.hash,
host: req.url.host,
hostname: req.url.hostname,
href: req.url.href,
origin: req.url.origin,
pathname: req.url.pathname,
port: req.url.port,
protocol: req.url.protocol,
search: req.url.search
},
headers: Object.fromEntries(req.headers.entries()),
session: req.session.data,
method: req.method,
mime: req.mimetype,
data: req.data()
},
response: res.toStatusResponse()
});
if (html) {
res.setHTML(html, status.code, status.status);
}
};
}
;
export function route(server) {
server.on('request', async (req, res, ctx) => {
const mode = ctx.config.path('server.mode', 'production');
if (mode === 'production'
|| !(req.resource instanceof IncomingMessage)
|| !(res.resource instanceof ServerResponse))
return;
const reactus = ctx.plugin('reactus');
const im = req.resource;
const sr = res.resource;
await reactus.http(im, sr);
if (sr.headersSent)
res.stop();
});
}
;