feat: pass res to hydrators

This commit is contained in:
cha0s 2020-07-23 23:10:32 -05:00
parent 7f55a32f67
commit bbe5afea39
2 changed files with 27 additions and 17 deletions

View File

@ -1,7 +1,7 @@
/* eslint-disable import/no-extraneous-dependencies */
import {createReadStream} from 'fs';
import http, {ServerResponse} from 'http';
import {join} from 'path';
import {join, resolve} from 'path';
import concat from 'concat-stream-p';
import express from 'express';
@ -11,18 +11,19 @@ import {invokeHookFlat} from 'scwp';
import passport from './passport';
import session from './session';
const hydration = async (req, buffer) => {
const hydration = JSON.stringify(
(await Promise.all(invokeHookFlat('hydration', req)))
.reduce((hydration, result) => ({...hydration, ...result}), {}),
);
return buffer
const hydrate = async (req, res) => (
(await Promise.all(invokeHookFlat('hydrators', req, res)))
.reduce((r, hydration) => ({...r, ...hydration}), {})
);
const deliver = async (buffer, req, res) => (
buffer
.toString()
.replace(
'window.__HYDRATION__ = {};',
`window.__HYDRATION__ = ${hydration};`,
);
};
`window.__HYDRATION__ = ${JSON.stringify(await hydrate(req, res))};`,
)
);
export async function createHttpServer() {
const app = express();
@ -41,7 +42,7 @@ export async function createHttpServer() {
proxy.on('proxyRes', async (proxyRes, req, res) => {
const buffer = await proxyRes.pipe(concat());
if ('text/html; charset=UTF-8' === proxyRes.headers['content-type']) {
res.end(await hydration(req, buffer));
res.end(await deliver(buffer, req, res));
}
else {
res.setHeader('Content-Type', proxyRes.headers['content-type']);
@ -60,7 +61,7 @@ export async function createHttpServer() {
app.use(express.static(join(__dirname, '..', 'client')));
const stream = createReadStream(join(__dirname, '..', 'client', 'index.html'));
const buffer = await stream.pipe(concat());
app.get('*', async (req, res) => res.end(await hydration(req, buffer)));
app.get('*', async (req, res) => res.end(await deliver(buffer, req, res)));
}
};
httpServer.listen(31344, '0.0.0.0');

View File

@ -19,9 +19,18 @@ export default (options = {}) => (
);
registerHooks({
hydration: async (req) => ({
chat: await appChatState(req),
user: await appUserState(req),
usernames: await appUsernamesState(req),
}),
hydrators: async (req, res) => {
if (req.channel && !req.user) {
const {name, type} = req.channel;
if (name !== 'anonymous' || type !== 'r') {
res.redirect('/');
return new Promise(() => {});
}
}
return {
chat: await appChatState(req, res),
user: await appUserState(req, res),
usernames: await appUsernamesState(req, res),
};
},
}, module.id);