├── notes └── .gitkeep ├── public ├── style.css ├── favicon.ico ├── chevron-down.svg ├── chevron-up.svg ├── cross.svg ├── checkmark.svg ├── logo.svg └── index.html ├── server ├── package.json └── api.server.js ├── credentials.js ├── src ├── FancyBlogPost.js ├── blog │ └── blog-api.js ├── Comment.client.js ├── App.server.js ├── db.server.js ├── LocationContext.client.js ├── BlogPost.server.js ├── index.client.js ├── BlogPostsList.server.js ├── LikeButton.client.js ├── Cache.client.js └── Root.client.js ├── scripts ├── init_db.sh ├── build.js └── seed.js ├── .prettierignore ├── .prettierrc.js ├── .gitignore ├── README.md ├── LICENSE ├── db.json ├── package.json └── CODE_OF_CONDUCT.md /notes/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /public/style.css: -------------------------------------------------------------------------------- 1 | .blog-post { 2 | padding: 10px; 3 | } 4 | -------------------------------------------------------------------------------- /server/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "type": "commonjs", 3 | "main": "./api.server.js" 4 | } 5 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sidthesloth92/server-components-demo/main/public/favicon.ico -------------------------------------------------------------------------------- /credentials.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | host: process.env.DB_HOST || 'localhost', 3 | database: 'notesapi', 4 | user: 'notesadmin', 5 | password: 'password', 6 | port: '5432', 7 | }; 8 | -------------------------------------------------------------------------------- /public/chevron-down.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /public/chevron-up.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /public/cross.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /public/checkmark.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /src/FancyBlogPost.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | 3 | export default function FancyBlogPost({children}) { 4 | return ( 5 |
9 | {children} 10 |
11 | ); 12 | } 13 | -------------------------------------------------------------------------------- /src/blog/blog-api.js: -------------------------------------------------------------------------------- 1 | import {fetch} from 'react-fetch'; 2 | 3 | export const getBlogPosts = function() { 4 | return fetch('http://localhost:3000/posts').json(); 5 | }; 6 | 7 | export const getBlogPost = function(id) { 8 | return fetch(`http://localhost:3000/posts/${id}`).json(); 9 | }; 10 | -------------------------------------------------------------------------------- /src/Comment.client.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | 3 | export default function Comment() { 4 | const [comment, setComment] = React.useState(''); 5 | return ( 6 | setComment(value)} 9 | /> 10 | ); 11 | } 12 | -------------------------------------------------------------------------------- /scripts/init_db.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | 4 | psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL 5 | DROP TABLE IF EXISTS notes; 6 | CREATE TABLE notes ( 7 | id SERIAL PRIMARY KEY, 8 | created_at TIMESTAMP NOT NULL, 9 | updated_at TIMESTAMP NOT NULL, 10 | title TEXT, 11 | body TEXT 12 | ); 13 | EOSQL 14 | -------------------------------------------------------------------------------- /src/App.server.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Facebook, Inc. and its affiliates. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | * 7 | */ 8 | import BlogPostsList from './BlogPostsList.server'; 9 | 10 | export default function App() { 11 | return ; 12 | } 13 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | # dependencies 2 | /node_modules 3 | /.pnp 4 | .pnp.js 5 | 6 | # testing 7 | /coverage 8 | 9 | # production 10 | /build 11 | /dist 12 | 13 | # misc 14 | .DS_Store 15 | .eslintcache 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 | 25 | *.html 26 | *.json 27 | *.md 28 | -------------------------------------------------------------------------------- /public/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | React Logo 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /src/db.server.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Facebook, Inc. and its affiliates. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | * 7 | */ 8 | 9 | import {Pool} from 'react-pg'; 10 | import credentials from '../credentials'; 11 | 12 | // Don't keep credentials in the source tree in a real app! 13 | export const db = new Pool(credentials); 14 | -------------------------------------------------------------------------------- /src/LocationContext.client.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Facebook, Inc. and its affiliates. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | * 7 | */ 8 | 9 | import {createContext, useContext} from 'react'; 10 | 11 | export const LocationContext = createContext(); 12 | export function useLocation() { 13 | return useContext(LocationContext); 14 | } 15 | -------------------------------------------------------------------------------- /.prettierrc.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Facebook, Inc. and its affiliates. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | * 7 | */ 8 | 9 | 'use strict'; 10 | 11 | module.exports = { 12 | arrowParens: 'always', 13 | bracketSpacing: false, 14 | singleQuote: true, 15 | jsxBracketSameLine: true, 16 | trailingComma: 'es5', 17 | printWidth: 80, 18 | }; 19 | -------------------------------------------------------------------------------- /src/BlogPost.server.js: -------------------------------------------------------------------------------- 1 | import {getBlogPost} from './blog/blog-api'; 2 | import LikeButton from './LikeButton.client'; 3 | import Comment from './Comment.client'; 4 | 5 | export default function BlogPost({blog: {id}}) { 6 | const blog = getBlogPost(id); 7 | return ( 8 |
9 |

{blog.title}

10 |

{blog.markdown}

11 | 12 | 13 |
14 | ); 15 | } 16 | -------------------------------------------------------------------------------- /src/index.client.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Facebook, Inc. and its affiliates. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | * 7 | */ 8 | 9 | import {unstable_createRoot} from 'react-dom'; 10 | import Root from './Root.client'; 11 | 12 | const initialCache = new Map(); 13 | const root = unstable_createRoot(document.getElementById('root')); 14 | root.render(); 15 | -------------------------------------------------------------------------------- /.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 | /dist 14 | 15 | # notes 16 | notes/*.md 17 | 18 | # misc 19 | .DS_Store 20 | .eslintcache 21 | .env 22 | .env.local 23 | .env.development.local 24 | .env.test.local 25 | .env.production.local 26 | 27 | npm-debug.log* 28 | yarn-debug.log* 29 | yarn-error.log* 30 | 31 | # vscode 32 | .vscode 33 | -------------------------------------------------------------------------------- /src/BlogPostsList.server.js: -------------------------------------------------------------------------------- 1 | import {getBlogPosts} from './blog/blog-api'; 2 | import BlogPost from './BlogPost.server'; 3 | import FancyBlogPost from './FancyBlogPost'; 4 | 5 | export default function BlogPostsList() { 6 | const blogs = getBlogPosts(); 7 | return ( 8 | <> 9 | {blogs.map((blog, index) => ( 10 | <> 11 | {index % 2 ? ( 12 | 13 | ) : ( 14 | 15 | 16 | 17 | )} 18 | 19 | ))} 20 | 21 | ); 22 | } 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # React Server Components Demo 2 | 3 | This is a simplified fork of [server-components-demo](https://github.com/reactjs/server-components-demo). 4 | ## What is this? 5 | 6 | This is a demo app built with React Server Components, an experimental React feature. 7 | 8 | ## Setup 9 | 10 | You will need to have nodejs >=14.9.0 in order to run this demo. [Node 14 LTS](https://nodejs.org/en/about/releases/) is a good choice! 11 | 12 | ``` 13 | npm install 14 | ``` 15 | 16 | To run 17 | ``` 18 | npm run start 19 | ``` 20 | 21 | Then open http://localhost:4000. 22 | 23 | ## Built by (A-Z) 24 | 25 | - [Andrew Clark](https://twitter.com/acdlite) 26 | - [Dan Abramov](https://twitter.com/dan_abramov) 27 | - [Joe Savona](https://twitter.com/en_JS) 28 | - [Lauren Tan](https://twitter.com/sugarpirate_) 29 | - [Sebastian Markbåge](https://twitter.com/sebmarkbage) 30 | - [Tate Strickland](http://www.tatestrickland.com/) (Design) 31 | 32 | ## License 33 | This demo is MIT licensed. 34 | -------------------------------------------------------------------------------- /src/LikeButton.client.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import {useLocation} from './LocationContext.client'; 3 | 4 | export default function LikeButton({blog}) { 5 | const [, setLocation] = useLocation(); 6 | const handleClick = async () => { 7 | await likeBlogPost(blog.id); 8 | setLocation((loc) => ({ 9 | ...loc, 10 | likes: blog.likes + 1, 11 | })); 12 | }; 13 | 14 | const likeBlogPost = async (id) => { 15 | const headers = new Headers(); 16 | headers.append('Content-Type', 'application/json'); 17 | 18 | var raw = JSON.stringify({ 19 | ...blog, 20 | likes: blog.likes + 1, 21 | }); 22 | 23 | await fetch(`http://localhost:3000/posts/${id}`, { 24 | method: 'PUT', 25 | headers, 26 | body: raw, 27 | redirect: 'follow', 28 | }) 29 | .then((response) => response.text()) 30 | .then((result) => console.log(result)) 31 | .catch((error) => console.log('error', error)); 32 | }; 33 | 34 | return Likes: {blog.likes}; 35 | } 36 | -------------------------------------------------------------------------------- /src/Cache.client.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Facebook, Inc. and its affiliates. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | * 7 | */ 8 | 9 | import {unstable_getCacheForType, unstable_useCacheRefresh} from 'react'; 10 | import {createFromFetch} from 'react-server-dom-webpack'; 11 | 12 | function createResponseCache() { 13 | return new Map(); 14 | } 15 | 16 | export function useRefresh() { 17 | const refreshCache = unstable_useCacheRefresh(); 18 | return function refresh(key, seededResponse) { 19 | refreshCache(createResponseCache, new Map([[key, seededResponse]])); 20 | }; 21 | } 22 | 23 | export function useServerResponse(location) { 24 | const key = JSON.stringify(location); 25 | const cache = unstable_getCacheForType(createResponseCache); 26 | let response = cache.get(key); 27 | if (response) { 28 | return response; 29 | } 30 | response = createFromFetch( 31 | fetch('/react?location=' + encodeURIComponent(key)) 32 | ); 33 | cache.set(key, response); 34 | return response; 35 | } 36 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Facebook, Inc. and its affiliates. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | React Server Components 9 | 10 | 11 |
12 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /src/Root.client.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Facebook, Inc. and its affiliates. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | * 7 | */ 8 | 9 | import {useState, Suspense} from 'react'; 10 | import {ErrorBoundary} from 'react-error-boundary'; 11 | 12 | import {useServerResponse} from './Cache.client'; 13 | import {LocationContext} from './LocationContext.client'; 14 | 15 | export default function Root({initialCache}) { 16 | return ( 17 | 18 | 19 | 20 | 21 | 22 | ); 23 | } 24 | 25 | function Content() { 26 | const [location, setLocation] = useState({ 27 | selectedId: null, 28 | isEditing: false, 29 | searchText: '', 30 | likes: 0, 31 | }); 32 | const response = useServerResponse(location); 33 | return ( 34 | 35 | {response.readRoot()} 36 | 37 | ); 38 | } 39 | 40 | function Error({error}) { 41 | return ( 42 |
43 |

Application Error

44 |
{error.stack}
45 |
46 | ); 47 | } 48 | -------------------------------------------------------------------------------- /db.json: -------------------------------------------------------------------------------- 1 | { 2 | "posts": [ 3 | { 4 | "id": 1, 5 | "title": "Blog 1", 6 | "description": "unt aut facere repellat provident occaecati excepturi optio reprehenderit", 7 | "markdown": "unt aut facere repellat provident occaecati excepturi optio reprehenderit unt aut facere repellat provident occaecati excepturi optio reprehenderit unt aut facere repellat provident occaecati excepturi optio reprehenderit", 8 | "likes": 54 9 | }, 10 | { 11 | "id": 2, 12 | "title": "Blog 2", 13 | "description": "st rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanunt aut facere repellat provident occaecati excepturi optio reprehenderit", 14 | "markdown": "pturi optio reprehenderit unt aut facere repellat provident occaecati excepturist rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blan optio reprehenderit unt aut facere repellat provident occaecati excepturi optio reprehenderit", 15 | "likes": 136 16 | }, 17 | { 18 | "id": 3, 19 | "title": "Blog 3", 20 | "description": "a molestias quasi exercitationem repellat qui ipsa ", 21 | "markdown": "a molestias quasi exercitationem repellat qui ipsa occaecati excepturi optio reprehenderit unt aut facere repellat provident occaecati excepturi optio reprehenderit unt aut facere repellat provident occaecati excepturi optio reprehenderit", 22 | "likes": 36 23 | } 24 | ] 25 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-notes", 3 | "version": "0.1.0", 4 | "private": true, 5 | "engines": { 6 | "node": ">=14.9.0" 7 | }, 8 | "license": "MIT", 9 | "dependencies": { 10 | "@babel/core": "7.12.3", 11 | "@babel/register": "^7.12.1", 12 | "babel-loader": "8.1.0", 13 | "babel-preset-react-app": "10.0.0", 14 | "compression": "^1.7.4", 15 | "concurrently": "^5.3.0", 16 | "date-fns": "^2.16.1", 17 | "excerpts": "^0.0.3", 18 | "express": "^4.17.1", 19 | "html-webpack-plugin": "4.5.0", 20 | "json-server": "^0.16.3", 21 | "lowdb": "^1.0.0", 22 | "marked": "^1.2.5", 23 | "nodemon": "^2.0.6", 24 | "pg": "^8.5.1", 25 | "react": "0.0.0-experimental-3310209d0", 26 | "react-dom": "0.0.0-experimental-3310209d0", 27 | "react-error-boundary": "^3.1.0", 28 | "react-fetch": "0.0.0-experimental-3310209d0", 29 | "react-fs": "0.0.0-experimental-3310209d0", 30 | "react-pg": "0.0.0-experimental-3310209d0", 31 | "react-server-dom-webpack": "0.0.0-experimental-3310209d0", 32 | "resolve": "1.12.0", 33 | "rimraf": "^3.0.2", 34 | "sanitize-html": "^2.2.0", 35 | "webpack": "4.44.2", 36 | "webpack-cli": "^4.2.0" 37 | }, 38 | "devDependencies": { 39 | "cross-env": "^7.0.3", 40 | "prettier": "1.19.1" 41 | }, 42 | "scripts": { 43 | "start": "concurrently \"npm run server:dev\" \"npm run bundler:dev\" \"npm run api:dev\"", 44 | "server:dev": "cross-env NODE_ENV=development nodemon -- --conditions=react-server server", 45 | "bundler:dev": "cross-env NODE_ENV=development nodemon -- scripts/build.js", 46 | "api:dev": "json-server --watch ./db.json" 47 | }, 48 | "babel": { 49 | "presets": [ 50 | [ 51 | "react-app", 52 | { 53 | "runtime": "automatic" 54 | } 55 | ] 56 | ] 57 | }, 58 | "nodemonConfig": { 59 | "ignore": [ 60 | "build/*" 61 | ] 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /scripts/build.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Facebook, Inc. and its affiliates. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | * 7 | */ 8 | 9 | 'use strict'; 10 | 11 | const path = require('path'); 12 | const rimraf = require('rimraf'); 13 | const webpack = require('webpack'); 14 | const HtmlWebpackPlugin = require('html-webpack-plugin'); 15 | const ReactServerWebpackPlugin = require('react-server-dom-webpack/plugin'); 16 | 17 | const isProduction = process.env.NODE_ENV === 'production'; 18 | rimraf.sync(path.resolve(__dirname, '../build')); 19 | webpack( 20 | { 21 | mode: isProduction ? 'production' : 'development', 22 | devtool: isProduction ? 'source-map' : 'cheap-module-source-map', 23 | entry: [path.resolve(__dirname, '../src/index.client.js')], 24 | output: { 25 | path: path.resolve(__dirname, '../build'), 26 | filename: 'main.js', 27 | }, 28 | module: { 29 | rules: [ 30 | { 31 | test: /\.js$/, 32 | use: 'babel-loader', 33 | exclude: /node_modules/, 34 | }, 35 | ], 36 | }, 37 | plugins: [ 38 | new HtmlWebpackPlugin({ 39 | inject: true, 40 | template: path.resolve(__dirname, '../public/index.html'), 41 | }), 42 | new ReactServerWebpackPlugin({isServer: false}), 43 | ], 44 | }, 45 | (err, stats) => { 46 | if (err) { 47 | console.error(err.stack || err); 48 | if (err.details) { 49 | console.error(err.details); 50 | } 51 | process.exit(1); 52 | return; 53 | } 54 | const info = stats.toJson(); 55 | if (stats.hasErrors()) { 56 | console.log('Finished running webpack with errors.'); 57 | info.errors.forEach((e) => console.error(e)); 58 | process.exit(1); 59 | } else { 60 | console.log('Finished running webpack.'); 61 | } 62 | } 63 | ); 64 | -------------------------------------------------------------------------------- /scripts/seed.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Facebook, Inc. and its affiliates. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | * 7 | */ 8 | 9 | 'use strict'; 10 | 11 | const fs = require('fs'); 12 | const path = require('path'); 13 | const {Pool} = require('pg'); 14 | const {readdir, unlink, writeFile} = require('fs/promises'); 15 | const startOfYear = require('date-fns/startOfYear'); 16 | const credentials = require('../credentials'); 17 | 18 | const NOTES_PATH = './notes'; 19 | const pool = new Pool(credentials); 20 | 21 | const now = new Date(); 22 | const startOfThisYear = startOfYear(now); 23 | // Thanks, https://stackoverflow.com/a/9035732 24 | function randomDateBetween(start, end) { 25 | return new Date( 26 | start.getTime() + Math.random() * (end.getTime() - start.getTime()) 27 | ); 28 | } 29 | 30 | const dropTableStatement = 'DROP TABLE IF EXISTS notes;'; 31 | const createTableStatement = `CREATE TABLE notes ( 32 | id SERIAL PRIMARY KEY, 33 | created_at TIMESTAMP NOT NULL, 34 | updated_at TIMESTAMP NOT NULL, 35 | title TEXT, 36 | body TEXT 37 | );`; 38 | const insertNoteStatement = `INSERT INTO notes(title, body, created_at, updated_at) 39 | VALUES ($1, $2, $3, $3) 40 | RETURNING *`; 41 | const seedData = [ 42 | [ 43 | 'Meeting Notes', 44 | 'This is an example note. It contains **Markdown**!', 45 | randomDateBetween(startOfThisYear, now), 46 | ], 47 | [ 48 | 'Make a thing', 49 | `It's very easy to make some words **bold** and other words *italic* with 50 | Markdown. You can even [link to React's website!](https://www.reactjs.org).`, 51 | randomDateBetween(startOfThisYear, now), 52 | ], 53 | [ 54 | 'A note with a very long title because sometimes you need more words', 55 | `You can write all kinds of [amazing](https://en.wikipedia.org/wiki/The_Amazing) 56 | notes in this app! These note live on the server in the \`notes\` folder. 57 | 58 | ![This app is powered by React](https://upload.wikimedia.org/wikipedia/commons/thumb/1/18/React_Native_Logo.png/800px-React_Native_Logo.png)`, 59 | randomDateBetween(startOfThisYear, now), 60 | ], 61 | ['I wrote this note today', 'It was an excellent note.', now], 62 | ]; 63 | 64 | async function seed() { 65 | await pool.query(dropTableStatement); 66 | await pool.query(createTableStatement); 67 | const res = await Promise.all( 68 | seedData.map((row) => pool.query(insertNoteStatement, row)) 69 | ); 70 | 71 | const oldNotes = await readdir(path.resolve(NOTES_PATH)); 72 | await Promise.all( 73 | oldNotes 74 | .filter((filename) => filename.endsWith('.md')) 75 | .map((filename) => unlink(path.resolve(NOTES_PATH, filename))) 76 | ); 77 | 78 | await Promise.all( 79 | res.map(({rows}) => { 80 | const id = rows[0].id; 81 | const content = rows[0].body; 82 | const data = new Uint8Array(Buffer.from(content)); 83 | return writeFile(path.resolve(NOTES_PATH, `${id}.md`), data, (err) => { 84 | if (err) { 85 | throw err; 86 | } 87 | }); 88 | }) 89 | ); 90 | } 91 | 92 | seed(); 93 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to make participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies within all project spaces, and it also applies when 49 | an individual is representing the project or its community in public spaces. 50 | Examples of representing a project or community include using an official 51 | project e-mail address, posting via an official social media account, or acting 52 | as an appointed representative at an online or offline event. Representation of 53 | a project may be further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at . All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /server/api.server.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) Facebook, Inc. and its affiliates. 3 | * 4 | * This source code is licensed under the MIT license found in the 5 | * LICENSE file in the root directory of this source tree. 6 | * 7 | */ 8 | 9 | 'use strict'; 10 | 11 | const register = require('react-server-dom-webpack/node-register'); 12 | register(); 13 | const babelRegister = require('@babel/register'); 14 | 15 | babelRegister({ 16 | ignore: [/[\\\/](build|server|node_modules)[\\\/]/], 17 | presets: [['react-app', {runtime: 'automatic'}]], 18 | plugins: ['@babel/transform-modules-commonjs'], 19 | }); 20 | 21 | const express = require('express'); 22 | const compress = require('compression'); 23 | const {readFileSync} = require('fs'); 24 | const {unlink, writeFile} = require('fs/promises'); 25 | const {pipeToNodeWritable} = require('react-server-dom-webpack/writer'); 26 | const path = require('path'); 27 | const {Pool} = require('pg'); 28 | const React = require('react'); 29 | const ReactApp = require('../src/App.server').default; 30 | 31 | // Don't keep credentials in the source tree in a real app! 32 | const pool = new Pool(require('../credentials')); 33 | 34 | const PORT = 4000; 35 | const app = express(); 36 | 37 | app.use(compress()); 38 | app.use(express.json()); 39 | 40 | app.listen(PORT, () => { 41 | console.log('React Notes listening at 4000...'); 42 | }); 43 | 44 | function handleErrors(fn) { 45 | return async function(req, res, next) { 46 | try { 47 | return await fn(req, res); 48 | } catch (x) { 49 | next(x); 50 | } 51 | }; 52 | } 53 | 54 | app.get( 55 | '/', 56 | handleErrors(async function(_req, res) { 57 | await waitForWebpack(); 58 | const html = readFileSync( 59 | path.resolve(__dirname, '../build/index.html'), 60 | 'utf8' 61 | ); 62 | // Note: this is sending an empty HTML shell, like a client-side-only app. 63 | // However, the intended solution (which isn't built out yet) is to read 64 | // from the Server endpoint and turn its response into an HTML stream. 65 | res.send(html); 66 | }) 67 | ); 68 | 69 | async function renderReactTree(res, props) { 70 | await waitForWebpack(); 71 | const manifest = readFileSync( 72 | path.resolve(__dirname, '../build/react-client-manifest.json'), 73 | 'utf8' 74 | ); 75 | const moduleMap = JSON.parse(manifest); 76 | pipeToNodeWritable(React.createElement(ReactApp, props), res, moduleMap); 77 | } 78 | 79 | function sendResponse(req, res, redirectToId) { 80 | const location = JSON.parse(req.query.location); 81 | if (redirectToId) { 82 | location.selectedId = redirectToId; 83 | } 84 | res.set('X-Location', JSON.stringify(location)); 85 | renderReactTree(res, { 86 | selectedId: location.selectedId, 87 | isEditing: location.isEditing, 88 | searchText: location.searchText, 89 | }); 90 | } 91 | 92 | app.get('/react', function(req, res) { 93 | sendResponse(req, res, null); 94 | }); 95 | 96 | const NOTES_PATH = path.resolve(__dirname, '../notes'); 97 | 98 | app.post( 99 | '/notes', 100 | handleErrors(async function(req, res) { 101 | const now = new Date(); 102 | const result = await pool.query( 103 | 'insert into notes (title, body, created_at, updated_at) values ($1, $2, $3, $3) returning id', 104 | [req.body.title, req.body.body, now] 105 | ); 106 | const insertedId = result.rows[0].id; 107 | await writeFile( 108 | path.resolve(NOTES_PATH, `${insertedId}.md`), 109 | req.body.body, 110 | 'utf8' 111 | ); 112 | sendResponse(req, res, insertedId); 113 | }) 114 | ); 115 | 116 | app.put( 117 | '/notes/:id', 118 | handleErrors(async function(req, res) { 119 | const now = new Date(); 120 | const updatedId = Number(req.params.id); 121 | await pool.query( 122 | 'update notes set title = $1, body = $2, updated_at = $3 where id = $4', 123 | [req.body.title, req.body.body, now, updatedId] 124 | ); 125 | await writeFile( 126 | path.resolve(NOTES_PATH, `${updatedId}.md`), 127 | req.body.body, 128 | 'utf8' 129 | ); 130 | sendResponse(req, res, null); 131 | }) 132 | ); 133 | 134 | app.delete( 135 | '/notes/:id', 136 | handleErrors(async function(req, res) { 137 | await pool.query('delete from notes where id = $1', [req.params.id]); 138 | await unlink(path.resolve(NOTES_PATH, `${req.params.id}.md`)); 139 | sendResponse(req, res, null); 140 | }) 141 | ); 142 | 143 | app.get( 144 | '/notes', 145 | handleErrors(async function(_req, res) { 146 | const {rows} = await pool.query('select * from notes order by id desc'); 147 | res.json(rows); 148 | }) 149 | ); 150 | 151 | app.get( 152 | '/notes/:id', 153 | handleErrors(async function(req, res) { 154 | const {rows} = await pool.query('select * from notes where id = $1', [ 155 | req.params.id, 156 | ]); 157 | res.json(rows[0]); 158 | }) 159 | ); 160 | 161 | app.get('/sleep/:ms', function(req, res) { 162 | setTimeout(() => { 163 | res.json({ok: true}); 164 | }, req.params.ms); 165 | }); 166 | 167 | app.use(express.static('build')); 168 | app.use(express.static('public')); 169 | 170 | app.on('error', function(error) { 171 | if (error.syscall !== 'listen') { 172 | throw error; 173 | } 174 | var bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port; 175 | switch (error.code) { 176 | case 'EACCES': 177 | console.error(bind + ' requires elevated privileges'); 178 | process.exit(1); 179 | break; 180 | case 'EADDRINUSE': 181 | console.error(bind + ' is already in use'); 182 | process.exit(1); 183 | break; 184 | default: 185 | throw error; 186 | } 187 | }); 188 | 189 | async function waitForWebpack() { 190 | while (true) { 191 | try { 192 | readFileSync(path.resolve(__dirname, '../build/index.html')); 193 | return; 194 | } catch (err) { 195 | console.log( 196 | 'Could not find webpack build output. Will retry in a second...' 197 | ); 198 | await new Promise((resolve) => setTimeout(resolve, 1000)); 199 | } 200 | } 201 | } 202 | --------------------------------------------------------------------------------