redoc/demo/ssr/index.ts

66 lines
2.1 KiB
TypeScript
Raw Normal View History

2018-03-06 14:12:49 +03:00
import { renderToString } from 'react-dom/server';
import * as React from 'react';
import { ServerStyleSheet } from 'styled-components';
import { Redoc, createStore } from '../../';
import { readFileSync } from 'fs';
import { resolve } from 'path';
2021-06-02 15:53:36 +03:00
const yaml = require('js-yaml');
2018-03-06 14:12:49 +03:00
const http = require('http');
const fs = require('fs');
const PORT = 9999;
const server = http.createServer(async (request, response) => {
console.time('request ' + request.url);
if (request.url === '/redoc.standalone.js') {
fs.createReadStream('bundles/redoc.standalone.js', 'utf8').pipe(response);
} else if (request.url === '/') {
2021-06-02 15:53:36 +03:00
const spec = yaml.load(readFileSync(resolve(__dirname, '../openapi.yaml'), 'utf-8'));
const store = await createStore(spec, 'path/to/spec.yaml');
2018-03-06 14:12:49 +03:00
const sheet = new ServerStyleSheet();
const html = renderToString(sheet.collectStyles(React.createElement(Redoc, { store })));
const css = sheet.getStyleTags();
const res = `<html>
<head>
<meta charset="utf8" />
<title>ReDoc</title>
<!-- needed for adaptive design -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
padding: 0;
margin: 0;
}
</style>
<script src="redoc.standalone.js"></script>
<link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700" rel="stylesheet">
${css}
</head>
<body>
<script>
2018-03-06 14:12:49 +03:00
document.addEventListener('DOMContentLoaded', function() {
const state = ${JSON.stringify(await store.toJS())};
Redoc.hydrate(state, document.getElementById('redoc'));
2018-03-06 14:12:49 +03:00
});
</script>
<div id="redoc">${html}</div>
2018-03-06 14:12:49 +03:00
</body>
</html>`;
response.writeHead(200, { 'Content-Length': res.length });
2018-03-06 14:12:49 +03:00
response.write(res);
response.end();
} else {
response.writeHead(404);
response.write('Not found');
response.end();
}
console.timeEnd('request ' + request.url);
});
server.listen(PORT, () => console.log(`Server started: http://127.0.0.1:${PORT}`));