From bef30a003cc65a3f3aea3e86d17e6478594305a3 Mon Sep 17 00:00:00 2001 From: Luke Bunselmeyer Date: Sat, 6 May 2023 10:36:27 -0400 Subject: [PATCH] Initial commit of scaffolded project. For details see https://github.com/remix-run/indie-stack. --- .dockerignore | 7 + .env.example | 2 + .eslintrc.js | 22 + .github/workflows/deploy.yml | 145 + .gitignore | 10 + .gitpod.Dockerfile | 9 + .gitpod.yml | 48 + .npmrc | 1 + .prettierignore | 7 + Dockerfile | 61 + README.md | 180 + app/db.server.ts | 23 + app/entry.client.tsx | 18 + app/entry.server.tsx | 120 + app/models/note.server.ts | 52 + app/models/user.server.ts | 62 + app/root.tsx | 42 + app/routes/_index.tsx | 141 + app/routes/healthcheck.tsx | 25 + app/routes/join.tsx | 166 + app/routes/login.tsx | 175 + app/routes/logout.tsx | 8 + app/routes/notes.$noteId.tsx | 70 + app/routes/notes._index.tsx | 12 + app/routes/notes.new.tsx | 109 + app/routes/notes.tsx | 70 + app/session.server.ts | 97 + app/tailwind.css | 3 + app/utils.test.ts | 13 + app/utils.ts | 71 + cypress.config.ts | 27 + cypress/.eslintrc.js | 6 + cypress/e2e/smoke.cy.ts | 51 + cypress/fixtures/example.json | 5 + cypress/support/commands.ts | 95 + cypress/support/create-user.ts | 48 + cypress/support/delete-user.ts | 37 + cypress/support/e2e.ts | 15 + cypress/tsconfig.json | 29 + fly.toml | 50 + mocks/README.md | 7 + mocks/index.js | 9 + package-lock.json | 16470 ++++++++++++++++ package.json | 84 + postcss.config.js | 6 + .../20220713162558_init/migration.sql | 31 + prisma/migrations/migration_lock.toml | 3 + prisma/schema.prisma | 38 + prisma/seed.ts | 53 + public/favicon.ico | Bin 0 -> 16958 bytes remix.config.js | 13 + remix.env.d.ts | 2 + start.sh | 10 + tailwind.config.ts | 9 + test/setup-test-env.ts | 4 + tsconfig.json | 26 + vitest.config.ts | 15 + 57 files changed, 18912 insertions(+) create mode 100644 .dockerignore create mode 100644 .env.example create mode 100644 .eslintrc.js create mode 100644 .github/workflows/deploy.yml create mode 100644 .gitignore create mode 100644 .gitpod.Dockerfile create mode 100644 .gitpod.yml create mode 100644 .npmrc create mode 100644 .prettierignore create mode 100644 Dockerfile create mode 100644 README.md create mode 100644 app/db.server.ts create mode 100644 app/entry.client.tsx create mode 100644 app/entry.server.tsx create mode 100644 app/models/note.server.ts create mode 100644 app/models/user.server.ts create mode 100644 app/root.tsx create mode 100644 app/routes/_index.tsx create mode 100644 app/routes/healthcheck.tsx create mode 100644 app/routes/join.tsx create mode 100644 app/routes/login.tsx create mode 100644 app/routes/logout.tsx create mode 100644 app/routes/notes.$noteId.tsx create mode 100644 app/routes/notes._index.tsx create mode 100644 app/routes/notes.new.tsx create mode 100644 app/routes/notes.tsx create mode 100644 app/session.server.ts create mode 100644 app/tailwind.css create mode 100644 app/utils.test.ts create mode 100644 app/utils.ts create mode 100644 cypress.config.ts create mode 100644 cypress/.eslintrc.js create mode 100644 cypress/e2e/smoke.cy.ts create mode 100644 cypress/fixtures/example.json create mode 100644 cypress/support/commands.ts create mode 100644 cypress/support/create-user.ts create mode 100644 cypress/support/delete-user.ts create mode 100644 cypress/support/e2e.ts create mode 100644 cypress/tsconfig.json create mode 100644 fly.toml create mode 100644 mocks/README.md create mode 100644 mocks/index.js create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 postcss.config.js create mode 100644 prisma/migrations/20220713162558_init/migration.sql create mode 100644 prisma/migrations/migration_lock.toml create mode 100644 prisma/schema.prisma create mode 100644 prisma/seed.ts create mode 100644 public/favicon.ico create mode 100644 remix.config.js create mode 100644 remix.env.d.ts create mode 100755 start.sh create mode 100644 tailwind.config.ts create mode 100644 test/setup-test-env.ts create mode 100644 tsconfig.json create mode 100644 vitest.config.ts diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..91077d0 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,7 @@ +/node_modules +*.log +.DS_Store +.env +/.cache +/public/build +/build diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..0d0e0d6 --- /dev/null +++ b/.env.example @@ -0,0 +1,2 @@ +DATABASE_URL="file:./data.db?connection_limit=1" +SESSION_SECRET="super-duper-s3cret" diff --git a/.eslintrc.js b/.eslintrc.js new file mode 100644 index 0000000..3693886 --- /dev/null +++ b/.eslintrc.js @@ -0,0 +1,22 @@ +/** @type {import('eslint').Linter.Config} */ +module.exports = { + root: true, + extends: [ + "@remix-run/eslint-config", + "@remix-run/eslint-config/node", + "@remix-run/eslint-config/jest-testing-library", + "prettier", + ], + env: { + "cypress/globals": true, + }, + plugins: ["cypress"], + // we're using vitest which has a very similar API to jest + // (so the linting plugins work nicely), but it means we have to explicitly + // set the jest version. + settings: { + jest: { + version: 28, + }, + }, +}; diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml new file mode 100644 index 0000000..25aa9e0 --- /dev/null +++ b/.github/workflows/deploy.yml @@ -0,0 +1,145 @@ +name: 🚀 Deploy + +on: + push: + branches: + - main + - dev + pull_request: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: + actions: write + contents: read + +jobs: + lint: + name: ⬣ ESLint + runs-on: ubuntu-latest + steps: + - name: ⬇️ Checkout repo + uses: actions/checkout@v3 + + - name: ⎔ Setup node + uses: actions/setup-node@v3 + with: + cache: npm + cache-dependency-path: ./package.json + node-version: 18 + + - name: 📥 Install deps + run: npm install + + - name: 🔬 Lint + run: npm run lint + + typecheck: + name: ʦ TypeScript + runs-on: ubuntu-latest + steps: + - name: ⬇️ Checkout repo + uses: actions/checkout@v3 + + - name: ⎔ Setup node + uses: actions/setup-node@v3 + with: + cache: npm + cache-dependency-path: ./package.json + node-version: 18 + + - name: 📥 Install deps + run: npm install + + - name: 🔎 Type check + run: npm run typecheck --if-present + + vitest: + name: ⚡ Vitest + runs-on: ubuntu-latest + steps: + - name: ⬇️ Checkout repo + uses: actions/checkout@v3 + + - name: ⎔ Setup node + uses: actions/setup-node@v3 + with: + cache: npm + cache-dependency-path: ./package.json + node-version: 18 + + - name: 📥 Install deps + run: npm install + + - name: ⚡ Run vitest + run: npm run test -- --coverage + + cypress: + name: ⚫️ Cypress + runs-on: ubuntu-latest + steps: + - name: ⬇️ Checkout repo + uses: actions/checkout@v3 + + - name: 🏄 Copy test env vars + run: cp .env.example .env + + - name: ⎔ Setup node + uses: actions/setup-node@v3 + with: + cache: npm + cache-dependency-path: ./package.json + node-version: 18 + + - name: 📥 Install deps + run: npm install + + - name: 🛠 Setup Database + run: npx prisma migrate reset --force + + - name: ⚙️ Build + run: npm run build + + - name: 🌳 Cypress run + uses: cypress-io/github-action@v5 + with: + start: npm run start:mocks + wait-on: http://localhost:8811 + env: + PORT: 8811 + + deploy: + name: 🚀 Deploy + runs-on: ubuntu-latest + needs: [lint, typecheck, vitest, cypress] + # only build/deploy main branch on pushes + if: ${{ (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/dev') && github.event_name == 'push' }} + + steps: + - name: ⬇️ Checkout repo + uses: actions/checkout@v3 + + - name: 👀 Read app name + uses: SebRollen/toml-action@v1.0.2 + id: app_name + with: + file: fly.toml + field: app + + - name: 🚀 Deploy Staging + if: ${{ github.ref == 'refs/heads/dev' }} + uses: superfly/flyctl-actions@1.3 + with: + args: deploy --remote-only --build-arg COMMIT_SHA=${{ github.sha }} --app ${{ steps.app_name.outputs.value }}-staging + env: + FLY_API_TOKEN: ${{ secrets.FLY_API_TOKEN }} + + - name: 🚀 Deploy Production + if: ${{ github.ref == 'refs/heads/main' }} + uses: superfly/flyctl-actions@1.3 + with: + args: deploy --remote-only --build-arg COMMIT_SHA=${{ github.sha }} --app ${{ steps.app_name.outputs.value }} + env: + FLY_API_TOKEN: ${{ secrets.FLY_API_TOKEN }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..38e2467 --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +node_modules + +/build +/public/build +.env + +/cypress/screenshots +/cypress/videos +/prisma/data.db +/prisma/data.db-journal diff --git a/.gitpod.Dockerfile b/.gitpod.Dockerfile new file mode 100644 index 0000000..e52ca2d --- /dev/null +++ b/.gitpod.Dockerfile @@ -0,0 +1,9 @@ +FROM gitpod/workspace-full + +# Install Fly +RUN curl -L https://fly.io/install.sh | sh +ENV FLYCTL_INSTALL="/home/gitpod/.fly" +ENV PATH="$FLYCTL_INSTALL/bin:$PATH" + +# Install GitHub CLI +RUN brew install gh diff --git a/.gitpod.yml b/.gitpod.yml new file mode 100644 index 0000000..f07c562 --- /dev/null +++ b/.gitpod.yml @@ -0,0 +1,48 @@ +# https://www.gitpod.io/docs/config-gitpod-file + +image: + file: .gitpod.Dockerfile + +ports: + - port: 3000 + onOpen: notify + +tasks: + - name: Restore .env file + command: | + if [ -f .env ]; then + # If this workspace already has a .env, don't override it + # Local changes survive a workspace being opened and closed + # but they will not persist between separate workspaces for the same repo + + echo "Found .env in workspace" + else + # There is no .env + if [ ! -n "${ENV}" ]; then + # There is no $ENV from a previous workspace + # Default to the example .env + echo "Setting example .env" + + cp .env.example .env + else + # After making changes to .env, run this line to persist it to $ENV + # eval $(gp env -e ENV="$(base64 .env | tr -d '\n')") + # + # Environment variables set this way are shared between all your workspaces for this repo + # The lines below will read $ENV and print a .env file + + echo "Restoring .env from Gitpod" + + echo "${ENV}" | base64 -d | tee .env > /dev/null + fi + fi + + - init: npm install + command: npm run setup && npm run dev + +vscode: + extensions: + - ms-azuretools.vscode-docker + - esbenp.prettier-vscode + - dbaeumer.vscode-eslint + - bradlc.vscode-tailwindcss diff --git a/.npmrc b/.npmrc new file mode 100644 index 0000000..521a9f7 --- /dev/null +++ b/.npmrc @@ -0,0 +1 @@ +legacy-peer-deps=true diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..8cb6bcb --- /dev/null +++ b/.prettierignore @@ -0,0 +1,7 @@ +node_modules + +/build +/public/build +.env + +/app/styles/tailwind.css diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..d1d0a13 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,61 @@ +# base node image +FROM node:16-bullseye-slim as base + +# set for base and all layer that inherit from it +ENV NODE_ENV production + +# Install openssl for Prisma +RUN apt-get update && apt-get install -y openssl sqlite3 + +# Install all node_modules, including dev dependencies +FROM base as deps + +WORKDIR /myapp + +ADD package.json package-lock.json .npmrc ./ +RUN npm install --production=false + +# Setup production node_modules +FROM base as production-deps + +WORKDIR /myapp + +COPY --from=deps /myapp/node_modules /myapp/node_modules +ADD package.json package-lock.json .npmrc ./ +RUN npm prune --production + +# Build the app +FROM base as build + +WORKDIR /myapp + +COPY --from=deps /myapp/node_modules /myapp/node_modules + +ADD prisma . +RUN npx prisma generate + +ADD . . +RUN npm run build + +# Finally, build the production image with minimal footprint +FROM base + +ENV DATABASE_URL=file:/data/sqlite.db +ENV PORT="8080" +ENV NODE_ENV="production" + +# add shortcut for connecting to database CLI +RUN echo "#!/bin/sh\nset -x\nsqlite3 \$DATABASE_URL" > /usr/local/bin/database-cli && chmod +x /usr/local/bin/database-cli + +WORKDIR /myapp + +COPY --from=production-deps /myapp/node_modules /myapp/node_modules +COPY --from=build /myapp/node_modules/.prisma /myapp/node_modules/.prisma + +COPY --from=build /myapp/build /myapp/build +COPY --from=build /myapp/public /myapp/public +COPY --from=build /myapp/package.json /myapp/package.json +COPY --from=build /myapp/start.sh /myapp/start.sh +COPY --from=build /myapp/prisma /myapp/prisma + +ENTRYPOINT [ "./start.sh" ] diff --git a/README.md b/README.md new file mode 100644 index 0000000..7394b8a --- /dev/null +++ b/README.md @@ -0,0 +1,180 @@ +# Remix Indie Stack + +![The Remix Indie Stack](https://repository-images.githubusercontent.com/465928257/a241fa49-bd4d-485a-a2a5-5cb8e4ee0abf) + +Learn more about [Remix Stacks](https://remix.run/stacks). + +```sh +npx create-remix@latest --template remix-run/indie-stack +``` + +## What's in the stack + +- [Fly app deployment](https://fly.io) with [Docker](https://www.docker.com/) +- Production-ready [SQLite Database](https://sqlite.org) +- Healthcheck endpoint for [Fly backups region fallbacks](https://fly.io/docs/reference/configuration/#services-http_checks) +- [GitHub Actions](https://github.com/features/actions) for deploy on merge to production and staging environments +- Email/Password Authentication with [cookie-based sessions](https://remix.run/utils/sessions#md-createcookiesessionstorage) +- Database ORM with [Prisma](https://prisma.io) +- Styling with [Tailwind](https://tailwindcss.com/) +- End-to-end testing with [Cypress](https://cypress.io) +- Local third party request mocking with [MSW](https://mswjs.io) +- Unit testing with [Vitest](https://vitest.dev) and [Testing Library](https://testing-library.com) +- Code formatting with [Prettier](https://prettier.io) +- Linting with [ESLint](https://eslint.org) +- Static Types with [TypeScript](https://typescriptlang.org) + +Not a fan of bits of the stack? Fork it, change it, and use `npx create-remix --template your/repo`! Make it your own. + +## Quickstart + +Click this button to create a [Gitpod](https://gitpod.io) workspace with the project set up and Fly pre-installed + +[![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/remix-run/indie-stack/tree/main) + +## Development + +- This step only applies if you've opted out of having the CLI install dependencies for you: + + ```sh + npx remix init + ``` + +- Initial setup: _If you just generated this project, this step has been done for you._ + + ```sh + npm run setup + ``` + +- Start dev server: + + ```sh + npm run dev + ``` + +This starts your app in development mode, rebuilding assets on file changes. + +The database seed script creates a new user with some data you can use to get started: + +- Email: `rachel@remix.run` +- Password: `racheliscool` + +### Relevant code: + +This is a pretty simple note-taking app, but it's a good example of how you can build a full stack app with Prisma and Remix. The main functionality is creating users, logging in and out, and creating and deleting notes. + +- creating users, and logging in and out [./app/models/user.server.ts](./app/models/user.server.ts) +- user sessions, and verifying them [./app/session.server.ts](./app/session.server.ts) +- creating, and deleting notes [./app/models/note.server.ts](./app/models/note.server.ts) + +## Deployment + +This Remix Stack comes with two GitHub Actions that handle automatically deploying your app to production and staging environments. + +Prior to your first deployment, you'll need to do a few things: + +- [Install Fly](https://fly.io/docs/getting-started/installing-flyctl/) + +- Sign up and log in to Fly + + ```sh + fly auth signup + ``` + + > **Note:** If you have more than one Fly account, ensure that you are signed into the same account in the Fly CLI as you are in the browser. In your terminal, run `fly auth whoami` and ensure the email matches the Fly account signed into the browser. + +- Create two apps on Fly, one for staging and one for production: + + ```sh + fly apps create tunein-radio-stations-1ae3 + fly apps create tunein-radio-stations-1ae3-staging + ``` + + > **Note:** Make sure this name matches the `app` set in your `fly.toml` file. Otherwise, you will not be able to deploy. + + - Initialize Git. + + ```sh + git init + ``` + +- Create a new [GitHub Repository](https://repo.new), and then add it as the remote for your project. **Do not push your app yet!** + + ```sh + git remote add origin + ``` + +- Add a `FLY_API_TOKEN` to your GitHub repo. To do this, go to your user settings on Fly and create a new [token](https://web.fly.io/user/personal_access_tokens/new), then add it to [your repo secrets](https://docs.github.com/en/actions/security-guides/encrypted-secrets) with the name `FLY_API_TOKEN`. + +- Add a `SESSION_SECRET` to your fly app secrets, to do this you can run the following commands: + + ```sh + fly secrets set SESSION_SECRET=$(openssl rand -hex 32) --app tunein-radio-stations-1ae3 + fly secrets set SESSION_SECRET=$(openssl rand -hex 32) --app tunein-radio-stations-1ae3-staging + ``` + + If you don't have openssl installed, you can also use [1Password](https://1password.com/password-generator) to generate a random secret, just replace `$(openssl rand -hex 32)` with the generated secret. + +- Create a persistent volume for the sqlite database for both your staging and production environments. Run the following: + + ```sh + fly volumes create data --size 1 --app tunein-radio-stations-1ae3 + fly volumes create data --size 1 --app tunein-radio-stations-1ae3-staging + ``` + +Now that everything is set up you can commit and push your changes to your repo. Every commit to your `main` branch will trigger a deployment to your production environment, and every commit to your `dev` branch will trigger a deployment to your staging environment. + +### Connecting to your database + +The sqlite database lives at `/data/sqlite.db` in your deployed application. You can connect to the live database by running `fly ssh console -C database-cli`. + +### Getting Help with Deployment + +If you run into any issues deploying to Fly, make sure you've followed all of the steps above and if you have, then post as many details about your deployment (including your app name) to [the Fly support community](https://community.fly.io). They're normally pretty responsive over there and hopefully can help resolve any of your deployment issues and questions. + +## GitHub Actions + +We use GitHub Actions for continuous integration and deployment. Anything that gets into the `main` branch will be deployed to production after running tests/build/etc. Anything in the `dev` branch will be deployed to staging. + +## Testing + +### Cypress + +We use Cypress for our End-to-End tests in this project. You'll find those in the `cypress` directory. As you make changes, add to an existing file or create a new file in the `cypress/e2e` directory to test your changes. + +We use [`@testing-library/cypress`](https://testing-library.com/cypress) for selecting elements on the page semantically. + +To run these tests in development, run `npm run test:e2e:dev` which will start the dev server for the app as well as the Cypress client. Make sure the database is running in docker as described above. + +We have a utility for testing authenticated features without having to go through the login flow: + +```ts +cy.login(); +// you are now logged in as a new user +``` + +We also have a utility to auto-delete the user at the end of your test. Just make sure to add this in each test file: + +```ts +afterEach(() => { + cy.cleanupUser(); +}); +``` + +That way, we can keep your local db clean and keep your tests isolated from one another. + +### Vitest + +For lower level tests of utilities and individual components, we use `vitest`. We have DOM-specific assertion helpers via [`@testing-library/jest-dom`](https://testing-library.com/jest-dom). + +### Type Checking + +This project uses TypeScript. It's recommended to get TypeScript set up for your editor to get a really great in-editor experience with type checking and auto-complete. To run type checking across the whole project, run `npm run typecheck`. + +### Linting + +This project uses ESLint for linting. That is configured in `.eslintrc.js`. + +### Formatting + +We use [Prettier](https://prettier.io/) for auto-formatting in this project. It's recommended to install an editor plugin (like the [VSCode Prettier plugin](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode)) to get auto-formatting on save. There's also a `npm run format` script you can run to format all files in the project. diff --git a/app/db.server.ts b/app/db.server.ts new file mode 100644 index 0000000..643c762 --- /dev/null +++ b/app/db.server.ts @@ -0,0 +1,23 @@ +import { PrismaClient } from "@prisma/client"; + +let prisma: PrismaClient; + +declare global { + var __db__: PrismaClient | undefined; +} + +// This is needed because in development we don't want to restart +// the server with every change, but we want to make sure we don't +// create a new connection to the DB with every change either. +// In production, we'll have a single connection to the DB. +if (process.env.NODE_ENV === "production") { + prisma = new PrismaClient(); +} else { + if (!global.__db__) { + global.__db__ = new PrismaClient(); + } + prisma = global.__db__; + prisma.$connect(); +} + +export { prisma }; diff --git a/app/entry.client.tsx b/app/entry.client.tsx new file mode 100644 index 0000000..36f2e51 --- /dev/null +++ b/app/entry.client.tsx @@ -0,0 +1,18 @@ +/** + * By default, Remix will handle hydrating your app on the client for you. + * You are free to delete this file if you'd like to, but if you ever want it revealed again, you can run `npx remix reveal` ✨ + * For more information, see https://remix.run/docs/en/main/file-conventions/entry.client + */ + +import { RemixBrowser } from "@remix-run/react"; +import { startTransition, StrictMode } from "react"; +import { hydrateRoot } from "react-dom/client"; + +startTransition(() => { + hydrateRoot( + document, + + + + ); +}); diff --git a/app/entry.server.tsx b/app/entry.server.tsx new file mode 100644 index 0000000..a39b156 --- /dev/null +++ b/app/entry.server.tsx @@ -0,0 +1,120 @@ +/** + * By default, Remix will handle generating the HTTP Response for you. + * You are free to delete this file if you'd like to, but if you ever want it revealed again, you can run `npx remix reveal` ✨ + * For more information, see https://remix.run/docs/en/main/file-conventions/entry.server + */ + +import { PassThrough } from "node:stream"; + +import type { EntryContext } from "@remix-run/node"; +import { Response } from "@remix-run/node"; +import { RemixServer } from "@remix-run/react"; +import isbot from "isbot"; +import { renderToPipeableStream } from "react-dom/server"; + +const ABORT_DELAY = 5_000; + +export default function handleRequest( + request: Request, + responseStatusCode: number, + responseHeaders: Headers, + remixContext: EntryContext +) { + return isbot(request.headers.get("user-agent")) + ? handleBotRequest( + request, + responseStatusCode, + responseHeaders, + remixContext + ) + : handleBrowserRequest( + request, + responseStatusCode, + responseHeaders, + remixContext + ); +} + +function handleBotRequest( + request: Request, + responseStatusCode: number, + responseHeaders: Headers, + remixContext: EntryContext +) { + return new Promise((resolve, reject) => { + const { pipe, abort } = renderToPipeableStream( + , + { + onAllReady() { + const body = new PassThrough(); + + responseHeaders.set("Content-Type", "text/html"); + + resolve( + new Response(body, { + headers: responseHeaders, + status: responseStatusCode, + }) + ); + + pipe(body); + }, + onShellError(error: unknown) { + reject(error); + }, + onError(error: unknown) { + responseStatusCode = 500; + console.error(error); + }, + } + ); + + setTimeout(abort, ABORT_DELAY); + }); +} + +function handleBrowserRequest( + request: Request, + responseStatusCode: number, + responseHeaders: Headers, + remixContext: EntryContext +) { + return new Promise((resolve, reject) => { + const { pipe, abort } = renderToPipeableStream( + , + { + onShellReady() { + const body = new PassThrough(); + + responseHeaders.set("Content-Type", "text/html"); + + resolve( + new Response(body, { + headers: responseHeaders, + status: responseStatusCode, + }) + ); + + pipe(body); + }, + onShellError(error: unknown) { + reject(error); + }, + onError(error: unknown) { + console.error(error); + responseStatusCode = 500; + }, + } + ); + + setTimeout(abort, ABORT_DELAY); + }); +} diff --git a/app/models/note.server.ts b/app/models/note.server.ts new file mode 100644 index 0000000..f385491 --- /dev/null +++ b/app/models/note.server.ts @@ -0,0 +1,52 @@ +import type { User, Note } from "@prisma/client"; + +import { prisma } from "~/db.server"; + +export function getNote({ + id, + userId, +}: Pick & { + userId: User["id"]; +}) { + return prisma.note.findFirst({ + select: { id: true, body: true, title: true }, + where: { id, userId }, + }); +} + +export function getNoteListItems({ userId }: { userId: User["id"] }) { + return prisma.note.findMany({ + where: { userId }, + select: { id: true, title: true }, + orderBy: { updatedAt: "desc" }, + }); +} + +export function createNote({ + body, + title, + userId, +}: Pick & { + userId: User["id"]; +}) { + return prisma.note.create({ + data: { + title, + body, + user: { + connect: { + id: userId, + }, + }, + }, + }); +} + +export function deleteNote({ + id, + userId, +}: Pick & { userId: User["id"] }) { + return prisma.note.deleteMany({ + where: { id, userId }, + }); +} diff --git a/app/models/user.server.ts b/app/models/user.server.ts new file mode 100644 index 0000000..cce401e --- /dev/null +++ b/app/models/user.server.ts @@ -0,0 +1,62 @@ +import type { Password, User } from "@prisma/client"; +import bcrypt from "bcryptjs"; + +import { prisma } from "~/db.server"; + +export type { User } from "@prisma/client"; + +export async function getUserById(id: User["id"]) { + return prisma.user.findUnique({ where: { id } }); +} + +export async function getUserByEmail(email: User["email"]) { + return prisma.user.findUnique({ where: { email } }); +} + +export async function createUser(email: User["email"], password: string) { + const hashedPassword = await bcrypt.hash(password, 10); + + return prisma.user.create({ + data: { + email, + password: { + create: { + hash: hashedPassword, + }, + }, + }, + }); +} + +export async function deleteUserByEmail(email: User["email"]) { + return prisma.user.delete({ where: { email } }); +} + +export async function verifyLogin( + email: User["email"], + password: Password["hash"] +) { + const userWithPassword = await prisma.user.findUnique({ + where: { email }, + include: { + password: true, + }, + }); + + if (!userWithPassword || !userWithPassword.password) { + return null; + } + + const isValid = await bcrypt.compare( + password, + userWithPassword.password.hash + ); + + if (!isValid) { + return null; + } + + const { password: _password, ...userWithoutPassword } = userWithPassword; + + return userWithoutPassword; +} diff --git a/app/root.tsx b/app/root.tsx new file mode 100644 index 0000000..fafef27 --- /dev/null +++ b/app/root.tsx @@ -0,0 +1,42 @@ +import { cssBundleHref } from "@remix-run/css-bundle"; +import type { LinksFunction, LoaderArgs } from "@remix-run/node"; +import { json } from "@remix-run/node"; +import { + Links, + LiveReload, + Meta, + Outlet, + Scripts, + ScrollRestoration, +} from "@remix-run/react"; + +import { getUser } from "~/session.server"; +import stylesheet from "~/tailwind.css"; + +export const links: LinksFunction = () => [ + { rel: "stylesheet", href: stylesheet }, + ...(cssBundleHref ? [{ rel: "stylesheet", href: cssBundleHref }] : []), +]; + +export const loader = async ({ request }: LoaderArgs) => { + return json({ user: await getUser(request) }); +}; + +export default function App() { + return ( + + + + + + + + + + + + + + + ); +} diff --git a/app/routes/_index.tsx b/app/routes/_index.tsx new file mode 100644 index 0000000..83e1f6b --- /dev/null +++ b/app/routes/_index.tsx @@ -0,0 +1,141 @@ +import type { V2_MetaFunction } from "@remix-run/node"; +import { Link } from "@remix-run/react"; + +import { useOptionalUser } from "~/utils"; + +export const meta: V2_MetaFunction = () => [{ title: "Remix Notes" }]; + +export default function Index() { + const user = useOptionalUser(); + return ( +
+
+
+
+
+ Sonic Youth On Stage +
+
+
+

+ + Indie Stack + +

+

+ Check the README.md file for instructions on how to get this + project deployed. +

+
+ {user ? ( + + View Notes for {user.email} + + ) : ( +
+ + Sign up + + + Log In + +
+ )} +
+ + Remix + +
+
+
+ +
+
+ {[ + { + src: "https://user-images.githubusercontent.com/1500684/157764397-ccd8ea10-b8aa-4772-a99b-35de937319e1.svg", + alt: "Fly.io", + href: "https://fly.io", + }, + { + src: "https://user-images.githubusercontent.com/1500684/157764395-137ec949-382c-43bd-a3c0-0cb8cb22e22d.svg", + alt: "SQLite", + href: "https://sqlite.org", + }, + { + src: "https://user-images.githubusercontent.com/1500684/157764484-ad64a21a-d7fb-47e3-8669-ec046da20c1f.svg", + alt: "Prisma", + href: "https://prisma.io", + }, + { + src: "https://user-images.githubusercontent.com/1500684/157764276-a516a239-e377-4a20-b44a-0ac7b65c8c14.svg", + alt: "Tailwind", + href: "https://tailwindcss.com", + }, + { + src: "https://user-images.githubusercontent.com/1500684/157764454-48ac8c71-a2a9-4b5e-b19c-edef8b8953d6.svg", + alt: "Cypress", + href: "https://www.cypress.io", + }, + { + src: "https://user-images.githubusercontent.com/1500684/157772386-75444196-0604-4340-af28-53b236faa182.svg", + alt: "MSW", + href: "https://mswjs.io", + }, + { + src: "https://user-images.githubusercontent.com/1500684/157772447-00fccdce-9d12-46a3-8bb4-fac612cdc949.svg", + alt: "Vitest", + href: "https://vitest.dev", + }, + { + src: "https://user-images.githubusercontent.com/1500684/157772662-92b0dd3a-453f-4d18-b8be-9fa6efde52cf.png", + alt: "Testing Library", + href: "https://testing-library.com", + }, + { + src: "https://user-images.githubusercontent.com/1500684/157772934-ce0a943d-e9d0-40f8-97f3-f464c0811643.svg", + alt: "Prettier", + href: "https://prettier.io", + }, + { + src: "https://user-images.githubusercontent.com/1500684/157772990-3968ff7c-b551-4c55-a25c-046a32709a8e.svg", + alt: "ESLint", + href: "https://eslint.org", + }, + { + src: "https://user-images.githubusercontent.com/1500684/157773063-20a0ed64-b9f8-4e0b-9d1e-0b65a3d4a6db.svg", + alt: "TypeScript", + href: "https://typescriptlang.org", + }, + ].map((img) => ( + + {img.alt} + + ))} +
+
+
+
+ ); +} diff --git a/app/routes/healthcheck.tsx b/app/routes/healthcheck.tsx new file mode 100644 index 0000000..6c520ce --- /dev/null +++ b/app/routes/healthcheck.tsx @@ -0,0 +1,25 @@ +// learn more: https://fly.io/docs/reference/configuration/#services-http_checks +import type { LoaderArgs } from "@remix-run/node"; + +import { prisma } from "~/db.server"; + +export const loader = async ({ request }: LoaderArgs) => { + const host = + request.headers.get("X-Forwarded-Host") ?? request.headers.get("host"); + + try { + const url = new URL("/", `http://${host}`); + // if we can connect to the database and make a simple query + // and make a HEAD request to ourselves, then we're good. + await Promise.all([ + prisma.user.count(), + fetch(url.toString(), { method: "HEAD" }).then((r) => { + if (!r.ok) return Promise.reject(r); + }), + ]); + return new Response("OK"); + } catch (error: unknown) { + console.log("healthcheck ❌", { error }); + return new Response("ERROR", { status: 500 }); + } +}; diff --git a/app/routes/join.tsx b/app/routes/join.tsx new file mode 100644 index 0000000..ccedff5 --- /dev/null +++ b/app/routes/join.tsx @@ -0,0 +1,166 @@ +import type { ActionArgs, LoaderArgs, V2_MetaFunction } from "@remix-run/node"; +import { json, redirect } from "@remix-run/node"; +import { Form, Link, useActionData, useSearchParams } from "@remix-run/react"; +import { useEffect, useRef } from "react"; + +import { createUser, getUserByEmail } from "~/models/user.server"; +import { createUserSession, getUserId } from "~/session.server"; +import { safeRedirect, validateEmail } from "~/utils"; + +export const loader = async ({ request }: LoaderArgs) => { + const userId = await getUserId(request); + if (userId) return redirect("/"); + return json({}); +}; + +export const action = async ({ request }: ActionArgs) => { + const formData = await request.formData(); + const email = formData.get("email"); + const password = formData.get("password"); + const redirectTo = safeRedirect(formData.get("redirectTo"), "/"); + + if (!validateEmail(email)) { + return json( + { errors: { email: "Email is invalid", password: null } }, + { status: 400 } + ); + } + + if (typeof password !== "string" || password.length === 0) { + return json( + { errors: { email: null, password: "Password is required" } }, + { status: 400 } + ); + } + + if (password.length < 8) { + return json( + { errors: { email: null, password: "Password is too short" } }, + { status: 400 } + ); + } + + const existingUser = await getUserByEmail(email); + if (existingUser) { + return json( + { + errors: { + email: "A user already exists with this email", + password: null, + }, + }, + { status: 400 } + ); + } + + const user = await createUser(email, password); + + return createUserSession({ + redirectTo, + remember: false, + request, + userId: user.id, + }); +}; + +export const meta: V2_MetaFunction = () => [{ title: "Sign Up" }]; + +export default function Join() { + const [searchParams] = useSearchParams(); + const redirectTo = searchParams.get("redirectTo") ?? undefined; + const actionData = useActionData(); + const emailRef = useRef(null); + const passwordRef = useRef(null); + + useEffect(() => { + if (actionData?.errors?.email) { + emailRef.current?.focus(); + } else if (actionData?.errors?.password) { + passwordRef.current?.focus(); + } + }, [actionData]); + + return ( +
+
+
+
+ +
+ + {actionData?.errors?.email ? ( +
+ {actionData.errors.email} +
+ ) : null} +
+
+ +
+ +
+ + {actionData?.errors?.password ? ( +
+ {actionData.errors.password} +
+ ) : null} +
+
+ + + +
+
+ Already have an account?{" "} + + Log in + +
+
+
+
+
+ ); +} diff --git a/app/routes/login.tsx b/app/routes/login.tsx new file mode 100644 index 0000000..25a8f92 --- /dev/null +++ b/app/routes/login.tsx @@ -0,0 +1,175 @@ +import type { ActionArgs, LoaderArgs, V2_MetaFunction } from "@remix-run/node"; +import { json, redirect } from "@remix-run/node"; +import { Form, Link, useActionData, useSearchParams } from "@remix-run/react"; +import { useEffect, useRef } from "react"; + +import { verifyLogin } from "~/models/user.server"; +import { createUserSession, getUserId } from "~/session.server"; +import { safeRedirect, validateEmail } from "~/utils"; + +export const loader = async ({ request }: LoaderArgs) => { + const userId = await getUserId(request); + if (userId) return redirect("/"); + return json({}); +}; + +export const action = async ({ request }: ActionArgs) => { + const formData = await request.formData(); + const email = formData.get("email"); + const password = formData.get("password"); + const redirectTo = safeRedirect(formData.get("redirectTo"), "/"); + const remember = formData.get("remember"); + + if (!validateEmail(email)) { + return json( + { errors: { email: "Email is invalid", password: null } }, + { status: 400 } + ); + } + + if (typeof password !== "string" || password.length === 0) { + return json( + { errors: { email: null, password: "Password is required" } }, + { status: 400 } + ); + } + + if (password.length < 8) { + return json( + { errors: { email: null, password: "Password is too short" } }, + { status: 400 } + ); + } + + const user = await verifyLogin(email, password); + + if (!user) { + return json( + { errors: { email: "Invalid email or password", password: null } }, + { status: 400 } + ); + } + + return createUserSession({ + redirectTo, + remember: remember === "on" ? true : false, + request, + userId: user.id, + }); +}; + +export const meta: V2_MetaFunction = () => [{ title: "Login" }]; + +export default function LoginPage() { + const [searchParams] = useSearchParams(); + const redirectTo = searchParams.get("redirectTo") || "/notes"; + const actionData = useActionData(); + const emailRef = useRef(null); + const passwordRef = useRef(null); + + useEffect(() => { + if (actionData?.errors?.email) { + emailRef.current?.focus(); + } else if (actionData?.errors?.password) { + passwordRef.current?.focus(); + } + }, [actionData]); + + return ( +
+
+
+
+ +
+ + {actionData?.errors?.email ? ( +
+ {actionData.errors.email} +
+ ) : null} +
+
+ +
+ +
+ + {actionData?.errors?.password ? ( +
+ {actionData.errors.password} +
+ ) : null} +
+
+ + + +
+
+ + +
+
+ Don't have an account?{" "} + + Sign up + +
+
+
+
+
+ ); +} diff --git a/app/routes/logout.tsx b/app/routes/logout.tsx new file mode 100644 index 0000000..541794d --- /dev/null +++ b/app/routes/logout.tsx @@ -0,0 +1,8 @@ +import type { ActionArgs } from "@remix-run/node"; +import { redirect } from "@remix-run/node"; + +import { logout } from "~/session.server"; + +export const action = async ({ request }: ActionArgs) => logout(request); + +export const loader = async () => redirect("/"); diff --git a/app/routes/notes.$noteId.tsx b/app/routes/notes.$noteId.tsx new file mode 100644 index 0000000..0f83fd8 --- /dev/null +++ b/app/routes/notes.$noteId.tsx @@ -0,0 +1,70 @@ +import type { ActionArgs, LoaderArgs } from "@remix-run/node"; +import { json, redirect } from "@remix-run/node"; +import { + Form, + isRouteErrorResponse, + useLoaderData, + useRouteError, +} from "@remix-run/react"; +import invariant from "tiny-invariant"; + +import { deleteNote, getNote } from "~/models/note.server"; +import { requireUserId } from "~/session.server"; + +export const loader = async ({ params, request }: LoaderArgs) => { + const userId = await requireUserId(request); + invariant(params.noteId, "noteId not found"); + + const note = await getNote({ id: params.noteId, userId }); + if (!note) { + throw new Response("Not Found", { status: 404 }); + } + return json({ note }); +}; + +export const action = async ({ params, request }: ActionArgs) => { + const userId = await requireUserId(request); + invariant(params.noteId, "noteId not found"); + + await deleteNote({ id: params.noteId, userId }); + + return redirect("/notes"); +}; + +export default function NoteDetailsPage() { + const data = useLoaderData(); + + return ( +
+

{data.note.title}

+

{data.note.body}

+
+
+ +
+
+ ); +} + +export function ErrorBoundary() { + const error = useRouteError(); + + if (error instanceof Error) { + return
An unexpected error occurred: {error.message}
; + } + + if (!isRouteErrorResponse(error)) { + return

Unknown Error

; + } + + if (error.status === 404) { + return
Note not found
; + } + + return
An unexpected error occurred: {error.statusText}
; +} diff --git a/app/routes/notes._index.tsx b/app/routes/notes._index.tsx new file mode 100644 index 0000000..aa858a9 --- /dev/null +++ b/app/routes/notes._index.tsx @@ -0,0 +1,12 @@ +import { Link } from "@remix-run/react"; + +export default function NoteIndexPage() { + return ( +

+ No note selected. Select a note on the left, or{" "} + + create a new note. + +

+ ); +} diff --git a/app/routes/notes.new.tsx b/app/routes/notes.new.tsx new file mode 100644 index 0000000..6afcf5c --- /dev/null +++ b/app/routes/notes.new.tsx @@ -0,0 +1,109 @@ +import type { ActionArgs } from "@remix-run/node"; +import { json, redirect } from "@remix-run/node"; +import { Form, useActionData } from "@remix-run/react"; +import { useEffect, useRef } from "react"; + +import { createNote } from "~/models/note.server"; +import { requireUserId } from "~/session.server"; + +export const action = async ({ request }: ActionArgs) => { + const userId = await requireUserId(request); + + const formData = await request.formData(); + const title = formData.get("title"); + const body = formData.get("body"); + + if (typeof title !== "string" || title.length === 0) { + return json( + { errors: { body: null, title: "Title is required" } }, + { status: 400 } + ); + } + + if (typeof body !== "string" || body.length === 0) { + return json( + { errors: { body: "Body is required", title: null } }, + { status: 400 } + ); + } + + const note = await createNote({ body, title, userId }); + + return redirect(`/notes/${note.id}`); +}; + +export default function NewNotePage() { + const actionData = useActionData(); + const titleRef = useRef(null); + const bodyRef = useRef(null); + + useEffect(() => { + if (actionData?.errors?.title) { + titleRef.current?.focus(); + } else if (actionData?.errors?.body) { + bodyRef.current?.focus(); + } + }, [actionData]); + + return ( +
+
+ + {actionData?.errors?.title ? ( +
+ {actionData.errors.title} +
+ ) : null} +
+ +
+