Skip to content
This repository has been archived by the owner on Oct 9, 2023. It is now read-only.

Feature/add middlewares to config #186

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions examples/simple/app/assets/javascripts/MyComponent.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
var React = require('react');
var renderReact = require('hypernova-react').renderReact;
const React = require('react');
const { renderReact } = require('hypernova-react');

function MyComponent(props) {
return React.createElement('div', {
onClick() {
alert('Click handlers work.');
},
}, 'Hello, ' + props.name + '!');
}, `Hello, ${props.name}!`);
}

module.exports = renderReact('MyComponent.js', MyComponent);
5 changes: 5 additions & 0 deletions src/Module.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const NativeModules = process.binding('natives');
// this is cool since we can now have different extensions for VM than for where your program is
// running.
// If you want to add an extension then you can use addExtension defined and exported below.
// eslint-disable-next-line no-underscore-dangle
const moduleExtensions = { ...NativeModule._extensions };

function isNativeModule(id) {
Expand Down Expand Up @@ -50,6 +51,7 @@ class Module {
load(filename) {
ok(!this.loaded);
this.filename = filename;
// eslint-disable-next-line no-underscore-dangle
this.paths = NativeModule._nodeModulePaths(path.dirname(filename));
}

Expand All @@ -65,12 +67,14 @@ class Module {
return Module.loadFile(filePath, this);
}

// eslint-disable-next-line no-underscore-dangle
_compile(content, filename) {
const self = this;

function require(filePath) {
return self.require(filePath);
}
// eslint-disable-next-line no-underscore-dangle
require.resolve = request => NativeModule._resolveFilename(request, this);
require.main = process.mainModule;
require.extensions = moduleExtensions;
Expand Down Expand Up @@ -98,6 +102,7 @@ class Module {
}

static loadFile(file, parent) {
// eslint-disable-next-line no-underscore-dangle
const filename = NativeModule._resolveFilename(file, parent);

if (parent) {
Expand Down
1 change: 1 addition & 0 deletions src/createVM.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export default (options = {}) => {

const module = new Module(name, environment);
module.load(name);
// eslint-disable-next-line no-underscore-dangle
module._compile(code, name);

exportsCache.set(key, module.exports);
Expand Down
1 change: 1 addition & 0 deletions src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ const defaultConfig = {
files: [],
logger: {},
plugins: [],
middlewares: [],
port: 8080,
host: '0.0.0.0',
processJobsConcurrent: true,
Expand Down
24 changes: 20 additions & 4 deletions src/worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,26 @@ import bodyParser from 'body-parser';
import './environment';
import logger from './utils/logger';
import renderBatch from './utils/renderBatch';
import { runAppLifecycle, errorSync, raceTo } from './utils/lifecycle';
import { errorSync, raceTo, runAppLifecycle } from './utils/lifecycle';
import BatchManager from './utils/BatchManager';

const attachMiddleware = (app, config) => {
app.use(bodyParser.json(config.bodyParser));
};

const attachMiddlewares = (app, config) => {
attachMiddleware(app, config);

const { middlewares } = config;
if (Array.isArray(middlewares)) {
middlewares.forEach((middleware) => {
if (typeof middleware === 'function') {
app.use(middleware);
}
});
}
};

const attachEndpoint = (app, config, callback) => {
app.post(config.endpoint, renderBatch(config, callback));
};
Expand Down Expand Up @@ -42,7 +55,9 @@ class Server {
try {
this.closing = true;
this.server.close((e) => {
if (e) { logger.info('Ran into error during close', { stack: e.stack }); }
if (e) {
logger.info('Ran into error during close', { stack: e.stack });
}
resolve();
});
} catch (e) {
Expand Down Expand Up @@ -117,8 +132,8 @@ const initServer = (app, config, callback) => {
};

const worker = (app, config, onServer, workerId) => {
// ===== Middleware =========================================================
attachMiddleware(app, config);
// ===== Middlewares =========================================================
attachMiddlewares(app, config);

if (onServer) {
onServer(app, process);
Expand Down Expand Up @@ -154,6 +169,7 @@ const worker = (app, config, onServer, workerId) => {
};

worker.attachMiddleware = attachMiddleware;
worker.attachMiddlewares = attachMiddlewares;
worker.attachEndpoint = attachEndpoint;
worker.initServer = initServer;
worker.Server = Server;
Expand Down
1 change: 1 addition & 0 deletions test/BatchManager-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ jobs.bar.name = 'bar'; // component not registered

const req = {};
const res = {};
// eslint-disable-next-line no-underscore-dangle
const _strategies = {
[COMPONENT_NAME]: sinon.stub().returns('html'),
baz: sinon.stub().returns(undefined),
Expand Down
1 change: 1 addition & 0 deletions test/Module-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ function run(code) {

const module = new Module(name);
module.load(name);
// eslint-disable-next-line no-underscore-dangle
module._compile(code, name);

return module.exports;
Expand Down
68 changes: 34 additions & 34 deletions test/escape-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,52 +12,52 @@ describe('escaping', () => {
});

wrap()
.withGlobal('document', () => ({}))
.describe('with fromScript', () => {
it('loads the escaped content correctly', () => {
const html = toScript({ a: 'b' }, { foo: '</script>', bar: '&gt;', baz: '&amp;' });
const $ = cheerio.load(html);
.withGlobal('document', () => ({}))
.describe('with fromScript', () => {
it('loads the escaped content correctly', () => {
const html = toScript({ a: 'b' }, { foo: '</script>', bar: '&gt;', baz: '&amp;' });
const $ = cheerio.load(html);

global.document.querySelector = () => ({ innerHTML: $($('script')[0]).html() });
global.document.querySelector = () => ({ innerHTML: $($('script')[0]).html() });

const res = fromScript({
a: 'b',
});

assert.isObject(res);
const res = fromScript({
a: 'b',
});

assert.equal(res.foo, '</script>');
assert.equal(res.bar, '&gt;');
assert.equal(res.baz, '&amp;');
});
assert.isObject(res);

it('escapes multiple times the same, with interleaved decoding', () => {
const makeHTML = () => toScript({ attr: 'key' }, {
props: 'yay',
needsEncoding: '" &gt; </script>', // "needsEncoding" is necessary
assert.equal(res.foo, '</script>');
assert.equal(res.bar, '&gt;');
assert.equal(res.baz, '&amp;');
});
const script1 = makeHTML();
const script2 = makeHTML();
assert.equal(script1, script2, 'two successive toScripts result in identical HTML');

const $ = cheerio.load(script1);
it('escapes multiple times the same, with interleaved decoding', () => {
const makeHTML = () => toScript({ attr: 'key' }, {
props: 'yay',
needsEncoding: '" &gt; </script>', // "needsEncoding" is necessary
});
const script1 = makeHTML();
const script2 = makeHTML();
assert.equal(script1, script2, 'two successive toScripts result in identical HTML');

global.document.querySelector = () => ({ innerHTML: $($('script')[0]).html() });
const $ = cheerio.load(script1);

const res = fromScript({ attr: 'key' });
global.document.querySelector = () => ({ innerHTML: $($('script')[0]).html() });

const script3 = makeHTML();
assert.equal(
script1,
script3,
'third toScript after a fromScript call results in the same HTML',
);
const res = fromScript({ attr: 'key' });

assert.isObject(res);
const script3 = makeHTML();
assert.equal(
script1,
script3,
'third toScript after a fromScript call results in the same HTML',
);

assert.equal(res.props, 'yay');
assert.isObject(res);

assert.equal(res.props, 'yay');
});
});
});

it('escapes quotes and fixes data attributes', () => {
const markup = toScript({
Expand Down
4 changes: 4 additions & 0 deletions test/renderBatch-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@ import renderBatch from '../lib/utils/renderBatch';

class Response {
status(status) {
// eslint-disable-next-line no-underscore-dangle
this._status = status;
return this;
}

json(res) {
// eslint-disable-next-line no-underscore-dangle
this._json = res;
return this;
}
Expand All @@ -16,7 +18,9 @@ class Response {

getResponse() {
return {
// eslint-disable-next-line no-underscore-dangle
status: this._status,
// eslint-disable-next-line no-underscore-dangle
json: this._json,
};
}
Expand Down
3 changes: 2 additions & 1 deletion test/server-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ describe('Hypernova server', () => {
'../server.js',
].forEach(module => delete require.cache[require.resolve(module)]);

hypernova = require('../server.js'); // eslint-disable-line global-require
// eslint-disable-next-line import/extensions,global-require
hypernova = require('../server.js');
} catch (e) {
console.error('Couldnt remove dependecy or load the hypernova module.');
}
Expand Down