UNPKG

stackpress

Version:

Incept is a content management framework.

83 lines (82 loc) 3.34 kB
import { IncomingMessage, ServerResponse } from 'node:http'; import reactus, { Server as ReactusServer } from 'reactus'; import Status from '@stackpress/lib/Status'; export default function plugin(ctx) { ctx.on('config', async (_req, _res, ctx) => { const cwd = ctx.config.path('server.cwd', process.cwd()); const mode = ctx.config.path('server.mode', 'production'); const production = mode === 'production'; const options = ctx.config.path('view.engine', {}); const engine = reactus(ReactusServer.configure({ ...options, cwd, production })); ctx.register('reactus', engine); ctx.view.render = (action, props) => engine.render(action, props); ctx.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); } }; }); ctx.on('route', async (_req, _res, ctx) => { ctx.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(); }); }); ctx.on('idea', async (req) => { const transformer = req.data('transformer'); const schema = await transformer.schema(); if (!schema.plugin) { schema.plugin = {}; } const dirname = typeof __dirname === 'string' ? __dirname : import.meta.dirname; schema.plugin[`${dirname}/transform`] = {}; }); } ;