Skip to content

Commit 804e87a

Browse files
authored
Merge pull request #12 from notabugio/scoped
0.9.0 - Major refactor for scopes/lenses/spaces
2 parents 88afd70 + d31c093 commit 804e87a

24 files changed

+268
-560
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,3 +27,4 @@ npm-debug.log*
2727
yarn-debug.log*
2828
yarn-error.log*
2929
*.swp
30+
*.swo

package.json

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "notabug",
3-
"version": "0.8.24",
3+
"version": "0.9.0",
44
"dependencies": {
55
"@trust/webcrypto": "^0.9.2",
66
"babel-cli": "^6.26.0",
@@ -54,7 +54,8 @@
5454
"text-encoding": "^0.6.4",
5555
"urllite": "^0.5.0",
5656
"uuid": "^3.2.1",
57-
"worker-loader": "^1.1.1"
57+
"worker-loader": "^1.1.1",
58+
"zalgo-promise": "^1.0.28"
5859
},
5960
"scripts": {
6061
"ui": "NODE_PATH=src/ react-app-rewired start",

server/http.js

Lines changed: 5 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,8 @@ import express from "express";
33
import expressStaticGzip from "express-static-gzip";
44
import expires from "express-cache-headers";
55
import init from "notabug-peer";
6-
import { listingMeta, things } from "./listings";
76

8-
export const initServer = ({ port, host, redis, render, ...options }) => {
7+
export const initServer = ({ port, host, render, ...options }) => {
98
let nab;
109
const app = express();
1110
const router = express.Router();
@@ -19,47 +18,21 @@ export const initServer = ({ port, host, redis, render, ...options }) => {
1918
});
2019
}
2120

22-
const cache = (redis && false) ? require("express-redis-cache")({
23-
client: require("redis").createClient({ db: 1 }),
24-
expire: 30
25-
}) : { route() { return (req, res, next) => next(); } };
26-
2721
// Static Media
2822
router.use(
29-
"/media",
30-
expires({ ttl: 60*60*24 }),
23+
"/media", expires({ ttl: 60*60*24 }),
3124
expressStaticGzip(path.join(__dirname, "..", "htdocs", "media"), { index: false })
3225
);
3326
router.use(
34-
"/static",
35-
expires({ ttl: 60*60*24 }),
27+
"/static", expires({ ttl: 60*60*24 }),
3628
expressStaticGzip(path.join(__dirname, "..", "htdocs", "static"), { index: false })
3729
);
3830
router.use(express.static(path.join(__dirname, "..", "htdocs"), { index: false }));
3931

40-
// REST API
41-
app.get(
42-
"/api/topics/:topic.json",
43-
expires(60), cache.route({ expires: 60 }),
44-
(req, res) => listingMeta(nab, req, res)
45-
);
46-
47-
app.get(
48-
"/api/submissions/:opId.json",
49-
expires(60), cache.route({ expires: 60 }),
50-
(req, res) => listingMeta(nab, req, res)
51-
);
52-
53-
app.get(
54-
"/api/things/:id.json",
55-
expires(2*60*60), cache.route({ expires: 2*60*60 }),
56-
(req, res) => things(nab, req, res)
57-
);
58-
5932
// Page Rendering
60-
renderer && app.get("^/$", expires(60), cache.route({ expires: 60 }), renderer);
33+
renderer && app.get("^/$", expires(60), renderer);
6134
app.use(router); // Static Media
62-
renderer && app.get("*", expires(60), cache.route({ expires: 60 }), renderer);
35+
renderer && app.get("*", expires(60), renderer);
6336

6437
return nab = init({ ...options, web: app.listen(port, host) });
6538
};

server/index.js

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ const options = commandLineArgs([
77
{ name: "redis", alias: "r", type: Boolean, defaultValue: false },
88
{ name: "localStorage", alias: "l", type: Boolean, defaultValue: false },
99
{ name: "disableValidation", alias: "D", type: Boolean, defaultValue: false },
10-
{ name: "score", alias: "s", type: Boolean, defaultValue: false },
1110
{ name: "json6", alias: "j", type: Boolean }, // TODO: gun-file is broken do not use
1211
{ name: "evict", alias: "e", type: Boolean, defaultValue: false },
1312
{ name: "debug", alias: "d", type: Boolean, defaultValue: false },
@@ -17,7 +16,6 @@ const options = commandLineArgs([
1716
{ name: "host", alias: "h", type: String, defaultValue: "127.0.0.1" },
1817
{ name: "peer", alias: "c", multiple: true, type: String },
1918
{ name: "until", alias: "u", multiple: true, type: Number, defaultValue: 1000 },
20-
{ name: "watch", alias: "i", type: Boolean, defaultValue: false },
2119
{ name: "listings", alias: "v", type: Boolean, defaultValue: false },
2220
{ name: "index", alias: "w", type: Boolean, defaultValue: false }
2321
]);
@@ -62,7 +60,7 @@ const peerOptions = {
6260
persist: options.persist,
6361
disableValidation: options.disableValidation,
6462
until: options.until,
65-
scoreThingsForPeers: options.score,
63+
computed: true,
6664
super: true
6765
};
6866

@@ -78,11 +76,6 @@ if (options.port) {
7876
nab = init(peerOptions);
7977
}
8078

81-
if (options.watch) {
82-
nab.watchListing({ days: options.days });
83-
setInterval(() => nab.watchListing({ days: options.days }), 1000*60*60);
84-
}
85-
8679
if (options.index) {
8780
const indexed = {};
8881
nab.gun.get("nab/things").map().once(function ({ id }) {

server/listings.js

Lines changed: 0 additions & 130 deletions
This file was deleted.

server/renderer.js

Lines changed: 48 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -1,68 +1,64 @@
11
import Promise from "promise";
22
import React from "react";
3-
import { StaticRouter, matchPath } from "react-router-dom";
3+
import { StaticRouter as Router, matchPath } from "react-router-dom";
44
import { renderToString } from "react-dom/server";
5-
//import { initialize } from "freactal/lib/server";
6-
// import our main App component
75
import { App } from "components/notabug";
86
import { routes } from "components/notabug/routes";
9-
//import { provideState } from "freactal";
10-
import { calculateListing } from "./listings";
117
import init from "notabug-peer";
128
import serialize from "serialize-javascript";
139

1410
const path = require("path");
15-
const fs = require("fs");
11+
const { readFile } = require("fs");
1612

17-
export default (nab, req, res) => {
18-
// point to the html file created by CRA"s build tool
19-
const filePath = path.resolve(__dirname, "..", "htdocs", "index.html");
20-
fs.readFile(filePath, "utf8", (err, htmlData) => {
21-
if (err) {
22-
console.error("err", err);
23-
return res.status(404).end();
24-
}
13+
const calculateListing = (nab, req, routeMatch, scope) => {
14+
let params;
15+
const opId = req.params.opId || (routeMatch && routeMatch.params.submission_id);
2516

26-
let routeMatch;
27-
const route = routes.find(route => {
28-
const match = matchPath(req.path, route);
29-
if (match) routeMatch = match;
30-
return match;
31-
});
17+
if (opId) {
18+
params = { submissionId: opId, sort: "new" };
19+
} else {
20+
const count = parseInt(req.query.count || 0, 10);
21+
const topic = req.params.topic || (routeMatch && routeMatch.params.topic) || "all";
22+
const topics = [topic];
23+
const sort = req.params.sort || (routeMatch && routeMatch.params.sort);
24+
const days = parseInt(req.query.days, 10);
25+
const limit = parseInt(req.query.limit, 10) || 25;
26+
params = { topics, sort, days, count, limit };
27+
}
3228

33-
if (!route) {
34-
return res.status(404).end();
35-
}
36-
37-
route.getStaticPeer = () => {
38-
const staticPeer = init({ noGun: true, localStorage: false, disableValidation: true });
39-
return calculateListing(nab, req, routeMatch)
40-
.then(staticPeer.loadState).then(() => staticPeer);
41-
};
29+
return nab.scopedListing({ scope: scope || nab.newScope() }).withData.query(params);
30+
};
4231

43-
return Promise.resolve(route && route.getStaticPeer && route.getStaticPeer(routeMatch))
44-
.then(staticPeer => {
45-
try {
46-
const context={};
47-
const html = renderToString((
48-
<StaticRouter context={context} location={req.url}>
49-
<App notabugApi={staticPeer} />
50-
</StaticRouter>
51-
));
52-
// inject the rendered app into our html and send it
53-
console.log("server rendered", req.url);
54-
const stateScript = `
32+
export default (nab, req, res) => readFile(
33+
path.resolve(__dirname, "..", "htdocs", "index.html"), "utf8",
34+
(err, htmlData) => {
35+
if (err) return console.error("err", err) || res.status(404).end();
36+
let routeMatch;
37+
const isJson = (/\.json$/.test(req.path));
38+
const urlpath = (isJson ? req.path.replace(/\.json$/, "") : req.path).replace(/^\/api/, "");
39+
const url = isJson ? req.url.replace(req.path, urlpath) : req.url;
40+
const route = routes.find(route => routeMatch = matchPath(urlpath, route));
41+
if (!route) return res.status(404).end();
42+
const staticPeer = init({ noGun: true, localStorage: false, disableValidation: true });
43+
const scope = staticPeer.scope = nab.newScope({ isCacheing: true });
44+
route.query = () => calculateListing(nab, req, routeMatch, scope).then(() => staticPeer);
45+
return Promise.resolve(route.query && route.query(routeMatch)).then(() => {
46+
const html = renderToString((
47+
<Router context={{}} location={url}><App notabugApi={staticPeer} /></Router>
48+
));
49+
console.log("server rendered", isJson ? "json" : "html", url);
50+
if (isJson) return res.send(staticPeer.scope.getCache());
51+
const stateScript = `
5552
<script type="text/javascript">
56-
window.initNabState = ${serialize(staticPeer.getState(), { isJSON: true })};
53+
window.initNabState = ${serialize(staticPeer.scope.getCache(), { isJSON: true })};
5754
</script>
58-
`;
59-
const parts = htmlData.split("!!!CONTENT!!!");
60-
const result = [parts[0], html, stateScript, parts[1]].join("");
61-
return res.send(result);
62-
} catch (e) {
63-
console.error("error generating page", (e && e.stack) || e);
64-
res.send(htmlData.replace("!!!CONTENT!!!", "<noscript>Something Broke</noscript>"));
65-
}
66-
});
55+
`;
56+
const parts = htmlData.split("!!!CONTENT!!!");
57+
const result = [parts[0], html, stateScript, parts[1]].join("");
58+
return res.send(result);
59+
}).catch(e => {
60+
console.error("error generating page", (e && e.stack) || e);
61+
res.status(500).end();
62+
// res.send(htmlData.replace("!!!CONTENT!!!", "<noscript>Something Broke</noscript>"));
63+
});
6764
});
68-
};

0 commit comments

Comments
 (0)