├── .babelrc
├── .editorconfig
├── .eslintignore
├── .eslintrc.js
├── .flowconfig
├── .gitignore
├── .prettierrc
├── .travis.yml
├── .vscode
├── extensions.json
└── settings.json
├── LICENSE
├── MiddleWare.js
├── README.md
├── TODO.md
├── app.js
├── bin
└── run
├── client
└── index.jsx
├── config
├── .eslintrc.js
└── rollup
│ ├── rollup.config.common.js
│ ├── rollup.config.dev.js
│ └── rollup.config.prod.js
├── docs
├── gettingStarted.md
├── middlewares.md
└── routes.md
├── lib
├── helper.js
└── testHelpers.jsx
├── middlewares
├── APIResourcesRouter.js
├── APIRouter.js
├── BlankMiddleWare.js
├── Compressor.js
├── Logger.js
├── ServiceWorkers.js
├── StaticContentRouter.js
└── index.js
├── package-lock.json
├── package.json
├── router
├── Router.jsx
├── components
│ └── index.jsx
├── history
│ ├── HashHistoryAPI.jsx
│ ├── HistoryAPI.jsx
│ ├── MockHistoryAPI.jsx
│ ├── NodeHistoryAPI.jsx
│ ├── _HnRouteHistoryAPI.jsx
│ ├── events.js
│ └── index.js
├── index.js
└── server.js
├── tests
├── .eslintrc.json
├── libs
│ └── urlMatch.spec.jsx
├── middlewares
│ ├── api-resources-router.spec.jsx
│ ├── apirouter.spec.jsx
│ ├── custom-middleware.spec.jsx
│ ├── public
│ │ └── test.txt
│ └── staticcontent.spec.jsx
└── router
│ ├── history
│ ├── NodeHistoryAPI.spec.jsx
│ └── events.spec.jsx
│ └── router.spec.jsx
└── yarn.lock
/.babelrc:
--------------------------------------------------------------------------------
1 | {
2 | "env": {
3 | "test": {
4 | "plugins": [["istanbul", { "exclude": ["**/*.spec.jsx", "lib/*.jsx"] }]],
5 | "presets": [
6 | [
7 | "@babel/preset-env",
8 | {
9 | "targets": {
10 | "browsers": ["last 2 versions", "safari >= 7"],
11 | "node": "current"
12 | }
13 | }
14 | ],
15 | "@babel/preset-stage-0",
16 | "@babel/preset-flow",
17 | "@babel/preset-react"
18 | ]
19 | }
20 | },
21 | "presets": [
22 | [
23 | "@babel/preset-env",
24 | {
25 | "targets": {
26 | "browsers": ["last 2 versions", "safari >= 7"],
27 | "node": "current"
28 | },
29 | "modules": false,
30 | "useBuiltIns": false
31 | }
32 | ],
33 | "@babel/preset-stage-0",
34 | "@babel/preset-flow",
35 | "@babel/preset-react"
36 | ]
37 | }
38 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 |
3 | [*]
4 | end_of_line = lf
5 | insert_final_newline = true
6 | indent_style = space
7 |
--------------------------------------------------------------------------------
/.eslintignore:
--------------------------------------------------------------------------------
1 |
2 | # Created by https://www.gitignore.io/api/node
3 |
4 | ### Node ###
5 | # Logs
6 | logs
7 | *.log
8 | npm-debug.log*
9 | yarn-debug.log*
10 | yarn-error.log*
11 |
12 | # Runtime data
13 | pids
14 | *.pid
15 | *.seed
16 | *.pid.lock
17 |
18 | # Directory for instrumented libs generated by jscoverage/JSCover
19 | lib-cov
20 |
21 | # Coverage directory used by tools like istanbul
22 | coverage
23 |
24 | # nyc test coverage
25 | .nyc_output
26 |
27 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
28 | .grunt
29 |
30 | # Bower dependency directory (https://bower.io/)
31 | bower_components
32 |
33 | # node-waf configuration
34 | .lock-wscript
35 |
36 | # Compiled binary addons (http://nodejs.org/api/addons.html)
37 | build/Release
38 |
39 | # Dependency directories
40 | node_modules/
41 | jspm_packages/
42 |
43 | # Typescript v1 declaration files
44 | typings/
45 |
46 | # Optional npm cache directory
47 | .npm
48 |
49 | # Optional eslint cache
50 | .eslintcache
51 |
52 | # Optional REPL history
53 | .node_repl_history
54 |
55 | # Output of 'npm pack'
56 | *.tgz
57 |
58 | # Yarn Integrity file
59 | .yarn-integrity
60 |
61 | # dotenv environment variables file
62 | .env
63 |
64 | # End of https://www.gitignore.io/api/node
65 |
66 | *.map
67 | /flow-typed/npm
68 | /dist
69 |
--------------------------------------------------------------------------------
/.eslintrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | env: {
3 | browser: true,
4 | es6: true,
5 | },
6 | extends: [
7 | 'eslint:recommended',
8 | 'plugin:flowtype/recommended',
9 | 'plugin:lodash/recommended',
10 | 'plugin:react/recommended',
11 | 'plugin:import/recommended',
12 | 'prettier',
13 | ],
14 | parser: 'babel-eslint',
15 | parserOptions: {
16 | ecmaFeatures: {
17 | experimentalObjectRestSpread: true,
18 | experimentalDecorators: true,
19 | jsx: true,
20 | },
21 | ecmaVersion: 2016,
22 | sourceType: 'module',
23 | },
24 | plugins: ['prettier', 'import', 'react', 'lodash', 'flowtype'],
25 | rules: {
26 | 'prettier/prettier': ['error'],
27 | 'react/display-name': ['off'],
28 | },
29 | };
30 |
--------------------------------------------------------------------------------
/.flowconfig:
--------------------------------------------------------------------------------
1 | [ignore]
2 |
3 | [include]
4 |
5 | [libs]
6 |
7 | [lints]
8 |
9 | [options]
10 |
11 | [strict]
12 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | # Created by https://www.gitignore.io/api/node
3 |
4 | ### Node ###
5 | # Logs
6 | logs
7 | *.log
8 | npm-debug.log*
9 | yarn-debug.log*
10 | yarn-error.log*
11 |
12 | # Runtime data
13 | pids
14 | *.pid
15 | *.seed
16 | *.pid.lock
17 |
18 | # Directory for instrumented libs generated by jscoverage/JSCover
19 | lib-cov
20 |
21 | # Coverage directory used by tools like istanbul
22 | coverage
23 |
24 | # nyc test coverage
25 | .nyc_output
26 |
27 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
28 | .grunt
29 |
30 | # Bower dependency directory (https://bower.io/)
31 | bower_components
32 |
33 | # node-waf configuration
34 | .lock-wscript
35 |
36 | # Compiled binary addons (http://nodejs.org/api/addons.html)
37 | build/Release
38 |
39 | # Dependency directories
40 | node_modules/
41 | jspm_packages/
42 |
43 | # Typescript v1 declaration files
44 | typings/
45 |
46 | # Optional npm cache directory
47 | .npm
48 |
49 | # Optional eslint cache
50 | .eslintcache
51 |
52 | # Optional REPL history
53 | .node_repl_history
54 |
55 | # Output of 'npm pack'
56 | *.tgz
57 |
58 | # Yarn Integrity file
59 | .yarn-integrity
60 |
61 | # dotenv environment variables file
62 | .env
63 |
64 | # End of https://www.gitignore.io/api/node
65 |
66 | *.map
67 | /flow-typed/npm
68 | /dist
69 |
--------------------------------------------------------------------------------
/.prettierrc:
--------------------------------------------------------------------------------
1 | {
2 | "singleQuote": true,
3 | "trailingComma": "all"
4 | }
5 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: node_js
2 | node_js:
3 | - node
4 | - lts/*
5 | - lts/boron
6 | cache:
7 | yarn: true
8 |
--------------------------------------------------------------------------------
/.vscode/extensions.json:
--------------------------------------------------------------------------------
1 | {
2 | // See http://go.microsoft.com/fwlink/?LinkId=827846
3 | // for the documentation about the extensions.json format
4 | "recommendations": [
5 | // Extension identifier format: ${publisher}.${name}. Example: vscode.csharp
6 | "christian-kohler.npm-intellisense",
7 | "dbaeumer.vscode-eslint",
8 | "EditorConfig.editorconfig",
9 | "esbenp.prettier-vscode",
10 | "flowtype.flow-for-vscode",
11 | "gamunu.vscode-yarn"
12 | ]
13 | }
14 |
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "javascript.validate.enable": false,
3 | "flow.useNPMPackagedFlow": true,
4 | "[javascript]": {
5 | "editor.formatOnSave": true
6 | },
7 | "[json]": {
8 | "editor.formatOnSave": true
9 | },
10 | "[markdown]": {
11 | "editor.formatOnSave": true
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2016 Akshay Nair
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/MiddleWare.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import PropTypes from 'prop-types';
3 | import constant from 'lodash/constant';
4 | import isFunction from 'lodash/isFunction';
5 |
6 | // Super class for creating middlewares
7 | export class MiddleWare extends React.Component {
8 | isMiddleWare = true;
9 | isTerminalResponse = false;
10 |
11 | constructor(props) {
12 | super(props);
13 |
14 | if (isFunction(this.onRequest)) {
15 | const { props: { request, response } } = this;
16 | this.onRequest.call(this, request, response);
17 | } else {
18 | throw new Error('Middlewares need an onRequest method defined');
19 | }
20 | }
21 |
22 | terminate() {
23 | this.props.response.hasTerminated = true;
24 | this.isTerminalResponse = true;
25 | }
26 |
27 | render = constant(null);
28 | }
29 |
30 | MiddleWare.propTypes = {
31 | request: PropTypes.object.isRequired,
32 | response: PropTypes.object.isRequired,
33 | };
34 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # PlasmaJS
2 |
3 | [](https://travis-ci.org/phenax/plasmajs)
4 | [](https://www.npmjs.com/package/plasmajs)
5 | [](https://github.com/phenax/plasmajs/blob/master/LICENSE)
6 | [](https://david-dm.org/phenax/plasmajs)
7 | [](https://discord.gg/b9Z4b6r)
8 |
9 | [](https://www.npmjs.com/package/plasmajs)
10 |
11 | An isomorphic NodeJS framework powered with React for building web apps.
12 |
13 | **[Use the starter-kit to get up and running with PlasmaJS](https://github.com/phenax/plasmajs-starter-kit) [OUTDATED]**
14 |
15 | **[Join us on discord](https://discord.gg/b9Z4b6r)**
16 |
17 |
18 |
19 | [Getting Started](https://github.com/ManuelPortero/plasmajs/blob/ManuelPortero-patch-1/docs/gettingStarted.md)
20 |
21 |
22 |
23 | [Middlewares](https://github.com/ManuelPortero/plasmajs/blob/ManuelPortero-patch-1/docs/middlewares.md)
24 |
25 |
26 |
27 | [Routes](https://github.com/ManuelPortero/plasmajs/blob/ManuelPortero-patch-1/docs/routes.md)
28 |
29 |
30 |
31 | ## Features
32 |
33 | * Declarative syntax
34 | * Isomorphic routing
35 | * Isolated routing for API endpoints
36 | * Middlewares that are maintanable
37 | * ES6 syntax with babel
38 |
39 |
40 |
41 | ## Installation
42 |
43 | * Install with npm `npm i --save plasmajs`(you can also install it globally with `npm i -g plasmajs`)
44 | * To run the server, `plasmajs path/to/server.js`(Add it to your package.json scripts for local install)
45 |
46 |
47 |
48 | ## Guide
49 |
50 | ### Import it to your app.js
51 |
52 | ```javascript
53 | import { Server, Route, Router, NodeHistoryAPI } from 'plasmajs';
54 | ```
55 |
56 | ### Writing A Server
57 |
58 | ```javascript
59 | const HeadLayout = props => (
60 |
61 | {props.title}
62 |
63 | );
64 | const WrapperLayout = props => {props.children};
65 | const HomeLayout = props => Hello World
;
66 | const ErrorLayout = props => 404 Not Found
;
67 |
68 | export default class App extends React.Component {
69 | // Port number (Default=8080)
70 | static port = 8080;
71 |
72 | render() {
73 | const history = new NodeHistoryAPI(this.props.request, this.props.response);
74 | return (
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 | );
83 | }
84 | }
85 | ```
86 |
87 |
88 |
89 | ### Middlewares
90 |
91 | #### Writing custom Middlewares
92 |
93 | In MyMiddleWare.jsx...
94 |
95 | ```javascript
96 | import { MiddleWare } from 'plasmajs';
97 |
98 | export default class MyMiddleWare extends MiddleWare {
99 | onRequest(req, res) {
100 | // Do your magic here
101 | // Run this.terminate() to stop the render and take over
102 | }
103 | }
104 | ```
105 |
106 | And in App's render method...
107 |
108 | ```html
109 |
110 |
111 |
112 |
113 | // ...
114 |
115 | ```
116 |
117 |
118 |
119 | #### Logger Middleware
120 |
121 | It logs information about the request made to the server out to the console.
122 |
123 | ````javascript
124 | import {Logger} from 'plasmajs' // and add it in the server but after the router declaration.
125 | ````
126 | ```html
127 |
128 | // ...
129 |
130 |
131 |
132 | ```
133 |
134 | * Props
135 | * `color` (boolean) - Adds color to the logs if true
136 |
137 |
138 |
139 | #### StaticContentRouter Middleware
140 |
141 | Allows you to host a static content directory for public files
142 |
143 | ````javascript
144 | import {StaticContentRouter} from 'plasmajs'
145 | ````
146 | ```html
147 |
148 |
149 |
150 | // ...
151 |
152 | ```
153 |
154 | * Props
155 | * `dir` (string) - The name of the static content folder to host
156 | * `hasPrefix` (boolean) - If set to false, will route it as http://example.com/file instead of http://example.com/public/file
157 | * `compress` (boolean) - If true, will enable gzip compression on all static content if the client supports it
158 |
159 |
160 |
161 | #### APIRoute Middleware
162 |
163 | Allows you to declare isolated routes for requests to api hooks
164 |
165 | ```javascript
166 | import {APIRoute} from 'plasmajs'
167 |
168 | //...
169 | // API request handler for api routes
170 | _apiRequestHandler() {
171 |
172 | // Return a promise
173 | return new Promise((resolve, reject) => {
174 |
175 | resolve({
176 | wow: "cool cool"
177 | });
178 | });
179 | }
180 |
181 | render() {
182 | return (
183 |
184 |
185 | //...
186 |
187 | );
188 | }
189 | ```
190 |
191 | * Props
192 | * `method` (string) - The http request method
193 | * `path` (string or regex) - The path to match
194 | * `controller` (function) - The request handler
195 |
196 |
197 |
198 | ### Routing
199 |
200 | Isomorphic routing which renders the content on the server-side and then lets the javascript kick in and take over the interactions. (The server side rendering only works for Push State routing on the client side, not Hash routing).
201 |
202 | `NOTE: Its better to isolate the route definitions to its own file so that the client-side and the server-side can share the components`
203 |
204 | #### History API
205 |
206 | There are 3 types of routing available - Backend routing(`new NodeHistoryAPI(request, response)`), Push State routing(`new HistoryAPI(options)`), Hash routing(`new HashHistoryAPI(options)`)(NOTE: The naming is just for consistency)
207 |
208 |
209 |
210 | #### The Router
211 |
212 | ```html
213 |
214 | {allRouteDeclarations}
215 |
216 | ```
217 |
218 | * Props
219 | * `history` (object) - It's the history api instance you pass in depending on the kind of routing you require.
220 | * `wrapper` (React component class) - It is a wrapper for the routed contents
221 |
222 |
223 |
224 | #### Declaring a route
225 |
226 | If `Homepage` is a react component class and `/` is the url.
227 |
228 | ```html
229 |
230 | ```
231 |
232 | * Props
233 | * `path` (string or regex) - The url to route the request to
234 | * `component` (React component class) - The component to be rendered when the route is triggered
235 | * `statusCode` (integer) - The status code for the response
236 | * `caseInsensitive` (boolean) - Set to true if you want the url to be case insensitive
237 | * `errorHandler` (boolean) - Set to true to define a 404 error handler
238 |
239 |
240 | ## Want to help?
241 | PRs are welcome. You can also join us on [discord](https://discord.gg/b9Z4b6r) for discussions about plasmajs.
242 |
--------------------------------------------------------------------------------
/TODO.md:
--------------------------------------------------------------------------------
1 | # To Do
2 |
3 | These are good things to work on if you wish to help out the project
4 |
5 | ## General
6 | ### Testing
7 |
8 | When you go to finalize your commits, please update the number to the next one in this list.
9 |
10 | [ ] Bring code coverage to over 95%
11 | [ ] Bring code coverage to over 75%
12 | [x] Statements
13 | [ ] Branches
14 | [x] Functions
15 | [x] Lines
16 | [ ] Bring code coverage to over 80%
17 | [ ] Statements
18 | [ ] Branches
19 | [ ] Functions
20 | [ ] Lines
21 | [ ] Bring code coverage to over 85%
22 | [ ] Bring code coverage to over 90%
23 |
24 | ### Code quality
25 |
26 | Ensure all existing tests pass and that you don't decrease the code coverage below the current threshold.
27 |
28 | [ ] Check the code for more modernization opportunities
29 | [ ] Enhance the code's FP style
30 | [ ] Reduce mutation of objects
31 |
--------------------------------------------------------------------------------
/app.js:
--------------------------------------------------------------------------------
1 | import { createElement, Component } from 'react';
2 | import http from 'http';
3 | import https from 'https';
4 | import mime from 'mime';
5 | import fs from 'fs';
6 | import { createGzip, createDeflate } from 'zlib';
7 |
8 | import { renderTemplate } from './lib/helper.jsx';
9 |
10 | export * from './router/server';
11 | export * from './MiddleWare';
12 | export * from './middlewares';
13 |
14 | // Wrapping element for the configuration
15 | export class Server extends Component {
16 | render() {
17 | // All middlewares that have called the .terminate()
18 | const $terminalComponents = this.props.children.filter(
19 | val => val.isTerminalResponse,
20 | );
21 |
22 | // If atleast one middleware has called the .terminate, return null;
23 | if ($terminalComponents.length > 0) {
24 | return null;
25 | }
26 |
27 | // Else wrap the childern in an html element and render
28 | return createElement('html', this.props.html || {}, this.props.children);
29 | }
30 | }
31 |
32 | // Http(s) server wrapper
33 | export class NodeServer {
34 | constructor(App) {
35 | this._App = App;
36 | this.port = this._App.port || process.env.PORT || 8080;
37 | this.config =
38 | this._App.config && this._App.config.https ? this._App.config : null;
39 |
40 | this._requestHandler = this._requestHandler.bind(this);
41 | }
42 |
43 | // Create a new server
44 | createServer(reqCB = () => {}) {
45 | // If the config is not null, create an https server
46 | // Else, create a http server
47 | if (this.config) {
48 | // HTTPS server
49 |
50 | this.server = https.createServer(this.config, (req, res) =>
51 | this._requestHandler(req, res, reqCB),
52 | );
53 | } else {
54 | // HTTP server
55 |
56 | this.server = http.createServer((req, res) =>
57 | this._requestHandler(req, res, reqCB),
58 | );
59 | }
60 |
61 | return this;
62 | }
63 |
64 | // Start the server
65 | start() {
66 | return new Promise((resolve, reject) => {
67 | this.server.listen(this.port, _ => {
68 | console.log(`Listening on port ${this.port}...`);
69 |
70 | resolve(_);
71 | });
72 | });
73 | }
74 |
75 | // Extend the response with additional functionality
76 | _wrapResponse(req, res) {
77 | return Object.assign(res, {
78 | respondWith(str, type) {
79 | res.writeHead(200, { 'Content-Type': type });
80 | res.end(str);
81 | },
82 |
83 | // For plain-text responses
84 | text(str) {
85 | res.respondWith(str, mime.lookup('a.txt'));
86 | },
87 |
88 | // For html resonses
89 | send(str) {
90 | res.respondWith(str, mime.lookup('a.html'));
91 | },
92 |
93 | // For json responses
94 | json(obj) {
95 | res.respondWith(JSON.stringify(obj), mime.lookup('a.json'));
96 | },
97 |
98 | // XML response
99 | xml() {
100 | // TODO: Fix the mime-type
101 | res.respondWith(str, mime.lookup('a.xml'));
102 | },
103 |
104 | compressStream(stream$, getCompressionType) {
105 | const compressionType = getCompressionType();
106 |
107 | // If compression is supported
108 | if (compressionType) {
109 | res.writeHead(200, { 'Content-Encoding': compressionType });
110 |
111 | const outer$ =
112 | compressionType === 'gzip' ? createGzip() : createDeflate();
113 |
114 | return stream$.pipe(outer$);
115 | }
116 |
117 | return stream$;
118 | },
119 |
120 | // For sending files
121 | sendFile(fileName, config = {}) {
122 | return new Promise((resolve, reject) => {
123 | // If the file wasnt found, stop here and let the router handler stuff
124 | let fileStream$ = fs.createReadStream(fileName);
125 |
126 | // Set the mime-type of the file requested
127 | res.statusCode = 200;
128 | res.setHeader('Content-Type', mime.lookup(fileName) || 'text/plain');
129 |
130 | // The file was found
131 | resolve();
132 |
133 | // If it needs compression, compress it
134 | if (config.compress) {
135 | fileStream$ = res.compressStream(fileStream$, config.compress);
136 | }
137 |
138 | // pipe the file out to the response
139 | fileStream$.pipe(res);
140 | });
141 | },
142 | });
143 | }
144 |
145 | // Request callback
146 | _requestHandler(req, res, reqCallback) {
147 | const response = this._wrapResponse(req, res);
148 |
149 | reqCallback(req, response);
150 |
151 | process.nextTick(_ => {
152 | const PAGE_RENDERING_TIMER = 'Page rendered';
153 |
154 | console.time(PAGE_RENDERING_TIMER);
155 |
156 | // Render the template
157 | const markup = renderTemplate(this._App, {
158 | request: req,
159 | response: response,
160 | port: this.port,
161 | });
162 |
163 | if (!response.hasTerminated && markup) {
164 | response.send(markup);
165 | console.timeEnd(PAGE_RENDERING_TIMER);
166 | }
167 | });
168 | }
169 | }
170 |
171 | export default {
172 | NodeServer,
173 | Server,
174 | };
175 |
--------------------------------------------------------------------------------
/bin/run:
--------------------------------------------------------------------------------
1 | #! /usr/bin/env node
2 |
3 |
4 | const path = require('path');
5 | // const defConf= {
6 | // presets: [ 'es2015', 'react' ],
7 | // plugins: [ 'transform-object-rest-spread' ]
8 | // };
9 |
10 | require('@babel/register')({
11 |
12 | ignore: (name) => {
13 |
14 | if (name.includes('node_modules/plasmajs')) {
15 | return false;
16 | }
17 |
18 | if (name.includes('node_modules')) {
19 | return true;
20 | }
21 |
22 | return false;
23 | }
24 | });
25 |
26 |
27 | //
28 | // TODO: Add more command-line arguments for more configurations
29 | //
30 | if (process.argv.length < 3) {
31 | console.log('Usage: plasmajs ./your-server.js');
32 | process.exit(0);
33 | }
34 |
35 | const fileName = process.argv[2];
36 |
37 | let App;
38 |
39 | try {
40 |
41 | App = require(path.resolve(fileName)).default;
42 |
43 | if (!App) {
44 | throw new Error("You need to export a React component class");
45 | }
46 |
47 | } catch (e) {
48 |
49 | console.error("ERROR:", e);
50 |
51 | process.exit(1);
52 | }
53 |
54 |
55 | // NodeServer class
56 | const NodeServer = App.NodeServer || require('./app').NodeServer;
57 |
58 | // Creates and starts a new server instance
59 | function startNewServer() {
60 |
61 | const plasmaJSServer = new NodeServer(App);
62 |
63 | return plasmaJSServer.createServer().start();
64 | }
65 |
66 |
67 | // If the user has enabled cluster in the app
68 | if (App.cluster && typeof App.cluster === 'object') {
69 |
70 | const cluster = require('cluster');
71 |
72 | if (cluster.isMaster) {
73 |
74 | for (let i = 0; i < App.cluster.count; i++) {
75 | cluster.fork();
76 | }
77 |
78 | if (typeof App.cluster.master === 'function') {
79 | App.cluster.master();
80 | }
81 |
82 | cluster.on('exit', () => {
83 | cluster.fork();
84 | });
85 |
86 | } else {
87 |
88 | startNewServer();
89 |
90 | if (typeof App.cluster.notMaster === 'function') {
91 | App.cluster.notMaster();
92 | }
93 | }
94 |
95 | } else {
96 | startNewServer();
97 | }
98 |
99 |
100 |
--------------------------------------------------------------------------------
/client/index.jsx:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/config/.eslintrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | env: {
3 | node: true,
4 | },
5 | };
6 |
--------------------------------------------------------------------------------
/config/rollup/rollup.config.common.js:
--------------------------------------------------------------------------------
1 | import resolveNode from 'rollup-plugin-node-resolve';
2 | import commonjs from 'rollup-plugin-commonjs';
3 | import babel from 'rollup-plugin-babel';
4 | import json from 'rollup-plugin-json';
5 | import builtins from 'rollup-plugin-node-builtins';
6 | // import globals from 'rollup-plugin-node-globals';
7 | import { dirname, join } from 'path';
8 |
9 | export function fromRootPath(...parts) {
10 | return join(dirname(__dirname), '..', ...parts);
11 | }
12 |
13 | export default {
14 | input: fromRootPath('app.jsx'),
15 | output: {
16 | file: 'plasma.js',
17 | dir: fromRootPath('dist'),
18 | format: 'iife',
19 | name: 'Plasma',
20 | },
21 | plugins: [
22 | resolveNode({ extensions: ['.js', '.json', '.jsx'], preferBuiltins: true }),
23 | json(),
24 | babel({
25 | exclude: 'node_modules/**', // only transpile our source code
26 | }),
27 | commonjs({
28 | namedExports: {
29 | 'node_modules/react-dom/server.js': ['renderToStaticMarkup'],
30 | 'node_modules/react/index.js': [
31 | // based on https://github.com/facebook/flow/blob/master/lib/react.js
32 | 'checkPropTypes',
33 | 'createFactory',
34 | 'initializeTouchEvents',
35 | 'isValidElement',
36 | 'Children',
37 | 'cloneElement',
38 | 'Component',
39 | 'createClass',
40 | 'createElement',
41 | 'DOM',
42 | 'Fragment',
43 | 'PropTypes',
44 | 'PureComponent',
45 | ],
46 | },
47 | }),
48 | // globals(),
49 | builtins(),
50 | ],
51 | // externals: ['lodash'],
52 | };
53 |
--------------------------------------------------------------------------------
/config/rollup/rollup.config.dev.js:
--------------------------------------------------------------------------------
1 | import commonConfig from './rollup.config.common';
2 |
3 | export default {
4 | ...commonConfig,
5 | output: {
6 | ...commonConfig.output,
7 | file: 'dist/plasma.js',
8 | },
9 | };
10 |
--------------------------------------------------------------------------------
/config/rollup/rollup.config.prod.js:
--------------------------------------------------------------------------------
1 | import commonConfig from './rollup.config.common';
2 | import uglify from 'rollup-plugin-uglify';
3 |
4 | export default {
5 | ...commonConfig,
6 | output: {
7 | ...commonConfig.output,
8 | file: 'dist/plasma.min.js',
9 | },
10 | plugins: [
11 | ...commonConfig.plugins,
12 | uglify({
13 | output: {
14 | comments(node, comment) {
15 | const { value: text, type } = comment;
16 | if (type === 'comment2') {
17 | // multiline comment
18 | return /@preserve|@license|@cc_on/i.test(text);
19 | }
20 | },
21 | },
22 | }),
23 | ],
24 | };
25 |
--------------------------------------------------------------------------------
/docs/gettingStarted.md:
--------------------------------------------------------------------------------
1 | # Getting Started with PlasmaJs:
2 |
3 | ## PlasmaJs is an isomorphic NodeJS framework powered with React for building web apps.
4 |
5 |
6 | ### 1) Features of PlasmaJs:
7 |
8 | - Declarative syntax
9 | - Isomorphic routing
10 | - Isolated routing for API endpoints
11 | - Maintainable middlewares
12 | - ES6 syntax with babel
13 |
14 |
15 | ### 2) How to install PlasmaJs:
16 |
17 | - Install with:
18 |
19 | npm npm i --save plasmajs (you can also install it globally with npm i -g plasmajs)
20 |
21 | - To run the server, plasmajs path/to/server.js (Add it to your package.json scripts for local install)
22 |
23 | ### 3) Plasma Js guide of use
24 |
25 | - Import PlasmaJs to your app.js
26 | ```javaScript
27 | import { Server, Route, Router, NodeHistoryAPI } from 'plasmajs';
28 | ```
29 | - Writing A Server
30 | ```javaScript
31 | const HeadLayout = props => (
32 |
33 | {props.title}
34 |
35 | );
36 | const WrapperLayout = props => {props.children};
37 | const HomeLayout = props => Hello World
;
38 | const ErrorLayout = props => 404 Not Found
;
39 |
40 | export default class App extends React.Component {
41 | // Port number (Default=8080)
42 | static port = 8080;
43 |
44 | render() {
45 | const history = new NodeHistoryAPI(this.props.request, this.props.response);
46 | return (
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 | );
55 | }
56 | }
57 | ```
58 |
--------------------------------------------------------------------------------
/docs/middlewares.md:
--------------------------------------------------------------------------------
1 | ## Middlewares
2 |
3 | ### How to Write custom middlewares
4 |
5 | You need to access to my MyMiddleWare.jsx and introduce this code:
6 | ```javaScript
7 | import { MiddleWare } from 'plasmajs';
8 |
9 | export default class MyMiddleWare extends MiddleWare {
10 | onRequest(req, res) {
11 | // Do your magic here
12 | // Run this.terminate() to stop the render and take over
13 | }
14 | }
15 | ```
16 | And in App's render method...
17 | ```javaScript
18 |
19 |
20 |
21 |
22 | // ...
23 |
24 | ```
25 | ### How to create a logger middleware:
26 |
27 | #### It logs information about the request made to the server out to the console.
28 | ```javaScript
29 | import {Logger} from 'plasmajs' // and add it in the server but after the router declaration.
30 |
31 |
32 |
33 |
34 | ```
35 | - Props
36 |
37 | - color (boolean) - Adds color to the logs if true
38 |
39 | ### StaticContentRouter middleware:
40 |
41 | #### Allows you to host a static content directory for public files
42 | ```javaScript
43 | import {StaticContentRouter} from 'plasmajs'
44 |
45 |
46 |
47 | // ...
48 |
49 | ```
50 | - Props
51 |
52 | - dir (string) - The name of the static content folder to host
53 |
54 | - hasPrefix (boolean) - If set to false, will route it as http://example.com/file instead of http://example.com/public/file
55 |
56 | - compress (boolean) - If true, will enable gzip compression on all static content if the client supports it
57 |
58 | ### How to create an APIRoute middleware
59 |
60 | #### Allows you to declare isolated routes for requests to api hooks
61 | ```javaScript
62 | import {APIRoute} from 'plasmajs'
63 |
64 | //...
65 | // API request handler for api routes
66 | _apiRequestHandler() {
67 |
68 | // Return a promise
69 | return new Promise((resolve, reject) => {
70 |
71 | resolve({
72 | wow: "cool cool"
73 | });
74 | });
75 | }
76 |
77 | render() {
78 | return (
79 |
80 |
81 | //...
82 |
83 | );
84 | }
85 | ```
86 | - Props:
87 |
88 | - method (string) - The http request method
89 |
90 | - path (string or regex) - The path to match
91 |
92 | - controller (function) - The request handler
93 |
94 |
--------------------------------------------------------------------------------
/docs/routes.md:
--------------------------------------------------------------------------------
1 | ## Routing on PlasmaJs:
2 |
3 | Isomorphic routing which renders the content on the server-side and then lets the javascript kick in and take over the interactions. (The server side rendering only works for Push State routing on the client side, not Hash routing).
4 |
5 | ##### NOTE: Its better to isolate the route definitions to its own file so that the client-side and the server-side can share the components
6 |
7 | ### History API:
8 |
9 | There are 3 types of routing available:
10 |
11 | - Backend routing(new NodeHistoryAPI(request, response))
12 | - Push State routing(new HistoryAPI(options))
13 | - Hash routing(new HashHistoryAPI(options)) (NOTE: The naming is just for consistency)
14 |
15 |
16 | ### The Router:
17 | ```javaScript
18 |
19 | {allRouteDeclarations}
20 |
21 | ```
22 | Props:
23 |
24 | - history (object) - It's the history api instance you pass in depending on the kind of routing you require.
25 |
26 | - wrapper (React component class) - It is a wrapper for the routed contents
27 |
28 | ### How to declare a route:
29 |
30 | If Homepage is a react component class and / is the url.
31 |
32 | ```javaScript
33 |
34 | ```
35 | Props:
36 |
37 | - path (string or regex) - The url to route the request to
38 |
39 | - component (React component class) - The component to be rendered when the route is triggered
40 |
41 | - statusCode (integer) - The status code for the response
42 |
43 | - caseInsensitive (boolean) - Set to true if you want the url to be case insensitive
44 |
45 | - errorHandler (boolean) - Set to true to define a 404 error handler
46 |
--------------------------------------------------------------------------------
/lib/helper.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 |
3 | import compact from 'lodash/compact';
4 | import isFunction from 'lodash/isFunction';
5 | import isNil from 'lodash/isNil';
6 | import isString from 'lodash/isString';
7 | import join from 'lodash/join';
8 | import split from 'lodash/split';
9 | import toLower from 'lodash/toLower';
10 |
11 | import { renderToStaticMarkup } from 'react-dom/server';
12 |
13 | export function renderComponent(Element, props = {}) {
14 | return renderToStaticMarkup();
15 | }
16 |
17 | // Render react components(only server-side)
18 | export function renderTemplate(Element, props) {
19 | const renderedContent = renderComponent(Element, props);
20 |
21 | if (isNil(renderedContent)) return null;
22 |
23 | return `${renderedContent}`;
24 | }
25 |
26 | // Route matching
27 | export function checkUrlMatch(url, reqUrl, method1 = 'GET', method2 = 'GET') {
28 | let isAMatch = false;
29 |
30 | if (isFunction(url.test)) {
31 | isAMatch = url.test(reqUrl);
32 | } else if (isString(url)) {
33 | isAMatch = toUrlToken(url) === toUrlToken(reqUrl);
34 | }
35 |
36 | // Does the method name match?
37 | if (isAMatch && toLower(method1) !== toLower(method2)) return false;
38 | return isAMatch;
39 | }
40 |
41 | export const trimAndReplaceChar = (str, char, replacementChar) =>
42 | join(compact(split(str, char)), replacementChar);
43 | export const toUrlToken = url =>
44 | trimAndReplaceChar(trimAndReplaceChar(url, '/', '.'), ' ', '-');
45 |
--------------------------------------------------------------------------------
/lib/testHelpers.jsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import PropTypes from 'prop-types';
3 | import constant from 'lodash/constant';
4 | import noop from 'lodash/noop';
5 |
6 | import { Router, Route } from '../router/server';
7 | import { MockHistoryAPI } from '../router/history/MockHistoryAPI.jsx';
8 | import { action } from '../middlewares/APIResourcesRouter';
9 |
10 | // Dummy components
11 | export const Wrapper = ({ children, name }) => (
12 |
13 | {children}
14 | {name}
15 |
16 | );
17 | Wrapper.propTypes = {
18 | children: PropTypes.node.isRequired,
19 | name: PropTypes.string.isRequired,
20 | };
21 |
22 | export const Index = () => Index
;
23 | export const About = () => About
;
24 | export const Error404 = () => Error
;
25 |
26 | export const CtrlrPage = () => constant(null);
27 |
28 | // Mock router component creator
29 | export const getRouter = (url, ctrlr = noop) => () => (
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 | );
39 |
40 | // Expected rendered strings for each routes
41 | export const indexString = '';
42 | export const aboutString = '';
43 | export const errorString = '';
44 |
45 | // Controller output depends on the name passed in so...
46 | export const getCtrlrString = name => `${name}
`;
47 |
48 | export const createController = (obj = {}) =>
49 | class _Controller {
50 | @action(['get', 'post'], '/')
51 | index(...props) {
52 | obj.index && obj.index(...props);
53 | }
54 |
55 | @action('post', '/add')
56 | add(...props) {
57 | obj.add && obj.add(...props);
58 | }
59 | };
60 |
61 | // Mock context object creator for the http request and response objects
62 | export const mockCtx = (url, requestStuff) => {
63 | const calledFn = null;
64 | const calledTarget = null;
65 | const calledWith = null;
66 | const ctx = {
67 | calledFn,
68 | calledTarget,
69 | calledWith,
70 |
71 | request: { url, ...requestStuff },
72 |
73 | response: new Proxy(
74 | {},
75 | {
76 | get: (target, field) => {
77 | ctx.calledTarget = target;
78 |
79 | ctx.calledFn = `response.${field}`;
80 |
81 | return data => {
82 | ctx.calledWith = data;
83 | return Promise.resolve();
84 | };
85 | },
86 | },
87 | ),
88 | };
89 |
90 | return ctx;
91 | };
92 |
--------------------------------------------------------------------------------
/middlewares/APIResourcesRouter.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import PropTypes from 'prop-types';
3 |
4 | import assign from 'lodash/assign';
5 | import concat from 'lodash/concat';
6 | import constant from 'lodash/constant';
7 | import filter from 'lodash/filter';
8 | import isArray from 'lodash/isArray';
9 | import isFunction from 'lodash/isFunction';
10 | import isString from 'lodash/isString';
11 | import map from 'lodash/map';
12 | import toLower from 'lodash/toLower';
13 |
14 | import { MiddleWare } from '../MiddleWare';
15 |
16 | import { checkUrlMatch } from '../lib/helper';
17 |
18 | /**
19 | * Api resources structure
20 | *
21 | *
22 | */
23 | export class Resource extends MiddleWare {
24 | toUrl(path) {
25 | return `/${this.props.name}${path}`;
26 | }
27 |
28 | onRequest() {
29 | this._controller = {};
30 | this._actions = [];
31 |
32 | const Ctrlr = this.props.controller;
33 |
34 | this._actions = map(this.props.children || [], child => {
35 | const { props: { path, method, handler } } = child;
36 | const action = {
37 | url: this.toUrl(path),
38 | methods: [toLower(method)],
39 | handler,
40 | };
41 |
42 | if (isString(action.handler)) {
43 | return { ...action, handler: Ctrlr[action.handler] };
44 | }
45 |
46 | return action;
47 | });
48 |
49 | if (isFunction(Ctrlr)) {
50 | this._controller = new Ctrlr();
51 |
52 | this._actions = concat(
53 | this._actions,
54 | map(
55 | filter(
56 | filter(
57 | map(
58 | Object.getOwnPropertyNames(Ctrlr.prototype),
59 | key => this._controller[key],
60 | ),
61 | action => isFunction(action),
62 | ),
63 | 'isAction',
64 | ),
65 | action => {
66 | return {
67 | url: this.toUrl(action.actionName),
68 | methods: action.actionMethods,
69 | handler: action,
70 | };
71 | },
72 | ),
73 | );
74 | }
75 |
76 | this._executeMatchingAction();
77 | }
78 |
79 | _executeMatchingAction() {
80 | for (let i = 0; i < this._actions.length; i++) {
81 | const action = this._actions[i];
82 |
83 | for (let j = 0; j < action.methods.length; j++) {
84 | const isAMatch = checkUrlMatch(
85 | action.url,
86 | this.props.request.url,
87 | this.props.request.method,
88 | action.methods[j],
89 | );
90 |
91 | if (isAMatch) {
92 | this.terminate();
93 |
94 | this.props.response.statusCode = 200;
95 |
96 | const promise = action.handler(
97 | this.props.request,
98 | this.props.response,
99 | );
100 |
101 | if (promise instanceof Promise) {
102 | promise.then(this.emitResponse).catch(this.emitError);
103 | }
104 | return;
105 | }
106 | }
107 | }
108 | }
109 |
110 | emitResponse(data = {}) {
111 | this.props.response.json(data);
112 | }
113 |
114 | emitError(e = {}) {
115 | this.props.response.statusCode = e.statusCode || 500;
116 | this.props.response.json(e);
117 | }
118 | }
119 |
120 | export class Action extends React.Component {
121 | static propTypes = {
122 | path: PropTypes.string.isRequired,
123 | method: PropTypes.string,
124 | handler: PropTypes.oneOf([
125 | PropTypes.string,
126 | PropTypes.function,
127 | PropTypes.object,
128 | ]).isRequired,
129 | // handler: React.PropTypes.object, string or function
130 | };
131 |
132 | render = constant(null);
133 | }
134 |
135 | /**
136 | *
137 | */
138 | export const action = (method = null, path = null) => (_, __, fnMeta) => {
139 | assign(fnMeta.value, {
140 | isAction: true,
141 | actionName: path !== null ? path : '/' + fnMeta.value.name,
142 | actionMethods: map(isArray(method) ? method : [method || 'get'], m =>
143 | toLower(m),
144 | ),
145 | });
146 | };
147 |
--------------------------------------------------------------------------------
/middlewares/APIRouter.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import PropTypes from 'prop-types';
3 |
4 | import { MiddleWare } from '../MiddleWare';
5 |
6 | import { checkUrlMatch } from '../lib/helper';
7 |
8 | export class APIRoute extends MiddleWare {
9 | onRequest() {
10 | this.emitError = this.emitError.bind(this);
11 | this.emitResponse = this.emitResponse.bind(this);
12 |
13 | if (
14 | checkUrlMatch(
15 | this.props.path,
16 | this.props.request.url,
17 | this.props.request.method,
18 | this.props.method,
19 | )
20 | ) {
21 | this.triggerAPIResponse();
22 | }
23 | }
24 |
25 | emitError(e = {}) {
26 | this.hasResponded = true;
27 |
28 | this.props.response.statusCode = e.statusCode || 500;
29 |
30 | this.props.response.json(e);
31 | }
32 |
33 | emitResponse(data = {}) {
34 | this.hasResponded = true;
35 |
36 | this.props.response.json(data);
37 | }
38 |
39 | triggerAPIResponse() {
40 | this.terminate();
41 |
42 | this.props.response.statusCode = 200;
43 |
44 | if (this.props.controller) {
45 | this.hasResponded = false;
46 |
47 | const promise = this.props.controller(this.emitResponse, this.emitError);
48 |
49 | if (!this.hasResponded && promise)
50 | promise.then(this.emitResponse).catch(this.emitError);
51 | } else {
52 | this.emitError({
53 | error: 'You need to specify the controller for the APIRoute',
54 | });
55 | }
56 | }
57 | }
58 |
59 | APIRoute.propTypes = {
60 | controller: PropTypes.func.isRequired,
61 | };
62 |
--------------------------------------------------------------------------------
/middlewares/BlankMiddleWare.js:
--------------------------------------------------------------------------------
1 | import { MiddleWare } from '../MiddleWare';
2 |
3 | export class BlankMiddleWare extends MiddleWare {
4 | onRequest(req, res) {
5 | if (typeof this.props.handler === 'function') this.props.handler(req, res);
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/middlewares/Compressor.js:
--------------------------------------------------------------------------------
1 | import { MiddleWare } from '../MiddleWare';
2 |
3 | import fs from 'fs';
4 |
5 | import { createGzip, createDeflate } from 'zlib';
6 |
7 | // Compressor middleware
8 | export class Compressor extends MiddleWare {
9 | onRequest(req, res) {
10 | // let compressionType= null;
11 | // const acceptEncoding = req.headers['accept-encoding'] || '';
12 | // if (acceptEncoding.includes('gzip'))
13 | // compressionType= 'gzip';
14 | // else if (acceptEncoding.includes('deflate'))
15 | // compressionType= 'deflate';
16 | // if(compressionType) {
17 | // // res.writeHead(200, { 'Content-Encoding': compressionType });
18 | // const outer= (compressionType === 'gzip')? createGzip(): createDeflate();
19 | // res.pipe(outer)//.pipe(outStrem);
20 | // }
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/middlewares/Logger.js:
--------------------------------------------------------------------------------
1 | import { MiddleWare } from '../MiddleWare';
2 |
3 | // Logger middleware
4 | export class Logger extends MiddleWare {
5 | // All middlewares must implement the onRequest method
6 | onRequest(req, res) {
7 | // Color codes
8 | const AQUA = '\x1b[36m';
9 | const DEFAULT = '\x1b[0m';
10 | const DIM = '\x1b[2m';
11 | const RED = '\x1b[31m';
12 |
13 | const statusGroup = Math.floor(res.statusCode / 100);
14 | const statusColor = statusGroup != 2 && statusGroup != 3 ? RED : AQUA;
15 |
16 | // if(this.props.time)
17 | // console.timeEnd(res.benchmarkNameSpace);
18 |
19 | if (this.props.color)
20 | console.log(
21 | statusColor,
22 | `[${res.statusCode}]`,
23 | DEFAULT,
24 | DIM,
25 | `${req.method}`,
26 | DEFAULT,
27 | `${req.url}`,
28 | );
29 | else console.log(`[${res.statusCode}] ${req.method} ${req.url}`);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/middlewares/ServiceWorkers.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import PropTypes from 'prop-types';
3 |
4 | import { MiddleWare } from '../MiddleWare';
5 |
6 | import { checkUrlMatch } from '../lib/helper';
7 |
8 | export class ServiceWorker extends MiddleWare {
9 | onRequest() {}
10 |
11 | constructor(props) {
12 | super(props);
13 |
14 | this.successScript =
15 | this.props.success ||
16 | (() => console.log('Service Worker was registered successfully'));
17 | this.errorScript =
18 | this.props.error ||
19 | (e => console.warn('Service worker registration failed ', e));
20 | this.swPathName = this.props.path || '/serviceWorker.js';
21 | }
22 |
23 | serviceWorkerRequestHandler() {
24 | if (checkUrlMatch(this.props.request.url, this.swPathName)) {
25 | this.terminate();
26 |
27 | const serviceWorkerScript = '';
28 |
29 | this.props.response.respondWith(
30 | serviceWorkerScript,
31 | 'application/javascript',
32 | );
33 | }
34 | }
35 |
36 | serviceWorkerRegScript() {
37 | return `
38 | if ('serviceWorker' in navigator) {
39 | navigator.serviceWorker.register('${this.swPathName}')
40 | .then(${this.successScript.toString()})
41 | .catch(${this.errorScript.toString()});
42 | }
43 | `.replace(/\s+/gi, ' ');
44 | }
45 |
46 | render() {
47 | this.serviceWorkerRequestHandler();
48 |
49 | return (
50 |
55 | );
56 | }
57 | }
58 |
59 | ServiceWorker.propTypes = {
60 | path: PropTypes.string,
61 | success: PropTypes.func,
62 | error: PropTypes.func,
63 | };
64 |
65 | export class SWToolboxFast extends React.Component {}
66 |
--------------------------------------------------------------------------------
/middlewares/StaticContentRouter.js:
--------------------------------------------------------------------------------
1 | /* eslint-disable no-console */
2 | import PropTypes from 'prop-types';
3 | import fs from 'fs';
4 | import path from 'path';
5 |
6 | import includes from 'lodash/includes';
7 |
8 | import { MiddleWare } from '../MiddleWare';
9 |
10 | /**
11 | * Middleware to host static content on the server
12 | */
13 | export class StaticContentRouter extends MiddleWare {
14 | static propTypes = {
15 | dir: PropTypes.string.isRequired,
16 | hasPrefix: PropTypes.bool,
17 | compress: PropTypes.bool,
18 | };
19 |
20 | /* eslint-disable no-unused-vars */
21 | onRequest(req, res) {
22 | // Defaults to a directory called static in the project root
23 | this.publicDir = this.props.dir || 'static';
24 |
25 | // Defaults to true because its faster
26 | this.hasPrefix = this.props.hasPrefix == null ? true : this.props.hasPrefix;
27 |
28 | // If the directory name if to be prefixed i.e.
29 | // ./public will be hosted as http://domain.com/public/file
30 | // instead of
31 | // http://domain.com/file
32 | if (this.hasPrefix) {
33 | const publicPathRegex = new RegExp(`^/${this.publicDir}/`);
34 | // If the url starts with /${publicDir}/
35 | if (publicPathRegex.test(req.url)) {
36 | this.sendFileContents();
37 | }
38 | } else {
39 | this.sendFileContents();
40 | }
41 | }
42 | /* eslint-enable no-unused-vars */
43 |
44 | getFileAbsolutePath(currentUrl) {
45 | // The base directory for the project i.e. root project directory
46 | const projectDir = path.resolve('.');
47 |
48 | // Read file and return string
49 | return this.hasPrefix
50 | ? // Has prefix i.e. static content url will be /${publicDir}/whatever
51 | path.resolve(projectDir, './' + currentUrl)
52 | : // No prefix i.e. static content url will be /whatever
53 | path.resolve(projectDir, this.publicDir + '/' + currentUrl);
54 | }
55 |
56 | // Send the file contents to the server
57 | sendFileContents() {
58 | const STATIC_FILE_TIMER = 'Static file fetched';
59 |
60 | // For benchmarking
61 | console.time(STATIC_FILE_TIMER);
62 |
63 | // If the file wasnt found, stop here and let the router handler stuff
64 | const fileToFetch = this.getFileAbsolutePath(this.props.request.url);
65 |
66 | try {
67 | const fileStat = fs.statSync(fileToFetch);
68 |
69 | // Got the file we were looking for
70 | if (fileStat.isFile()) this.terminate();
71 | else return false;
72 | } catch (e) {
73 | return false;
74 | }
75 |
76 | // Stream the file
77 | this.props.response
78 | .sendFile(fileToFetch, {
79 | compress: this._supportedCompression.bind(this),
80 | })
81 | .then(() => console.timeEnd(STATIC_FILE_TIMER))
82 | .catch(e => console.error(e));
83 |
84 | return true;
85 | }
86 |
87 | _supportedCompression() {
88 | if (!this.props.compress) return false;
89 | const GZIP = 'gzip';
90 | const DEFL = 'deflate';
91 | let compressionType = false;
92 | const acceptEncoding = this.props.request.headers['accept-encoding'] || '';
93 | // Identify the compression supported
94 | if (includes(acceptEncoding, GZIP)) return GZIP;
95 | else if (includes(acceptEncoding, DEFL)) return DEFL;
96 | return compressionType;
97 | }
98 | }
99 |
--------------------------------------------------------------------------------
/middlewares/index.js:
--------------------------------------------------------------------------------
1 | export * from './Logger';
2 | export * from './APIRouter.jsx';
3 | export * from './ServiceWorkers.jsx';
4 | export * from './BlankMiddleWare.jsx';
5 | export * from './StaticContentRouter.jsx';
6 | export * from './Compressor.jsx';
7 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "plasmajs",
3 | "version": "0.1.6",
4 | "description": "Isomorphic nodeJS framework powered with react",
5 | "main": "app.jsx",
6 | "scripts": {
7 | "build:d":
8 | "cross-env NODE_ENV=development rollup -c config/rollup/rollup.config.dev.js",
9 | "build:p":
10 | "cross-env NODE_ENV=production rollup -c config/rollup/rollup.config.prod.js",
11 | "check": "flow check",
12 | "coverage":
13 | "cross-env NODE_ENV=test nyc --reporter=lcov --reporter=text mocha ./**/*.spec.jsx --require @babel/register",
14 | "lint": "eslint --ext js,jsx .",
15 | "lint:fix": "eslint --ext js,jsx --fix .",
16 | "precommit": "lint-staged",
17 | "prepush": "npm run coverage && lint-staged",
18 | "test":
19 | "cross-env NODE_ENV=test mocha ./**/*.spec.jsx --require @babel/register",
20 | "test:w":
21 | "cross-env NODE_ENV=test mocha --watch ./**/*.spec.jsx --require @babel/register",
22 | "types": "flow-typed install"
23 | },
24 | "bin": {
25 | "plasmajs": "./bin/run"
26 | },
27 | "repository": {
28 | "type": "git",
29 | "url": "https://github.com/phenax/plasmajs.git"
30 | },
31 | "keywords": ["react", "plasma", "nodejs", "framework"],
32 | "author": "Akshay Nair ",
33 | "contributors": ["Jonathan Sifuentes "],
34 | "license": "Apache-2.0",
35 | "devDependencies": {
36 | "babel-eslint": "^8.2.2",
37 | "babel-plugin-istanbul": "^4.1.5",
38 | "chai": "^4.1.2",
39 | "cross-env": "^5.1.3",
40 | "eslint": "^4.18.2",
41 | "eslint-config-prettier": "^2.9.0",
42 | "eslint-plugin-flowtype": "^2.46.1",
43 | "eslint-plugin-import": "^2.9.0",
44 | "eslint-plugin-jsx-a11y": "^6.0.3",
45 | "eslint-plugin-lodash": "^2.6.1",
46 | "eslint-plugin-prettier": "^2.6.0",
47 | "eslint-plugin-react": "^7.7.0",
48 | "flow-bin": "^0.68.0",
49 | "flow-typed": "^2.3.0",
50 | "husky": "^0.14.3",
51 | "istanbul": "^0.4.5",
52 | "lint-staged": "^7.3.0",
53 | "mocha": "^5.0.2",
54 | "nock": "^9.2.3",
55 | "nyc": "^13.1.0",
56 | "prettier": "^1.11.1",
57 | "prettier-eslint": "^8.8.1",
58 | "rollup": "^0.57.0",
59 | "rollup-plugin-babel": "^4.0.0-beta",
60 | "rollup-plugin-commonjs": "^9.1.0",
61 | "rollup-plugin-json": "^2.3.0",
62 | "rollup-plugin-node-builtins": "^2.1.2",
63 | "rollup-plugin-node-globals": "^1.2.0",
64 | "rollup-plugin-node-resolve": "^3.2.0",
65 | "rollup-plugin-uglify": "^3.0.0"
66 | },
67 | "dependencies": {
68 | "@babel/core": "^7.0.0-beta.40",
69 | "@babel/preset-env": "^7.0.0-beta.40",
70 | "@babel/preset-flow": "7.0.0-beta.40",
71 | "@babel/preset-react": "^7.0.0-beta.40",
72 | "@babel/preset-stage-0": "^7.0.0-beta.40",
73 | "@babel/register": "^7.0.0-beta.40",
74 | "lodash": "^4.17.5",
75 | "mime": "^2.2.0",
76 | "prop-types": "^15.6.0",
77 | "react": "^16.2.0",
78 | "react-dom": "^16.2.0"
79 | },
80 | "lint-staged": {
81 | "*.{js,jsx,json}": ["prettier --write", "git add"]
82 | },
83 | "nyc": {
84 | "check-coverage": true,
85 | "per-file": false,
86 | "lines": 75,
87 | "statements": 75,
88 | "functions": 75,
89 | "branches": 50,
90 | "sourceMap": false,
91 | "instrument": false
92 | }
93 | }
94 |
--------------------------------------------------------------------------------
/router/Router.jsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import PropTypes from 'prop-types';
3 |
4 | import _HnRouteHistoryAPI from './history/_HnRouteHistoryAPI.jsx';
5 |
6 | import assign from 'lodash/assign';
7 | import constant from 'lodash/constant';
8 | import filter from 'lodash/filter';
9 | import isFunction from 'lodash/isFunction';
10 | import map from 'lodash/map';
11 |
12 | // Error components
13 | const DEFAULTERROR = 'Something went wrong';
14 | const NULLCOMPONENTERROR = 'The component cannot be null';
15 | const HISTORYTYPEERROR =
16 | 'The prop `history` has to be an instance of either HistoryAPI or NodeHistoryAPI';
17 |
18 | /**
19 | * Route declaration component
20 | */
21 | export class Route extends React.Component {
22 | static propTypes = {
23 | caseInsensitive: PropTypes.bool,
24 | statusCode: PropTypes.number,
25 | errorHandler: PropTypes.bool,
26 | controller: PropTypes.func,
27 | method: PropTypes.string,
28 | component: PropTypes.func.isRequired,
29 | };
30 | render = constant(null);
31 | }
32 |
33 | /**
34 | * Router wrapper
35 | */
36 | export class Router extends React.Component {
37 | static propTypes = {
38 | wrapper: PropTypes.func,
39 | children: PropTypes.node,
40 | history: PropTypes.object.isRequired,
41 | };
42 |
43 | _EMPTY_ROUTER = ;
44 |
45 | constructor(props) {
46 | super(props);
47 |
48 | this.state = { currentUrl: '/' };
49 |
50 | this._routes = map(
51 | filter(this.props.children, { type: this._EMPTY_ROUTER.type }),
52 | 'props',
53 | );
54 |
55 | if (!(this.props.history instanceof _HnRouteHistoryAPI))
56 | throw new Error(HISTORYTYPEERROR);
57 | }
58 |
59 | // Life cycle methods only executes on the client-side
60 | componentDidMount() {
61 | this.props.history.routeChangeListener(data =>
62 | this.setState({ currentUrl: data.url }),
63 | );
64 | }
65 |
66 | componentWillUnmount() {
67 | this.props.history.removeChangeListener();
68 | }
69 |
70 | render() {
71 | const { props: { history, wrapper } } = this;
72 | if (history.response && history.response.hasTerminated) {
73 | return null;
74 | }
75 |
76 | const route = history.matchRoute(this._routes);
77 |
78 | if (!route) {
79 | throw new Error(DEFAULTERROR);
80 | }
81 |
82 | if (!route.$component) {
83 | throw new Error(NULLCOMPONENTERROR);
84 | }
85 |
86 | // The default props
87 | let defaultProps = {
88 | routerProps: {
89 | url: this.state.currentUrl,
90 | location: history.location,
91 | },
92 | };
93 |
94 | // Call the router controller
95 | if (route.controller) {
96 | route.controller(_props => (defaultProps = assign(defaultProps, _props)));
97 | }
98 |
99 | // Either render the route component or wrap it in a wrapper and render
100 | let $reactElement = route.$component;
101 |
102 | // If it's on the serverside and the wrapper is a function
103 | if (history.response && isFunction(wrapper)) {
104 | const Wrapper = wrapper;
105 | $reactElement = {route.$component};
106 | }
107 |
108 | return React.cloneElement($reactElement, defaultProps);
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/router/components/index.jsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import PropTypes from 'prop-types';
3 |
4 | import { triggerUpdate, routerConfig } from '../history/events.jsx';
5 |
6 | /**
7 | * Link component to be used as an anchor tag for front-end routing
8 | */
9 | export class Link extends React.Component {
10 | _shouldTriggerUpdate() {
11 | // IF the href is set, dont do shit
12 | if (this.props.href) return false;
13 |
14 | // IF to is not set, dont do shit
15 | if (!this.props.to) return false;
16 |
17 | return true;
18 | }
19 |
20 | _visitLink(e) {
21 | if (!this._shouldTriggerUpdate()) return;
22 |
23 | e.preventDefault();
24 |
25 | // If its hash based url, change hash
26 | if (routerConfig.type === 'hash') {
27 | window.location.hash = `#${this.props.to}`;
28 | return;
29 | }
30 |
31 | const defaultState = {
32 | path: this.props.to,
33 | };
34 |
35 | window.history.pushState(
36 | this.props.state
37 | ? { ...defaultState, ...this.props.state }
38 | : { ...defaultState },
39 | '',
40 | this.props.to,
41 | );
42 |
43 | triggerUpdate();
44 | }
45 |
46 | render() {
47 | const properties = {};
48 |
49 | for (let key in this.props) {
50 | if (key === 'to' || key === 'children') continue;
51 |
52 | properties[key] = this.props[key];
53 | }
54 |
55 | return (
56 |
61 | {this.props.children}
62 |
63 | );
64 | }
65 | }
66 |
67 | Link.propTypes = {
68 | to: PropTypes.string,
69 | href: PropTypes.string,
70 | state: PropTypes.object,
71 | };
72 |
--------------------------------------------------------------------------------
/router/history/HashHistoryAPI.jsx:
--------------------------------------------------------------------------------
1 | import _HnRouteHistoryAPI from './_HnRouteHistoryAPI.jsx';
2 |
3 | import * as events from './events.jsx';
4 |
5 | /**
6 | * Helper class to be passed into the HnRouter component for
7 | * routing on the client side (hash routing)
8 | */
9 | export class HashHistoryAPI extends _HnRouteHistoryAPI {
10 | constructor(config) {
11 | super();
12 |
13 | this._config = config;
14 |
15 | events.routerConfig.type = 'hash';
16 | }
17 |
18 | _parseHash(hash) {
19 | return hash.replace('#', '');
20 | }
21 |
22 | matchRoute(routes) {
23 | if (window.location.hash == '') window.location.hash = '#/';
24 |
25 | this._currentUrl = this._parseHash(window.location.hash);
26 |
27 | if (this._currentUrl == '') this._currentUrl = '/';
28 |
29 | return this._matchRoute(routes, this._currentUrl);
30 | }
31 |
32 | routeChangeListener() {
33 | window.addEventListener('hashchange', events.triggerUpdate);
34 | }
35 |
36 | removeChangeListener() {
37 | window.removeEventListener('hashchange', events.triggerUpdate);
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/router/history/HistoryAPI.jsx:
--------------------------------------------------------------------------------
1 | import _HnRouteHistoryAPI from './_HnRouteHistoryAPI.jsx';
2 |
3 | import * as events from './events.jsx';
4 |
5 | /**
6 | * Helper class to be passed into the HnRouter component for
7 | * routing on the client side (pushState routing)
8 | */
9 | export class HistoryAPI extends _HnRouteHistoryAPI {
10 | constructor(config) {
11 | super();
12 |
13 | this._randomId = Math.floor(Math.random() * 1000000).toString(16);
14 |
15 | window.addEventListener('popstate', events.triggerUpdate);
16 |
17 | events.routerConfig.type = 'push';
18 | }
19 |
20 | get location() {
21 | return {
22 | push(url = '/', state = {}, title = '') {
23 | window.history.pushState(state, title, url);
24 | events.triggerUpdate();
25 | },
26 | replace(url = '/', state = {}, title = '') {
27 | window.history.replaceState(state, title, url);
28 | events.triggerUpdate();
29 | },
30 | };
31 | }
32 |
33 | matchRoute(routes) {
34 | this._currentUrl = window.location.pathname;
35 |
36 | return this._matchRoute(routes, this._currentUrl);
37 | }
38 |
39 | routeChangeListener(callback) {
40 | events.addRouteChangeListener(this._randomId, event => {
41 | callback({
42 | url: window.location.pathname,
43 | });
44 | });
45 | }
46 |
47 | removeChangeListener() {
48 | events.removeRouteChangeListener(this._randomId);
49 | window.removeEventListener('popstate', events.triggerUpdate);
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/router/history/MockHistoryAPI.jsx:
--------------------------------------------------------------------------------
1 | import { createElement } from 'react';
2 | import _HnRouteHistoryAPI from './_HnRouteHistoryAPI.jsx';
3 |
4 | import { routerConfig } from './events';
5 |
6 | /**
7 | * Mock history api for testing
8 | */
9 | export class MockHistoryAPI extends _HnRouteHistoryAPI {
10 | constructor(req, res, currentUrl) {
11 | super();
12 |
13 | this._req = req;
14 | this.response = res;
15 |
16 | this._defaultErrorHandler = {
17 | errorHandler: true,
18 | component: createElement('div', {}, '404 Not Found'),
19 | };
20 |
21 | this._currentUrl = currentUrl;
22 |
23 | routerConfig.type = 'node';
24 | }
25 |
26 | // Finds the best match for the current request from the routes
27 | matchRoute(routes) {
28 | this._currentUrl = this._currentUrl;
29 |
30 | // Find the best match
31 | const route =
32 | this._findMatchRoute(routes, this._currentUrl, 'GET') ||
33 | this._defaultErrorHandler;
34 |
35 | // Set the response status code
36 | this.response.statusCode = route.errorHandler
37 | ? 404
38 | : route.statusCode || 200;
39 |
40 | return {
41 | url: this._currentUrl,
42 |
43 | $component: this._getComponentFromClass(route.component, route.props),
44 |
45 | controller: route.controller,
46 | };
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/router/history/NodeHistoryAPI.jsx:
--------------------------------------------------------------------------------
1 | import { createElement } from 'react';
2 | import _HnRouteHistoryAPI from './_HnRouteHistoryAPI.jsx';
3 |
4 | import { routerConfig } from './events';
5 |
6 | /**
7 | * Helper class to be passed into the HnRouter component for
8 | * routing in NodeJS
9 | */
10 | export class NodeHistoryAPI extends _HnRouteHistoryAPI {
11 | constructor(req, res) {
12 | super();
13 |
14 | this._req = req;
15 | this.response = res;
16 |
17 | this._defaultErrorHandler = {
18 | errorHandler: true,
19 | component: createElement('div', {}, '404 Not Found'),
20 | };
21 |
22 | routerConfig.type = 'node';
23 | }
24 |
25 | // Finds the best match for the current request from the routes
26 | matchRoute(routes) {
27 | this._currentUrl = this._req.url;
28 |
29 | // Find the best match
30 | const route =
31 | this._findMatchRoute(routes, this._currentUrl, this._req.method) ||
32 | this._defaultErrorHandler;
33 |
34 | // Set the response status code
35 | this.response.statusCode = route.errorHandler
36 | ? 404
37 | : route.statusCode || 200;
38 |
39 | return {
40 | url: this._currentUrl,
41 | $component: this._getComponentFromClass(route.component, route.props),
42 | controller: route.controller,
43 | };
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/router/history/_HnRouteHistoryAPI.jsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import head from 'lodash/head';
3 | import isNil from 'lodash/isNil';
4 | import isString from 'lodash/isString';
5 | import filter from 'lodash/filter';
6 | import toLower from 'lodash/toLower';
7 | // import {} from 'lodash'; // for searching for functions in VSCode
8 |
9 | import { checkUrlMatch } from '../../lib/helper';
10 | /**
11 | * Super class for all the history api classes
12 | */
13 | export default class _HnRouteHistoryAPI {
14 | // Checks if two routes match
15 | _isAMatch(url1, currentUrl, isCaseInsensitive = false, method1, method2) {
16 | // For case insensitive route urls
17 | if (isString(url1) && isCaseInsensitive) {
18 | return toLower(url1) === toLower(currentUrl);
19 | }
20 |
21 | return checkUrlMatch(url1, currentUrl, method1, method2);
22 | }
23 |
24 | // Iterates through all routes to find the best match
25 | _findMatchRoute(routes, currentUrl, currentMethod) {
26 | let errorRoute = null;
27 |
28 | const matchedRoute = head(
29 | filter(routes, route => {
30 | const { errorHandler, path, caseInsensitive, method } = route;
31 | if (!isNil(errorHandler)) {
32 | errorRoute = route;
33 | return false;
34 | }
35 | if (isNil(path)) {
36 | return false;
37 | }
38 | return this._isAMatch(
39 | path,
40 | currentUrl,
41 | caseInsensitive,
42 | method,
43 | currentMethod,
44 | );
45 | }),
46 | );
47 | if (isNil(matchedRoute)) return errorRoute;
48 | return matchedRoute;
49 | }
50 |
51 | _matchRoute(routes, currentUrl) {
52 | let $renderComponent;
53 |
54 | const route = this._findMatchRoute(routes, currentUrl);
55 |
56 | if (!route) $renderComponent = null;
57 | else
58 | $renderComponent = this._getComponentFromClass(
59 | route.component,
60 | route.props,
61 | );
62 |
63 | return {
64 | url: currentUrl,
65 | $component: $renderComponent,
66 | controller: route.controller,
67 | };
68 | }
69 |
70 | _getComponentFromClass(Component, props) {
71 | if (!Component) return null;
72 |
73 | return ;
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/router/history/events.js:
--------------------------------------------------------------------------------
1 | // @flow
2 | import clone from 'lodash/clone';
3 | import filter from 'lodash/filter';
4 | import map from 'lodash/map';
5 | import isFunction from 'lodash/isFunction';
6 |
7 | const handlers: Map = new Map();
8 |
9 | export const routerConfig = {
10 | type: 'push',
11 | };
12 |
13 | /**
14 | * Trigger update i.e. execute all handlers
15 | */
16 | export function triggerUpdate() {
17 | return map(filter(Array.from(handlers.values()), isFunction), handler =>
18 | handler(),
19 | );
20 | }
21 |
22 | /**
23 | * Add an update handler
24 | * @param {String} id the ID to trigger with
25 | * @param {Function} callback the function to run at the specified ID
26 | * @returns {Boolean} true when the listener was added successfully
27 | */
28 | export function addRouteChangeListener(id: string, callback: Function) {
29 | if (handlers.has(id)) return false;
30 |
31 | handlers.set(id, callback);
32 |
33 | return true;
34 | }
35 |
36 | /**
37 | * Remove an update handler
38 | * @param {String} id the ID to delete
39 | */
40 | export function removeRouteChangeListener(id: string) {
41 | handlers.delete(id);
42 | }
43 |
44 | /**
45 | * Exposes the handlers (i.e., for testing)
46 | * @returns {Map} the handlers as a map object
47 | */
48 | export function exposeRouteChangeListeners() {
49 | return clone(handlers);
50 | }
51 |
--------------------------------------------------------------------------------
/router/history/index.js:
--------------------------------------------------------------------------------
1 | export * from './NodeHistoryAPI.jsx';
2 |
3 | export * from './HistoryAPI.jsx';
4 |
5 | export * from './HashHistoryAPI.jsx';
6 |
--------------------------------------------------------------------------------
/router/index.js:
--------------------------------------------------------------------------------
1 | export * from './components/index';
2 |
3 | export * from './history/HistoryAPI.jsx';
4 | export * from './history/HashHistoryAPI.jsx';
5 |
6 | export * from './Router.jsx';
7 |
--------------------------------------------------------------------------------
/router/server.js:
--------------------------------------------------------------------------------
1 | export * from './history/NodeHistoryAPI.jsx';
2 |
3 | export * from './Router.jsx';
4 |
--------------------------------------------------------------------------------
/tests/.eslintrc.json:
--------------------------------------------------------------------------------
1 | { "env": { "mocha": true, "node": true } }
2 |
--------------------------------------------------------------------------------
/tests/libs/urlMatch.spec.jsx:
--------------------------------------------------------------------------------
1 | import { expect } from 'chai';
2 |
3 | import { checkUrlMatch, toUrlToken } from '../../lib/helper';
4 |
5 | describe('URL Matching', () => {
6 | it('should match two same urls as strings', () => {
7 | expect(checkUrlMatch('/', '/')).to.be.true;
8 | expect(checkUrlMatch('/wontwork', '/wont')).to.be.false;
9 | });
10 |
11 | it('should match a regex to the string', () => {
12 | expect(checkUrlMatch(/^\/hello$/, '/hello')).to.be.true;
13 | expect(checkUrlMatch(/^\/wontwork$/, '/wont')).to.be.false;
14 | });
15 |
16 | it('should match url and the method', () => {
17 | expect(checkUrlMatch('/hello', '/hello', 'GET', 'POST')).to.be.false;
18 | expect(checkUrlMatch(/^\/hello$/, '/hello', 'GET', 'POST')).to.be.false;
19 | });
20 |
21 | it('should tokenize url correctly', () => {
22 | expect(toUrlToken('/users/add')).to.be.eql('users.add');
23 | expect(toUrlToken('/us3clj be-rs/a-232wasd svdd')).to.be.eql(
24 | 'us3clj-be-rs.a-232wasd-svdd',
25 | );
26 | });
27 | });
28 |
--------------------------------------------------------------------------------
/tests/middlewares/api-resources-router.spec.jsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 |
3 | import { expect } from 'chai';
4 |
5 | import constant from 'lodash/constant';
6 |
7 | import { renderComponent } from '../../lib/helper';
8 |
9 | import { Resource, Action } from '../../middlewares/APIResourcesRouter';
10 |
11 | import { mockCtx, createController } from '../../lib/testHelpers.jsx';
12 |
13 | describe('API Resources Router', () => {
14 | describe('with simple handler function routing', () => {
15 | it('should call the correct handler', () => {
16 | let handerFnWasCalled = false;
17 | const handlerFn = () => {
18 | handerFnWasCalled = true;
19 | };
20 |
21 | const ctx = mockCtx('/users', { method: 'get' });
22 |
23 | renderComponent(() => (
24 |
25 |
26 |
27 |
28 | ));
29 |
30 | expect(handerFnWasCalled).to.be.true;
31 | });
32 |
33 | it('should not match when http method is incorrect', () => {
34 | let handerFnWasCalled = false;
35 | const handlerFn = () => {
36 | handerFnWasCalled = true;
37 | };
38 |
39 | const ctx = mockCtx('/users/add', { method: 'get' });
40 |
41 | renderComponent(() => (
42 |
43 |
44 |
45 |
46 | ));
47 |
48 | expect(handerFnWasCalled).to.be.false;
49 | });
50 |
51 | it('should call nothing when nothing matches', () => {
52 | let handerFnWasCalled = false;
53 | const handlerFn = () => {
54 | handerFnWasCalled = true;
55 | };
56 |
57 | const ctx = mockCtx('/uk09kse', { method: 'get' });
58 |
59 | renderComponent(() => (
60 |
61 |
62 |
67 |
68 | ));
69 |
70 | expect(handerFnWasCalled).to.be.false;
71 | });
72 | });
73 |
74 | describe('with controller class', () => {
75 | it('should call the correct decorated action in the controller', () => {
76 | let handerFnWasCalled = false;
77 | const handlerFn = () => {
78 | handerFnWasCalled = true;
79 | };
80 |
81 | const ctx = mockCtx('/users', { method: 'get' });
82 |
83 | renderComponent(() => (
84 |
89 | ));
90 |
91 | expect(handerFnWasCalled).to.be.true;
92 | });
93 |
94 | it('should call handle multiple http methods', () => {
95 | let handerFnWasCalled = false;
96 | const handlerFn = () => {
97 | handerFnWasCalled = true;
98 | };
99 |
100 | let ctx = null;
101 |
102 | handerFnWasCalled = false;
103 | ctx = mockCtx('/users', { method: 'get' });
104 | renderComponent(() => (
105 |
110 | ));
111 |
112 | expect(handerFnWasCalled).to.be.true;
113 |
114 | handerFnWasCalled = false;
115 | ctx = mockCtx('/users', { method: 'post' });
116 | renderComponent(() => (
117 |
122 | ));
123 |
124 | expect(handerFnWasCalled).to.be.true;
125 |
126 | handerFnWasCalled = false;
127 | ctx = mockCtx('/users', { method: 'put' });
128 | renderComponent(() => (
129 |
134 | ));
135 |
136 | expect(handerFnWasCalled).to.be.false;
137 | });
138 | });
139 |
140 | // Tests for controller that return a promise
141 | // describe('With controllers that return a Promise', () => {
142 |
143 | // });
144 | });
145 |
--------------------------------------------------------------------------------
/tests/middlewares/apirouter.spec.jsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 |
3 | import { expect } from 'chai';
4 |
5 | import { renderComponent } from '../../lib/helper';
6 | import { APIRoute } from '../../middlewares/APIRouter';
7 |
8 | import { mockCtx } from '../../lib/testHelpers.jsx';
9 |
10 | describe('APIRoute Middleware', () => {
11 | let ctx;
12 |
13 | // API Route component creator
14 | const component = ctrlr => () => (
15 |
16 | );
17 |
18 | beforeEach(() => {
19 | // Create a new context for /api/test
20 | ctx = mockCtx('/api/test');
21 | });
22 |
23 | // Test to check whether the controller for the api route was called
24 | it('should call controller when route is triggered', () => {
25 | const controller = () => {
26 | controller.hasBeenCalled = true;
27 | };
28 | controller.hasBeenCalled = false;
29 |
30 | renderComponent(component(controller));
31 |
32 | expect(controller.hasBeenCalled).to.be.true;
33 | });
34 |
35 | // Test to check whether the apiroute renders json data
36 | it('should render json', () => {
37 | const data = { a: 'b' };
38 | const controller = send => send(data);
39 |
40 | renderComponent(component(controller));
41 |
42 | // The middleware should make a call to response.json
43 | expect(ctx.calledFn).to.eql('response.json');
44 |
45 | // response.json should be called with the data
46 | expect(ctx.calledWith).to.eql(data);
47 |
48 | // The statusCode of the response should be 200
49 | expect(ctx.calledTarget.statusCode).to.eql(200);
50 | });
51 |
52 | it('should give an error if the controller sends an error', () => {
53 | const err = new Error('Some error');
54 | err.statusCode = 503;
55 |
56 | // Call the error method
57 | const controller = (send, error) => error(err);
58 |
59 | renderComponent(component(controller));
60 |
61 | // Should be a 500 server error
62 | expect(ctx.calledTarget.statusCode).to.eql(503);
63 |
64 | // Should send the error as json
65 | expect(ctx.calledFn).to.eql('response.json');
66 | expect(ctx.calledWith).to.eql(err);
67 | });
68 |
69 | // Tests for controller that return a promise
70 | describe('With controllers that return a Promise', () => {
71 | const data = { a: 'b' };
72 | const err = new Error('Some error');
73 |
74 | let controller, ctrlPromise;
75 |
76 | beforeEach(done => {
77 | ctrlPromise = null;
78 |
79 | // Controller that returns a promise
80 | controller = () => {
81 | ctrlPromise = new Promise((resolve, reject) => {
82 | // A 50ms delay. Slow enough
83 | setTimeout(() => {
84 | resolve(data);
85 | }, 50);
86 | })
87 | .then(data => {
88 | done();
89 | return data;
90 | })
91 | .catch(e => {
92 | done();
93 | return e;
94 | });
95 |
96 | return ctrlPromise;
97 | };
98 |
99 | // Render the component
100 | renderComponent(component(controller));
101 | });
102 |
103 | it('should render json that it got from the promise', done => {
104 | // Slightly hacky but no way to execute a function at the end
105 | // of the promise chain
106 | process.nextTick(() => {
107 | // Should render json
108 | expect(ctx.calledFn).to.eql('response.json');
109 | expect(ctx.calledWith).to.eql(data);
110 |
111 | expect(ctx.calledTarget.statusCode).to.eql(200);
112 |
113 | done();
114 | });
115 | });
116 | });
117 | });
118 |
--------------------------------------------------------------------------------
/tests/middlewares/custom-middleware.spec.jsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 |
3 | import { expect } from 'chai';
4 |
5 | import { MiddleWare } from '../../MiddleWare';
6 |
7 | import { renderComponent } from '../../lib/helper';
8 | import { mockCtx } from '../../lib/testHelpers.jsx';
9 |
10 | describe('Custom Middleware', () => {
11 | let wasCalled;
12 |
13 | let callback;
14 |
15 | let ctx;
16 |
17 | class MockMiddleWare extends MiddleWare {
18 | onRequest(req, res) {
19 | wasCalled = true;
20 | this.res = res;
21 | if (callback) callback(() => this.terminate());
22 | }
23 | }
24 |
25 | beforeEach(() => {
26 | wasCalled = false;
27 |
28 | ctx = mockCtx();
29 | });
30 |
31 | it('should call the onRequest method when rendered', () => {
32 | renderComponent(() => );
33 |
34 | expect(wasCalled).to.be.true;
35 | });
36 |
37 | it('should terminate when .terminate is called', () => {
38 | callback = terminate => terminate();
39 |
40 | renderComponent(() => );
41 |
42 | expect(ctx.calledTarget.hasTerminated).to.be.true;
43 | });
44 |
45 | it('should throw error when there is no onRequest method defined', () => {
46 | const onReqBackup = MockMiddleWare.prototype.onRequest;
47 | MockMiddleWare.prototype.onRequest = null;
48 |
49 | expect(() => renderComponent(() => )).to.throw(
50 | Error,
51 | );
52 |
53 | MockMiddleWare.prototype.onRequest = onReqBackup;
54 | });
55 | });
56 |
--------------------------------------------------------------------------------
/tests/middlewares/public/test.txt:
--------------------------------------------------------------------------------
1 | Test file that does exist
2 |
--------------------------------------------------------------------------------
/tests/middlewares/staticcontent.spec.jsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import path from 'path';
3 | import { expect } from 'chai';
4 |
5 | import { StaticContentRouter } from '../../middlewares/StaticContentRouter';
6 |
7 | import { renderComponent } from '../../lib/helper';
8 | import { mockCtx } from '../../lib/testHelpers.jsx';
9 |
10 | describe('StaticContentRouter Middleware', () => {
11 | let ctx;
12 |
13 | const FILE_EXISTS_URL = '/test.txt';
14 | const FILE_DOESNT_EXIST_URL = '/doesnt/exist.txt';
15 |
16 | const STATIC_DIRECTORY = './tests/middlewares/public';
17 |
18 | const scRouter = config => () => (
19 |
26 | );
27 |
28 | // Static file routing without file url prefixing
29 | describe('Static routing without prefix', () => {
30 | it('should send the correct file', () => {
31 | ctx = mockCtx(FILE_EXISTS_URL);
32 |
33 | renderComponent(scRouter());
34 |
35 | // Should be a terminal node
36 | expect(ctx.calledTarget).to.exist;
37 | expect(ctx.calledTarget.hasTerminated).to.be.true;
38 |
39 | // Should call sendFile
40 | expect(ctx.calledFn).to.eql('response.sendFile');
41 |
42 | // Should call sendFile with this path
43 | expect(ctx.calledWith).to.eql(
44 | path.resolve(STATIC_DIRECTORY + FILE_EXISTS_URL),
45 | );
46 | });
47 |
48 | it('should do nothing when no file matches', () => {
49 | ctx = mockCtx(FILE_DOESNT_EXIST_URL);
50 |
51 | renderComponent(scRouter());
52 |
53 | // Shouldn't call anything
54 | expect(ctx.calledTarget).to.not.exist;
55 | expect(ctx.calledFn).to.not.exist;
56 | expect(ctx.calledWith).to.not.exist;
57 | });
58 | });
59 | });
60 |
--------------------------------------------------------------------------------
/tests/router/history/NodeHistoryAPI.spec.jsx:
--------------------------------------------------------------------------------
1 | // @flow
2 | import React from 'react';
3 | import PropTypes from 'prop-types';
4 |
5 | import constant from 'lodash/constant';
6 | import forEach from 'lodash/forEach';
7 | import isString from 'lodash/isString';
8 | import isObject from 'lodash/isObject';
9 | import noop from 'lodash/noop';
10 |
11 | import { expect } from 'chai';
12 |
13 | // import nock from 'nock';
14 |
15 | import { Router, Route } from '../../../router/server';
16 | import { NodeHistoryAPI } from '../../../router/history/NodeHistoryAPI.jsx';
17 |
18 | const Wrapper = ({ children, name }) => (
19 |
20 | {children}
21 | {name}
22 |
23 | );
24 | Wrapper.propTypes = {
25 | children: PropTypes.node.isRequired,
26 | name: PropTypes.string.isRequired,
27 | };
28 |
29 | export const Index = () => Index
;
30 | export const About = () => About
;
31 | export const Error404 = () => Error
;
32 |
33 | export const CtrlrPage = () => constant(null);
34 |
35 | const router = (
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 | );
45 | describe('Router', () => {
46 | describe('Node History API', () => {
47 | it('can be created', () => {
48 | const history = new NodeHistoryAPI(null, null);
49 | expect(history).to.be.an.instanceof(NodeHistoryAPI);
50 | });
51 | });
52 | describe('Configuration', () => {
53 | describe('Node History API', () => {
54 | it('should have the history api', () => {
55 | expect(router.props.history).to.exist;
56 | expect(router.props.history).to.be.instanceof(NodeHistoryAPI);
57 | });
58 |
59 | it('should have all routes', () => {
60 | expect(router.props.children).to.not.be.empty;
61 |
62 | forEach(router.props.children, child => {
63 | expect(child).to.exist;
64 |
65 | expect(child.type).to.eql(.type);
66 | });
67 | });
68 |
69 | it('should have all the routes configured correctly', () => {
70 | forEach(router.props.children, child => {
71 | expect(child.props.component).to.exist;
72 | expect(child.props.component).to.be.instanceof(Function);
73 |
74 | if (!child.props.errorHandler) {
75 | expect(child.props.path).to.satisfy(path => {
76 | if (isString(path) || (isObject(path) && 'test' in path))
77 | return true;
78 | return false;
79 | });
80 | }
81 | });
82 | });
83 | });
84 | });
85 | });
86 |
--------------------------------------------------------------------------------
/tests/router/history/events.spec.jsx:
--------------------------------------------------------------------------------
1 | import constant from 'lodash/constant';
2 | import { expect } from 'chai';
3 |
4 | import {
5 | addRouteChangeListener,
6 | exposeRouteChangeListeners,
7 | removeRouteChangeListener,
8 | triggerUpdate,
9 | } from '../../../router/history/events';
10 |
11 | describe('Router', () => {
12 | describe('history', () => {
13 | describe('event handlers', () => {
14 | afterEach(() => {
15 | removeRouteChangeListener('test');
16 | });
17 | it('can add a trigger handler based on an id', () => {
18 | expect(addRouteChangeListener('test', constant(true))).to.be.true;
19 | expect(exposeRouteChangeListeners().has('test')).to.be.true;
20 | });
21 | it('will not clobber an existing trigger', () => {
22 | addRouteChangeListener('test', constant(true));
23 | expect(addRouteChangeListener('test', constant(false))).to.be.false;
24 | expect(exposeRouteChangeListeners().get('test')).to.be.a('function');
25 | expect(exposeRouteChangeListeners().get('test')()).to.be.true;
26 | });
27 | it('can remove an existing ID', () => {
28 | addRouteChangeListener('test', constant(true));
29 | expect(removeRouteChangeListener('test')).not.to.throw;
30 | expect(exposeRouteChangeListeners().has('test')).to.be.false;
31 | });
32 | it("don't care if the ID exists or not when removing", () => {
33 | addRouteChangeListener('test', constant(true));
34 | expect(removeRouteChangeListener('test')).not.to.throw;
35 | expect(exposeRouteChangeListeners().has('test')).to.be.false;
36 | expect(removeRouteChangeListener('foo')).not.to.throw;
37 | expect(exposeRouteChangeListeners().has('foo')).to.be.false;
38 | });
39 | it('will fire off all the handlers that are functions whenever updates are triggered', () => {
40 | addRouteChangeListener('foo', 2);
41 | addRouteChangeListener('bar', constant(3));
42 | addRouteChangeListener('baz', constant(4));
43 | addRouteChangeListener('test', constant(true));
44 | const updates = triggerUpdate();
45 | expect(updates)
46 | .to.be.an('array')
47 | .and.have.length(3);
48 | expect(updates).to.include(3);
49 | expect(updates).to.include(4);
50 | expect(updates).to.include(true);
51 | });
52 | });
53 | });
54 | });
55 |
--------------------------------------------------------------------------------
/tests/router/router.spec.jsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 |
3 | import { expect } from 'chai';
4 |
5 | import forEach from 'lodash/forEach';
6 | import isString from 'lodash/isString';
7 | import isObject from 'lodash/isObject';
8 | import noop from 'lodash/noop';
9 |
10 | import { Route } from '../../router/server';
11 | import { MockHistoryAPI } from '../../router/history/MockHistoryAPI.jsx';
12 |
13 | import { renderComponent } from '../../lib/helper';
14 | import * as route from '../../lib/testHelpers.jsx';
15 |
16 | describe('Router', () => {
17 | describe('Configuration', () => {
18 | let router;
19 |
20 | beforeEach(() => {
21 | router = route.getRouter('/')();
22 | });
23 |
24 | it('should have the history api', () => {
25 | expect(router.props.history).to.exist;
26 | expect(router.props.history).to.be.instanceof(MockHistoryAPI);
27 | });
28 |
29 | it('should have all routes', () => {
30 | expect(router.props.children).to.not.be.empty;
31 |
32 | forEach(router.props.children, child => {
33 | expect(child).to.exist;
34 |
35 | expect(child.type).to.eql(.type);
36 | });
37 | });
38 | it('should be able to unmount without throwing errors', () => {
39 | expect(router.componentWillUnmount).not.to.throw;
40 | });
41 | it('should have all the routes configured correctly', () => {
42 | forEach(router.props.children, child => {
43 | expect(child.props.component).to.exist;
44 | expect(child.props.component).to.be.instanceof(Function);
45 |
46 | if (!child.props.errorHandler) {
47 | expect(child.props.path).to.satisfy(path => {
48 | if (isString(path) || (isObject(path) && 'test' in path))
49 | return true;
50 | return false;
51 | });
52 | }
53 | });
54 | });
55 | });
56 |
57 | describe('Routing', () => {
58 | it('should render match for path as a string', () => {
59 | const markup = renderComponent(route.getRouter('/'));
60 |
61 | // Rendered route should be the index route
62 | expect(markup).to.eql(route.indexString);
63 | });
64 |
65 | it('should render match for path as a regex', () => {
66 | const markup = renderComponent(route.getRouter('/about'));
67 |
68 | // Rendered route should be the about route
69 | expect(markup).to.eql(route.aboutString);
70 | });
71 |
72 | it('should render error route if no match was found', () => {
73 | const markup = renderComponent(
74 | route.getRouter('/this-route-doesnt-exist-404-error'),
75 | );
76 |
77 | // Rendered route should be the 404 error
78 | expect(markup).to.eql(route.errorString);
79 | });
80 | });
81 |
82 | describe('Controller', () => {
83 | it('should be called', () => {
84 | let wasControllerCalled = false;
85 | const controller = _ => (wasControllerCalled = true); //eslint-disable-line no-unused-vars
86 |
87 | renderComponent(route.getRouter('/ctrlr', controller));
88 |
89 | expect(wasControllerCalled).to.be.true;
90 | });
91 |
92 | it('should set props for component', () => {
93 | const props = { name: 'It Works' };
94 |
95 | const controller = setProps => setProps(props);
96 |
97 | const markup = renderComponent(route.getRouter('/ctrlr', controller));
98 |
99 | expect(markup).to.eql(route.getCtrlrString(props.name));
100 | });
101 | });
102 | });
103 |
--------------------------------------------------------------------------------