├── .yarnrc ├── .npmrc ├── .prettierignore ├── client ├── src │ ├── react-app-env.d.ts │ ├── setupTests.ts │ ├── index.css │ ├── App.test.tsx │ ├── App.css │ ├── App.tsx │ ├── index.tsx │ ├── logo.svg │ └── serviceWorker.ts ├── public │ ├── robots.txt │ ├── favicon.ico │ ├── logo192.png │ ├── logo512.png │ ├── manifest.json │ └── index.html ├── .env.example ├── .gitignore ├── tsconfig.json ├── package.json └── README.md ├── .vscode ├── settings.json └── launch.json ├── .prettierrc ├── scripts └── build.sh ├── cypress.json ├── src ├── controllers │ └── sample.ts ├── routes │ └── index.ts ├── types │ └── sample.ts ├── schema.ts └── app.ts ├── jest.config.js ├── cypress ├── tsconfig.json ├── fixtures │ └── example.json ├── support │ └── index.js ├── plugins │ └── index.js ├── integration │ └── spec.ts └── README.md ├── __tests__ └── routes.ts ├── .gitignore ├── .editorconfig ├── README.md ├── package.json ├── bin └── www ├── .circleci └── config.yml └── tsconfig.json /.yarnrc: -------------------------------------------------------------------------------- 1 | save-prefix "" -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | package-lock=false 2 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | node_modules/* 2 | package.json 3 | package-lock.json 4 | -------------------------------------------------------------------------------- /client/src/react-app-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "typescript.tsdk": "node_modules/typescript/lib" 3 | } 4 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "semi": true, 3 | "singleQuote": true, 4 | "trailingComma": "all" 5 | } 6 | -------------------------------------------------------------------------------- /client/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /client/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bondz/node-express-react-ts/HEAD/client/public/favicon.ico -------------------------------------------------------------------------------- /client/public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bondz/node-express-react-ts/HEAD/client/public/logo192.png -------------------------------------------------------------------------------- /client/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bondz/node-express-react-ts/HEAD/client/public/logo512.png -------------------------------------------------------------------------------- /scripts/build.sh: -------------------------------------------------------------------------------- 1 | yarn tsc 2 | 3 | cd client 4 | export SKIP_PREFLIGHT_CHECK=true 5 | yarn 6 | yarn build 7 | -------------------------------------------------------------------------------- /cypress.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://on.cypress.io/cypress.schema.json", 3 | "baseUrl": "http://localhost:3005" 4 | } 5 | -------------------------------------------------------------------------------- /client/.env.example: -------------------------------------------------------------------------------- 1 | SKIP_PREFLIGHT_CHECK=true 2 | REACT_APP_SENTRY_CONFIG_DSN=your sentry dsn 3 | REACT_APP_CLIENT_ENVIRONMENT=development 4 | -------------------------------------------------------------------------------- /src/controllers/sample.ts: -------------------------------------------------------------------------------- 1 | function sampleController() { 2 | return { hello: 'Hello World' }; 3 | } 4 | 5 | export default sampleController; 6 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | preset: 'ts-jest', 3 | testEnvironment: 'node', 4 | testPathIgnorePatterns: ['/client/', '/cypress/'], 5 | }; 6 | -------------------------------------------------------------------------------- /cypress/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": ["*/*.ts"], 3 | "compilerOptions": { 4 | "noEmit": false, 5 | "isolatedModules": false, 6 | "types": ["cypress"] 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /cypress/fixtures/example.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Using fixtures to represent data", 3 | "email": "hello@cypress.io", 4 | "body": "Fixtures are a great way to mock data for responses to routes" 5 | } 6 | -------------------------------------------------------------------------------- /client/src/setupTests.ts: -------------------------------------------------------------------------------- 1 | // jest-dom adds custom jest matchers for asserting on DOM nodes. 2 | // allows you to do things like: 3 | // expect(element).toHaveTextContent(/react/i) 4 | // learn more: https://github.com/testing-library/jest-dom 5 | import '@testing-library/jest-dom/extend-expect'; 6 | -------------------------------------------------------------------------------- /src/routes/index.ts: -------------------------------------------------------------------------------- 1 | import { Router } from 'express'; 2 | import sampleController from '../controllers/sample'; 3 | 4 | const router = Router(); 5 | 6 | router.get('/', function(_req, res, _next) { 7 | const message = sampleController(); 8 | 9 | res.status(200).json({ message }); 10 | }); 11 | 12 | export default router; 13 | -------------------------------------------------------------------------------- /__tests__/routes.ts: -------------------------------------------------------------------------------- 1 | import request from 'supertest'; 2 | 3 | import app from '../src/app'; 4 | 5 | describe('Server', () => { 6 | test('Has a /api endpoint', () => { 7 | return request(app) 8 | .get('/api') 9 | .expect('Content-Type', /json/) 10 | .expect(200, { message: { hello: 'Hello World' } }); 11 | }); 12 | }); 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # Typescript compiled files 4 | dist/ 5 | 6 | # dependencies 7 | node_modules 8 | 9 | # testing 10 | coverage 11 | 12 | # misc 13 | .DS_Store 14 | .env 15 | .env.local 16 | .env.development.local 17 | .env.test.local 18 | .env.production.local 19 | 20 | *.log 21 | 22 | cypress/videos 23 | -------------------------------------------------------------------------------- /src/types/sample.ts: -------------------------------------------------------------------------------- 1 | import { GraphQLObjectType, GraphQLString } from 'graphql'; 2 | 3 | const SampleType = new GraphQLObjectType({ 4 | name: 'SampleType', 5 | description: 'This is a sample graphql type', 6 | fields: () => ({ 7 | hello: { 8 | type: GraphQLString, 9 | description: 'Returns hello world', 10 | }, 11 | }), 12 | }); 13 | 14 | export default SampleType; 15 | -------------------------------------------------------------------------------- /client/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /client/src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 5 | sans-serif; 6 | -webkit-font-smoothing: antialiased; 7 | -moz-osx-font-smoothing: grayscale; 8 | } 9 | 10 | code { 11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', 12 | monospace; 13 | } 14 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # top-most EditorConfig file 2 | root = true 3 | 4 | # Unix-style newlines with a newline ending every file 5 | [*] 6 | end_of_line = lf 7 | insert_final_newline = true 8 | indent_style = space 9 | indent_size = 2 10 | trim_trailing_whitespace = true 11 | 12 | [node_modules/**] 13 | end_of_line = unset 14 | insert_final_newline = unset 15 | indent_style = unset 16 | indent_size = unset 17 | trim_trailing_whitespace = unset 18 | -------------------------------------------------------------------------------- /client/src/App.test.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { render, screen } from '@testing-library/react'; 3 | import { MockedProvider } from '@apollo/client/testing'; 4 | 5 | import App from './App'; 6 | 7 | test('renders learn react link', () => { 8 | render( 9 | 10 | 11 | , 12 | ); 13 | 14 | expect(screen.getByText(/learn react/i)).toBeInTheDocument(); 15 | expect( 16 | screen.getByText(/Please wait - GraphQL Data Loading/i), 17 | ).toBeInTheDocument(); 18 | }); 19 | -------------------------------------------------------------------------------- /src/schema.ts: -------------------------------------------------------------------------------- 1 | import { GraphQLObjectType, GraphQLSchema } from 'graphql'; 2 | 3 | import sampleController from './controllers/sample'; 4 | import SampleType from './types/sample'; 5 | 6 | const query = new GraphQLObjectType({ 7 | name: 'Query', 8 | description: 'The query root of Nert.', 9 | fields: () => ({ 10 | sample: { 11 | type: SampleType, 12 | description: 'A sample root schema', 13 | resolve: () => sampleController(), 14 | }, 15 | }), 16 | }); 17 | 18 | const schema = new GraphQLSchema({ 19 | query, 20 | }); 21 | 22 | export default schema; 23 | -------------------------------------------------------------------------------- /cypress/support/index.js: -------------------------------------------------------------------------------- 1 | // *********************************************************** 2 | // This example support/index.js is processed and 3 | // loaded automatically before your test files. 4 | // 5 | // This is a great place to put global configuration and 6 | // behavior that modifies Cypress. 7 | // 8 | // You can change the location of this file or turn off 9 | // automatically serving support files with the 10 | // 'supportFile' configuration option. 11 | // 12 | // You can read more here: 13 | // https://on.cypress.io/configuration 14 | // *********************************************************** 15 | -------------------------------------------------------------------------------- /client/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "lib": [ 5 | "dom", 6 | "dom.iterable", 7 | "esnext" 8 | ], 9 | "allowJs": true, 10 | "skipLibCheck": true, 11 | "esModuleInterop": true, 12 | "allowSyntheticDefaultImports": true, 13 | "strict": true, 14 | "forceConsistentCasingInFileNames": true, 15 | "module": "esnext", 16 | "moduleResolution": "node", 17 | "resolveJsonModule": true, 18 | "isolatedModules": true, 19 | "noEmit": true, 20 | "jsx": "react" 21 | }, 22 | "include": [ 23 | "src" 24 | ] 25 | } 26 | -------------------------------------------------------------------------------- /client/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Express React Template with Typescript 2 | 3 | [![CircleCI](https://circleci.com/gh/bondz/node-express-react-ts.svg?style=svg)](https://circleci.com/gh/bondz/node-express-react-ts) 4 | 5 | Run the server with 6 | 7 | ```bash 8 | yarn 9 | yarn start 10 | ``` 11 | 12 | --- 13 | 14 | Then run the client 15 | 16 | ```bash 17 | cd client 18 | yarn 19 | yarn start 20 | ``` 21 | 22 | --- 23 | 24 | The server part of this system is already designed and exposes a set of REST endpoints via the `/api` route and a GraphQL endpoint. 25 | 26 | The client has been setup to consume graphql if you chose to use that instead. 27 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "type": "node", 9 | "request": "launch", 10 | "name": "Launch App Server", 11 | "protocol": "inspector", 12 | "program": "${workspaceFolder}/bin/www", 13 | "sourceMaps": true, 14 | "smartStep": true, 15 | "env": { 16 | "PORT": "3005", 17 | "NODE_ENV": "development" 18 | } 19 | } 20 | ] 21 | } 22 | -------------------------------------------------------------------------------- /client/src/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | text-align: center; 3 | } 4 | 5 | .App-logo { 6 | height: 40vmin; 7 | pointer-events: none; 8 | } 9 | 10 | @media (prefers-reduced-motion: no-preference) { 11 | .App-logo { 12 | animation: App-logo-spin infinite 20s linear; 13 | } 14 | } 15 | 16 | .App-header { 17 | background-color: #282c34; 18 | min-height: 100vh; 19 | display: flex; 20 | flex-direction: column; 21 | align-items: center; 22 | justify-content: center; 23 | font-size: calc(10px + 2vmin); 24 | color: white; 25 | } 26 | 27 | .App-link { 28 | color: #61dafb; 29 | } 30 | 31 | @keyframes App-logo-spin { 32 | from { 33 | transform: rotate(0deg); 34 | } 35 | to { 36 | transform: rotate(360deg); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /cypress/plugins/index.js: -------------------------------------------------------------------------------- 1 | /// 2 | // *********************************************************** 3 | // This example plugins/index.js can be used to load plugins 4 | // 5 | // You can change the location of this file or turn off loading 6 | // the plugins file with the 'pluginsFile' configuration option. 7 | // 8 | // You can read more here: 9 | // https://on.cypress.io/plugins-guide 10 | // *********************************************************** 11 | 12 | // This function is called when a project is opened or re-opened (e.g. due to 13 | // the project's config changing) 14 | 15 | /** 16 | * @type {Cypress.PluginConfig} 17 | */ 18 | module.exports = (on, config) => { 19 | // `on` is used to hook into various events Cypress emits 20 | // `config` is the resolved Cypress config 21 | }; 22 | -------------------------------------------------------------------------------- /cypress/integration/spec.ts: -------------------------------------------------------------------------------- 1 | // enables intelligent code completion for Cypress commands 2 | // https://on.cypress.io/intelligent-code-completion 3 | /// 4 | 5 | context('Example Cypress TodoMVC test', () => { 6 | beforeEach(() => { 7 | // usually we recommend setting baseUrl in cypress.json 8 | // but for simplicity of this example we just use it here 9 | // https://on.cypress.io/visit 10 | cy.visit('/'); 11 | }); 12 | 13 | it('shows learn link', function() { 14 | cy.get('.App-link') 15 | .should('be.visible') 16 | .and('have.text', 'Learn React'); 17 | }); 18 | 19 | // more examples 20 | // 21 | // https://github.com/cypress-io/cypress-example-todomvc 22 | // https://github.com/cypress-io/cypress-example-kitchensink 23 | // https://on.cypress.io/writing-your-first-test 24 | }); 25 | -------------------------------------------------------------------------------- /cypress/README.md: -------------------------------------------------------------------------------- 1 | # Cypress.io end-to-end tests 2 | 3 | [Cypress.io](https://www.cypress.io) is an open source, MIT licensed end-to-end test runner 4 | 5 | ## Folder structure 6 | 7 | These folders hold end-to-end tests and supporting files for the Cypress Test Runner. 8 | 9 | - [fixtures](fixtures) holds optional JSON data for mocking, [read more](https://on.cypress.io/fixture) 10 | - [integration](integration) holds the actual test files, [read more](https://on.cypress.io/writing-and-organizing-tests) 11 | - [plugins](plugins) allow you to customize how tests are loaded, [read more](https://on.cypress.io/plugins) 12 | - [support](support) file runs before all tests and is a great place to write or load additional custom commands, [read more](https://on.cypress.io/writing-and-organizing-tests#Support-file) 13 | 14 | ## `cypress.json` file 15 | 16 | You can configure project options in the [../cypress.json](../cypress.json) file, see [Cypress configuration doc](https://on.cypress.io/configuration). 17 | 18 | ## More information 19 | 20 | - [https://github.com/cypress.io/cypress](https://github.com/cypress.io/cypress) 21 | - [https://docs.cypress.io/](https://docs.cypress.io/) 22 | - [Writing your first Cypress test](http://on.cypress.io/intro) 23 | -------------------------------------------------------------------------------- /client/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "client", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@apollo/client": "3.0.2", 7 | "@sentry/browser": "5.20.1", 8 | "@testing-library/jest-dom": "^5.11.1", 9 | "@testing-library/react": "10.4.7", 10 | "@testing-library/user-event": "^12.0.15", 11 | "@types/jest": "^26.0.7", 12 | "@types/node": "^12.0.0", 13 | "@types/react": "^16.9.43", 14 | "@types/react-dom": "^16.9.8", 15 | "graphql": "15.3.0", 16 | "react": "^16.13.1", 17 | "react-dom": "^16.13.1", 18 | "react-scripts": "3.4.1", 19 | "typescript": "~3.9.7" 20 | }, 21 | "scripts": { 22 | "start": "react-scripts start", 23 | "build": "react-scripts build", 24 | "test": "react-scripts test", 25 | "eject": "react-scripts eject" 26 | }, 27 | "eslintConfig": { 28 | "extends": "react-app" 29 | }, 30 | "browserslist": { 31 | "production": [ 32 | ">0.2%", 33 | "not dead", 34 | "not op_mini all" 35 | ], 36 | "development": [ 37 | "last 1 chrome version", 38 | "last 1 firefox version", 39 | "last 1 safari version" 40 | ] 41 | }, 42 | "resolutions": { 43 | "lodash": ">=4.17.13", 44 | "lodash.template": ">=4.5.0" 45 | }, 46 | "proxy": "http://localhost:3005" 47 | } 48 | -------------------------------------------------------------------------------- /client/src/App.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import logo from './logo.svg'; 3 | import './App.css'; 4 | 5 | import { gql, useQuery } from '@apollo/client'; 6 | const query = gql` 7 | { 8 | sample { 9 | hello 10 | } 11 | } 12 | `; 13 | function SampleComponent() { 14 | const { data, loading, error } = useQuery(query); 15 | 16 | if (loading) { 17 | return <>Please wait - GraphQL Data Loading; 18 | } 19 | 20 | if (error) { 21 | console.error(error); 22 | 23 | return ( 24 | <> 25 | An Error occured: Check the console. It could be that the server is 26 | offline, start the server and refresh. 27 | 28 | ); 29 | } 30 | 31 | return <>Data Fetched: {data.sample.hello}; 32 | } 33 | 34 | function App() { 35 | return ( 36 |
37 |
38 | 39 | logo 40 |

41 | Edit src/App.tsx and save to reload. 42 |

43 | 49 | Learn React 50 | 51 |
52 |
53 | ); 54 | } 55 | 56 | export default App; 57 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nert-service", 3 | "version": "2.0.0", 4 | "main": "bin/www", 5 | "author": "Bond ", 6 | "license": "MIT", 7 | "private": true, 8 | "scripts": { 9 | "build": "scripts/build.sh", 10 | "start": "./bin/www", 11 | "test": "jest", 12 | "test:integration": "cypress run", 13 | "client:start": "cd client; yarn start" 14 | }, 15 | "dependencies": { 16 | "compression": "1.7.4", 17 | "cors": "2.8.5", 18 | "date-fns": "2.15.0", 19 | "dotenv": "8.2.0", 20 | "express": "4.17.1", 21 | "express-graphql": "0.11.0", 22 | "graphql": "15.3.0", 23 | "http-errors": "1.8.0", 24 | "morgan": "1.10.0" 25 | }, 26 | "devDependencies": { 27 | "@types/compression": "1.7.0", 28 | "@types/cors": "2.8.6", 29 | "@types/express": "4.17.7", 30 | "@types/express-graphql": "0.9.0", 31 | "@types/graphql": "14.5.0", 32 | "@types/http-errors": "1.8.0", 33 | "@types/jest": "26.0.7", 34 | "@types/morgan": "1.9.1", 35 | "@types/node": "14.0.26", 36 | "@types/supertest": "2.0.10", 37 | "cypress": "4.11.0", 38 | "husky": "4.2.5", 39 | "jest": "26.1.0", 40 | "prettier": "2.0.5", 41 | "pretty-quick": "2.0.1", 42 | "supertest": "4.0.2", 43 | "ts-jest": "26.1.3", 44 | "typescript": "3.9.7" 45 | }, 46 | "husky": { 47 | "hooks": { 48 | "pre-commit": "pretty-quick --staged" 49 | } 50 | }, 51 | "resolutions": { 52 | "@types/node": "12.12.53", 53 | "lodash": ">=4.17.13" 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /client/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React App 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /client/src/index.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import * as sentry from '@sentry/browser'; 4 | 5 | import { 6 | ApolloProvider, 7 | ApolloClient, 8 | ApolloLink, 9 | InMemoryCache, 10 | createHttpLink, 11 | } from '@apollo/client'; 12 | import { setContext } from '@apollo/client/link/context'; 13 | import { onError } from '@apollo/client/link/error'; 14 | 15 | import App from './App'; 16 | import * as serviceWorker from './serviceWorker'; 17 | 18 | if (process.env.NODE_ENV === 'production') { 19 | sentry.init({ 20 | dsn: process.env.REACT_APP_SENTRY_CONFIG_DSN, 21 | environment: process.env.REACT_APP_CLIENT_ENVIRONMENT, 22 | }); 23 | } 24 | 25 | const link = ApolloLink.from([ 26 | onError(({ graphQLErrors, networkError }) => { 27 | if (graphQLErrors) { 28 | graphQLErrors.forEach(({ message, locations, path }) => { 29 | const errMsg = `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`; 30 | 31 | sentry.captureMessage(errMsg); 32 | }); 33 | } 34 | if (networkError) { 35 | // Todo: Logout the user for 401 http errors? 36 | } 37 | }), 38 | setContext((_, { headers }) => { 39 | return { 40 | headers: { 41 | ...headers, 42 | authorization: undefined, // You can pass a token here like: token ? `Bearer ${token}` : null, 43 | }, 44 | }; 45 | }), 46 | createHttpLink({ 47 | uri: '/graphql', 48 | }), 49 | ]); 50 | 51 | const client = new ApolloClient({ 52 | link, 53 | cache: new InMemoryCache(), 54 | }); 55 | 56 | ReactDOM.render( 57 | 58 | 59 | , 60 | document.getElementById('root'), 61 | ); 62 | 63 | // If you want your app to work offline and load faster, you can change 64 | // unregister() to register() below. Note this comes with some pitfalls. 65 | // Learn more about service workers: https://bit.ly/CRA-PWA 66 | serviceWorker.unregister(); 67 | -------------------------------------------------------------------------------- /client/README.md: -------------------------------------------------------------------------------- 1 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 2 | 3 | ## Available Scripts 4 | 5 | In the project directory, you can run: 6 | 7 | ### `yarn start` 8 | 9 | Runs the app in the development mode.
10 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 11 | 12 | The page will reload if you make edits.
13 | You will also see any lint errors in the console. 14 | 15 | ### `yarn test` 16 | 17 | Launches the test runner in the interactive watch mode.
18 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 19 | 20 | ### `yarn build` 21 | 22 | Builds the app for production to the `build` folder.
23 | It correctly bundles React in production mode and optimizes the build for the best performance. 24 | 25 | The build is minified and the filenames include the hashes.
26 | Your app is ready to be deployed! 27 | 28 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 29 | 30 | ### `yarn eject` 31 | 32 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 33 | 34 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 35 | 36 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. 37 | 38 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. 39 | 40 | ## Learn More 41 | 42 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 43 | 44 | To learn React, check out the [React documentation](https://reactjs.org/). 45 | -------------------------------------------------------------------------------- /src/app.ts: -------------------------------------------------------------------------------- 1 | import createError from 'http-errors'; 2 | import express from 'express'; 3 | import cors from 'cors'; 4 | import compression from 'compression'; 5 | import morgan from 'morgan'; 6 | import { graphqlHTTP } from 'express-graphql'; 7 | import path from 'path'; 8 | import fs from 'fs'; 9 | 10 | import apiRouter from './routes/index'; 11 | import schema from './schema'; 12 | 13 | const app = express(); 14 | 15 | // Setup Request logging 16 | const logFormat = process.env.NODE_ENV === 'production' ? 'combined' : 'dev'; 17 | 18 | app.use( 19 | morgan(logFormat, { 20 | skip: function (_req, res) { 21 | if (process.env.NODE_ENV === 'test') { 22 | return true; 23 | } 24 | 25 | return res.statusCode < 400; 26 | }, 27 | stream: process.stderr, 28 | }), 29 | ); 30 | 31 | app.use( 32 | morgan(logFormat, { 33 | skip: function (_req, res) { 34 | if (process.env.NODE_ENV === 'test') { 35 | return true; 36 | } 37 | 38 | return res.statusCode >= 400; 39 | }, 40 | stream: process.stdout, 41 | }), 42 | ); 43 | 44 | app.disable('x-powered-by'); 45 | app.use(compression()); 46 | app.use(cors()); 47 | app.use(express.json()); 48 | app.use(express.urlencoded({ extended: false })); 49 | 50 | app.use('/api', apiRouter); 51 | 52 | app.use( 53 | '/graphql', 54 | graphqlHTTP({ 55 | schema, 56 | graphiql: true, 57 | }), 58 | ); 59 | 60 | const clientPath = path.join(__dirname, '../', 'client/build'); 61 | 62 | if (fs.existsSync(clientPath)) { 63 | app.use(express.static(clientPath)); 64 | app.get('/*', (_req, res) => { 65 | res.sendFile(path.join(clientPath, 'index.html')); 66 | }); 67 | } 68 | 69 | // catch 404 and forward to error handler 70 | app.use(function ( 71 | _req: express.Request, 72 | _res: express.Response, 73 | next: express.NextFunction, 74 | ) { 75 | next(createError(404)); 76 | }); 77 | 78 | // error handler 79 | app.use(function (err: any, req: express.Request, res: express.Response) { 80 | // set locals, only providing error in development 81 | res.locals.message = err.message; 82 | res.locals.error = req.app.get('env') === 'development' ? err : {}; 83 | 84 | // render the error page 85 | res.status(err.status || 500); 86 | res.render('error'); 87 | }); 88 | 89 | export default app; 90 | -------------------------------------------------------------------------------- /bin/www: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | /** 4 | * Read environment variables 5 | */ 6 | require('dotenv').config(); 7 | 8 | /** 9 | * Believe it or not, reading process.env is expensive in NODE.js 10 | * https://github.com/nodejs/node/issues/3104 11 | * We want to cache process.env to a regular object since we don't expect it to change at runtime anyway. 12 | */ 13 | process.env = JSON.parse(JSON.stringify(process.env)); 14 | 15 | /** 16 | * Module dependencies. 17 | */ 18 | 19 | const app = require('../dist/app').default; 20 | const debug = require('debug')('nert:server'); 21 | const http = require('http'); 22 | 23 | /** 24 | * Get port from environment and store in Express. 25 | */ 26 | 27 | const port = normalizePort(process.env.PORT || '3005'); 28 | app.set('port', port); 29 | 30 | /** 31 | * Create HTTP server. 32 | */ 33 | 34 | const server = http.createServer(app); 35 | 36 | /** 37 | * Listen on provided port, on all network interfaces. 38 | */ 39 | 40 | server.listen(port); 41 | server.on('error', onError); 42 | server.on('listening', onListening); 43 | 44 | /** 45 | * Normalize a port into a number, string, or false. 46 | */ 47 | 48 | function normalizePort(val) { 49 | const portNumber = parseInt(val, 10); 50 | 51 | if (isNaN(portNumber)) { 52 | // named pipe 53 | return val; 54 | } 55 | 56 | if (portNumber >= 0) { 57 | // port number 58 | return portNumber; 59 | } 60 | 61 | return false; 62 | } 63 | 64 | /** 65 | * Event listener for HTTP server "error" event. 66 | */ 67 | 68 | function onError(error) { 69 | if (error.syscall !== 'listen') { 70 | throw error; 71 | } 72 | 73 | const bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port; 74 | 75 | // handle specific listen errors with friendly messages 76 | switch (error.code) { 77 | case 'EACCES': 78 | console.error(bind + ' requires elevated privileges'); 79 | process.exit(1); 80 | break; 81 | case 'EADDRINUSE': 82 | console.error(bind + ' is already in use'); 83 | process.exit(1); 84 | break; 85 | default: 86 | throw error; 87 | } 88 | } 89 | 90 | /** 91 | * Event listener for HTTP server "listening" event. 92 | */ 93 | 94 | function onListening() { 95 | const addr = server.address(); 96 | const bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port; 97 | debug('Listening on ' + bind); 98 | } 99 | -------------------------------------------------------------------------------- /client/src/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | # Javascript Node CircleCI 2.0 configuration file 2 | # 3 | # Check https://circleci.com/docs/2.0/language-javascript/ for more details 4 | # 5 | version: 2.1 6 | jobs: 7 | NERT Server: 8 | docker: 9 | # specify the version you desire here 10 | - image: circleci/node:10 11 | 12 | # Specify service dependencies here if necessary 13 | # CircleCI maintains a library of pre-built images 14 | # documented at https://circleci.com/docs/2.0/circleci-images/ 15 | # - image: circleci/mongo:4.0.3 16 | 17 | working_directory: ~/node-express-react-ts 18 | 19 | steps: 20 | - checkout 21 | 22 | # Download and cache dependencies 23 | - restore_cache: 24 | keys: 25 | - dependency-cache-server-{{ checksum "package.json" }} 26 | # fallback to using the latest cache if no exact match is found 27 | - dependency-cache-server- 28 | 29 | - run: yarn --frozen-lockfile 30 | 31 | - save_cache: 32 | key: dependency-cache-server-{{ checksum "package.json" }} 33 | paths: 34 | # Save the yarn cache folder so we can cache cypress as well. 35 | - ~/.cache 36 | 37 | # Run typescript 38 | - run: yarn tsc 39 | # run tests! 40 | - run: yarn jest 41 | 42 | NERT Client: 43 | docker: 44 | # specify the version you desire here 45 | - image: circleci/node:10 46 | 47 | working_directory: ~/node-express-react-ts 48 | 49 | steps: 50 | - checkout 51 | 52 | # Download and cache dependencies 53 | - restore_cache: 54 | keys: 55 | - dependency-cache-client-{{ checksum "./client/package.json" }} 56 | # fallback to using the latest cache if no exact match is found 57 | - dependency-cache-client- 58 | 59 | - run: 60 | name: Install client dependencies 61 | command: cd client && yarn --frozen-lockfile 62 | 63 | - save_cache: 64 | key: dependency-cache-client-{{ checksum "./client/package.json" }} 65 | paths: 66 | - ./client/node_modules 67 | 68 | # run tests! 69 | - run: 70 | name: Run client tests 71 | command: cd client && yarn test 72 | 73 | NERT Integration: 74 | docker: 75 | # specify the version you desire here 76 | - image: cypress/browsers:node10.16.0-chrome77 77 | 78 | # Specify service dependencies here if necessary 79 | # CircleCI maintains a library of pre-built images 80 | # documented at https://circleci.com/docs/2.0/circleci-images/ 81 | # - image: circleci/mongo:4.0.3 82 | 83 | working_directory: ~/node-express-react-ts 84 | 85 | steps: 86 | - checkout 87 | 88 | # Download and cache dependencies 89 | - restore_cache: 90 | keys: 91 | - dependency-cache-server-{{ checksum "package.json" }} 92 | - dependency-cache-server- 93 | 94 | - run: 95 | name: Build client 96 | command: cd client && yarn --frozen-lockfile && yarn build 97 | - run: 98 | name: Build server 99 | command: yarn --frozen-lockfile && yarn tsc 100 | 101 | # run tests! 102 | - run: 103 | name: Run integration tests 104 | command: npx start-server-and-test start http://localhost:3005 test:integration 105 | 106 | workflows: 107 | Test Server and Client: 108 | jobs: 109 | - NERT Client 110 | - NERT Server 111 | - NERT Integration: 112 | filters: 113 | branches: 114 | only: 115 | - master 116 | requires: 117 | - NERT Client 118 | - NERT Server 119 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Basic Options */ 4 | "incremental": true /* Enable incremental compilation */, 5 | "target": "es2017" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */, 6 | "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */, 7 | // "lib": [], /* Specify library files to be included in the compilation. */ 8 | // "allowJs": true, /* Allow javascript files to be compiled. */ 9 | // "checkJs": true, /* Report errors in .js files. */ 10 | // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ 11 | // "declaration": true, /* Generates corresponding '.d.ts' file. */ 12 | // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ 13 | "sourceMap": true /* Generates corresponding '.map' file. */, 14 | // "outFile": "./", /* Concatenate and emit output to single file. */ 15 | "outDir": "./dist" /* Redirect output structure to the directory. */, 16 | // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ 17 | // "composite": true, /* Enable project compilation */ 18 | // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ 19 | // "removeComments": true, /* Do not emit comments to output. */ 20 | // "noEmit": true, /* Do not emit outputs. */ 21 | // "importHelpers": true, /* Import emit helpers from 'tslib'. */ 22 | // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ 23 | // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ 24 | 25 | /* Strict Type-Checking Options */ 26 | "strict": true /* Enable all strict type-checking options. */, 27 | // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ 28 | // "strictNullChecks": true, /* Enable strict null checks. */ 29 | // "strictFunctionTypes": true, /* Enable strict checking of function types. */ 30 | // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ 31 | // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ 32 | // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ 33 | // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ 34 | 35 | /* Additional Checks */ 36 | "noUnusedLocals": true /* Report errors on unused locals. */, 37 | "noUnusedParameters": true /* Report errors on unused parameters. */, 38 | "noImplicitReturns": true /* Report error when not all code paths in function return a value. */, 39 | "noFallthroughCasesInSwitch": true /* Report errors for fallthrough cases in switch statement. */, 40 | 41 | /* Module Resolution Options */ 42 | // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ 43 | // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ 44 | // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ 45 | // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ 46 | // "typeRoots": [], /* List of folders to include type definitions from. */ 47 | // "types": [], /* Type declaration files to be included in compilation. */ 48 | // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ 49 | "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ 50 | // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ 51 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 52 | 53 | /* Source Map Options */ 54 | // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ 55 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 56 | // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ 57 | // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ 58 | 59 | /* Experimental Options */ 60 | // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ 61 | // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ 62 | }, 63 | "include": ["typings/**/*.d.ts", "src"] 64 | } 65 | -------------------------------------------------------------------------------- /client/src/serviceWorker.ts: -------------------------------------------------------------------------------- 1 | // This optional code is used to register a service worker. 2 | // register() is not called by default. 3 | 4 | // This lets the app load faster on subsequent visits in production, and gives 5 | // it offline capabilities. However, it also means that developers (and users) 6 | // will only see deployed updates on subsequent visits to a page, after all the 7 | // existing tabs open on the page have been closed, since previously cached 8 | // resources are updated in the background. 9 | 10 | // To learn more about the benefits of this model and instructions on how to 11 | // opt-in, read https://bit.ly/CRA-PWA 12 | 13 | const isLocalhost = Boolean( 14 | window.location.hostname === 'localhost' || 15 | // [::1] is the IPv6 localhost address. 16 | window.location.hostname === '[::1]' || 17 | // 127.0.0.0/8 are considered localhost for IPv4. 18 | window.location.hostname.match( 19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ 20 | ) 21 | ); 22 | 23 | type Config = { 24 | onSuccess?: (registration: ServiceWorkerRegistration) => void; 25 | onUpdate?: (registration: ServiceWorkerRegistration) => void; 26 | }; 27 | 28 | export function register(config?: Config) { 29 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 30 | // The URL constructor is available in all browsers that support SW. 31 | const publicUrl = new URL( 32 | process.env.PUBLIC_URL, 33 | window.location.href 34 | ); 35 | if (publicUrl.origin !== window.location.origin) { 36 | // Our service worker won't work if PUBLIC_URL is on a different origin 37 | // from what our page is served on. This might happen if a CDN is used to 38 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374 39 | return; 40 | } 41 | 42 | window.addEventListener('load', () => { 43 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 44 | 45 | if (isLocalhost) { 46 | // This is running on localhost. Let's check if a service worker still exists or not. 47 | checkValidServiceWorker(swUrl, config); 48 | 49 | // Add some additional logging to localhost, pointing developers to the 50 | // service worker/PWA documentation. 51 | navigator.serviceWorker.ready.then(() => { 52 | console.log( 53 | 'This web app is being served cache-first by a service ' + 54 | 'worker. To learn more, visit https://bit.ly/CRA-PWA' 55 | ); 56 | }); 57 | } else { 58 | // Is not localhost. Just register service worker 59 | registerValidSW(swUrl, config); 60 | } 61 | }); 62 | } 63 | } 64 | 65 | function registerValidSW(swUrl: string, config?: Config) { 66 | navigator.serviceWorker 67 | .register(swUrl) 68 | .then(registration => { 69 | registration.onupdatefound = () => { 70 | const installingWorker = registration.installing; 71 | if (installingWorker == null) { 72 | return; 73 | } 74 | installingWorker.onstatechange = () => { 75 | if (installingWorker.state === 'installed') { 76 | if (navigator.serviceWorker.controller) { 77 | // At this point, the updated precached content has been fetched, 78 | // but the previous service worker will still serve the older 79 | // content until all client tabs are closed. 80 | console.log( 81 | 'New content is available and will be used when all ' + 82 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' 83 | ); 84 | 85 | // Execute callback 86 | if (config && config.onUpdate) { 87 | config.onUpdate(registration); 88 | } 89 | } else { 90 | // At this point, everything has been precached. 91 | // It's the perfect time to display a 92 | // "Content is cached for offline use." message. 93 | console.log('Content is cached for offline use.'); 94 | 95 | // Execute callback 96 | if (config && config.onSuccess) { 97 | config.onSuccess(registration); 98 | } 99 | } 100 | } 101 | }; 102 | }; 103 | }) 104 | .catch(error => { 105 | console.error('Error during service worker registration:', error); 106 | }); 107 | } 108 | 109 | function checkValidServiceWorker(swUrl: string, config?: Config) { 110 | // Check if the service worker can be found. If it can't reload the page. 111 | fetch(swUrl, { 112 | headers: { 'Service-Worker': 'script' } 113 | }) 114 | .then(response => { 115 | // Ensure service worker exists, and that we really are getting a JS file. 116 | const contentType = response.headers.get('content-type'); 117 | if ( 118 | response.status === 404 || 119 | (contentType != null && contentType.indexOf('javascript') === -1) 120 | ) { 121 | // No service worker found. Probably a different app. Reload the page. 122 | navigator.serviceWorker.ready.then(registration => { 123 | registration.unregister().then(() => { 124 | window.location.reload(); 125 | }); 126 | }); 127 | } else { 128 | // Service worker found. Proceed as normal. 129 | registerValidSW(swUrl, config); 130 | } 131 | }) 132 | .catch(() => { 133 | console.log( 134 | 'No internet connection found. App is running in offline mode.' 135 | ); 136 | }); 137 | } 138 | 139 | export function unregister() { 140 | if ('serviceWorker' in navigator) { 141 | navigator.serviceWorker.ready 142 | .then(registration => { 143 | registration.unregister(); 144 | }) 145 | .catch(error => { 146 | console.error(error.message); 147 | }); 148 | } 149 | } 150 | --------------------------------------------------------------------------------