├── .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 | [![Build Status](https://travis-ci.org/phenax/plasmajs.svg?branch=master)](https://travis-ci.org/phenax/plasmajs) 4 | [![npm version](https://img.shields.io/npm/v/plasmajs.svg)](https://www.npmjs.com/package/plasmajs) 5 | [![license](https://img.shields.io/npm/l/plasmajs.svg)](https://github.com/phenax/plasmajs/blob/master/LICENSE) 6 | [![dependency status](https://david-dm.org/phenax/plasmajs/status.svg)](https://david-dm.org/phenax/plasmajs) 7 | [![Discord](https://img.shields.io/discord/425972740688838656.svg)](https://discord.gg/b9Z4b6r) 8 | 9 | [![NPM](https://nodei.co/npm/plasmajs.png?downloadRank=true)](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 = '
Index
'; 42 | export const aboutString = '
About
'; 43 | export const errorString = '
Error
'; 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 |