commit 52a0ba1b3b0e994b670e0c13d540d080593c0309 Author: Jane Petrovna Date: Tue Mar 22 13:42:07 2022 -0400 switch to remix 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..2259bc5 --- /dev/null +++ b/.env.example @@ -0,0 +1,2 @@ +DATABASE_URL="postgresql://postgres:postgres@localhost:5432/postgres" +SESSION_SECRET="super-duper-s3cret" diff --git a/.eslintrc.js b/.eslintrc.js new file mode 100644 index 0000000..81000a8 --- /dev/null +++ b/.eslintrc.js @@ -0,0 +1,19 @@ +/** + * @type {import('@types/eslint').Linter.BaseConfig} + */ +module.exports = { + extends: [ + "@remix-run/eslint-config", + "@remix-run/eslint-config/node", + "@remix-run/eslint-config/jest", + "prettier", + ], + // we're using vitest which has a very similar API to jest + // (so the linting plugins work nicely), but it we have to explicitly + // set the jest version. + settings: { + jest: { + version: 27, + }, + }, +}; diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml new file mode 100644 index 0000000..f60c169 --- /dev/null +++ b/.github/workflows/deploy.yml @@ -0,0 +1,211 @@ +name: 🚀 Deploy +on: + push: + branches: + - main + - dev + pull_request: {} + +jobs: + lint: + name: ⬣ ESLint + runs-on: ubuntu-latest + steps: + - name: 🛑 Cancel Previous Runs + uses: styfle/cancel-workflow-action@0.9.1 + + - name: ⬇️ Checkout repo + uses: actions/checkout@v3 + + - name: ⎔ Setup node + uses: actions/setup-node@v3 + with: + node-version: 16 + + - name: 📥 Download deps + uses: bahmutov/npm-install@v1 + + - name: 🔬 Lint + run: npm run lint + + typecheck: + name: ʦ TypeScript + runs-on: ubuntu-latest + steps: + - name: 🛑 Cancel Previous Runs + uses: styfle/cancel-workflow-action@0.9.1 + + - name: ⬇️ Checkout repo + uses: actions/checkout@v3 + + - name: ⎔ Setup node + uses: actions/setup-node@v3 + with: + node-version: 16 + + - name: 📥 Download deps + uses: bahmutov/npm-install@v1 + + - name: 🔎 Type check + run: npm run typecheck --if-present + + vitest: + name: ⚡ Vitest + runs-on: ubuntu-latest + steps: + - name: 🛑 Cancel Previous Runs + uses: styfle/cancel-workflow-action@0.9.1 + + - name: ⬇️ Checkout repo + uses: actions/checkout@v3 + + - name: ⎔ Setup node + uses: actions/setup-node@v3 + with: + node-version: 16 + + - name: 📥 Download deps + uses: bahmutov/npm-install@v1 + + - name: ⚡ Run vitest + run: npm run test -- --coverage + + cypress: + name: ⚫️ Cypress + runs-on: ubuntu-latest + steps: + - name: 🛑 Cancel Previous Runs + uses: styfle/cancel-workflow-action@0.9.1 + + - 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: + node-version: 16 + + - name: 📥 Download deps + uses: bahmutov/npm-install@v1 + + - name: 🐳 Docker compose + # the sleep is just there to give time for postgres to get started + run: docker-compose up -d && sleep 3 + env: + DATABASE_URL: "postgresql://postgres:postgres@localhost:5432/postgres" + + - name: 🛠 Setup Database + run: npx prisma migrate reset --force + + - name: 🌱 Seed the Database + run: npx prisma db seed + + - name: ⚙️ Build + run: npm run build + + - name: 🌳 Cypress run + uses: cypress-io/github-action@v3 + with: + start: npm run start:mocks + wait-on: "http://localhost:8811" + env: + PORT: "8811" + + build: + name: 🐳 Build + # only build/deploy main branch on pushes + if: ${{ (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/dev') && github.event_name == 'push' }} + runs-on: ubuntu-latest + steps: + - name: 🛑 Cancel Previous Runs + uses: styfle/cancel-workflow-action@0.9.1 + + - name: ⬇️ Checkout repo + uses: actions/checkout@v3 + + - name: 👀 Read app name + uses: SebRollen/toml-action@v1.0.0 + id: app_name + with: + file: "fly.toml" + field: "app" + + - name: 🐳 Set up Docker Buildx + uses: docker/setup-buildx-action@v1 + + # Setup cache + - name: ⚡️ Cache Docker layers + uses: actions/cache@v2 + with: + path: /tmp/.buildx-cache + key: ${{ runner.os }}-buildx-${{ github.sha }} + restore-keys: | + ${{ runner.os }}-buildx- + + - name: 🔑 Fly Registry Auth + uses: docker/login-action@v1 + with: + registry: registry.fly.io + username: x + password: ${{ secrets.FLY_API_TOKEN }} + + - name: 🐳 Docker build + uses: docker/build-push-action@v2 + with: + context: . + push: true + tags: registry.fly.io/${{ steps.app_name.outputs.value }}:${{ github.ref_name }}-${{ github.sha }} + build-args: | + COMMIT_SHA=${{ github.sha }} + cache-from: type=local,src=/tmp/.buildx-cache + cache-to: type=local,mode=max,dest=/tmp/.buildx-cache-new + + # This ugly bit is necessary if you don't want your cache to grow forever + # till it hits GitHub's limit of 5GB. + # Temp fix + # https://github.com/docker/build-push-action/issues/252 + # https://github.com/moby/buildkit/issues/1896 + - name: 🚚 Move cache + run: | + rm -rf /tmp/.buildx-cache + mv /tmp/.buildx-cache-new /tmp/.buildx-cache + + deploy: + name: 🚀 Deploy + runs-on: ubuntu-latest + needs: [lint, typecheck, vitest, cypress, build] + # only build/deploy main branch on pushes + if: ${{ (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/dev') && github.event_name == 'push' }} + + steps: + - name: 🛑 Cancel Previous Runs + uses: styfle/cancel-workflow-action@0.9.1 + + - name: ⬇️ Checkout repo + uses: actions/checkout@v3 + + - name: 👀 Read app name + uses: SebRollen/toml-action@v1.0.0 + 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 --app ${{ steps.app_name.outputs.value }}-staging --image registry.fly.io/${{ steps.app_name.outputs.value }}:${{ github.ref_name }}-${{ github.sha }}" + 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 --image registry.fly.io/${{ steps.app_name.outputs.value }}:${{ github.ref_name }}-${{ github.sha }}" + env: + FLY_API_TOKEN: ${{ secrets.FLY_API_TOKEN }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..72bfc1f --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +node_modules + +/build +/public/build +.env + +/cypress/screenshots +/cypress/videos +/postgres-data + +/app/styles/tailwind.css diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..72bfc1f --- /dev/null +++ b/.prettierignore @@ -0,0 +1,11 @@ +node_modules + +/build +/public/build +.env + +/cypress/screenshots +/cypress/videos +/postgres-data + +/app/styles/tailwind.css diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..06a5140 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,53 @@ +# 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 + +# Install all node_modules, including dev dependencies +FROM base as deps + +WORKDIR /myapp + +ADD package.json package-lock.json ./ +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 ./ +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 postinstall +RUN npm run build + +# Finally, build the production image with minimal footprint +FROM base + +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 +ADD . . + +CMD ["npm", "start"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..b20a2f2 --- /dev/null +++ b/README.md @@ -0,0 +1,197 @@ +# Remix Blues Stack + +![The Remix Blues Stack](https://repository-images.githubusercontent.com/461012689/37d5bd8b-fa9c-4ab0-893c-f0a199d5012d) + +Learn more about [Remix Stacks](https://remix.run/stacks). + +``` +npx create-remix --template remix-run/blues-stack +``` + +## What's in the stack + +- [Multi-region Fly app deployment](https://fly.io/docs/reference/scaling/) with [Docker](https://www.docker.com/) +- [Multi-region Fly PostgreSQL Cluster](https://fly.io/docs/getting-started/multi-region-databases/) +- 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/docs/en/v1/api/remix#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. + +## Development + +- Start the Postgres Database in [Docker](https://www.docker.com/get-started): + + ```sh + npm run docker + ``` + + > **Note:** The npm script will complete while Docker sets up the container in the background. Ensure that Docker has finished and your container is running before proceeding. + +- Initial setup: + + ```sh + npm run setup + ``` + +- Start dev server: + + ```sh + npm run dev + ``` + + > **Note:** You may see a nasty error in the PM2 logs when you initially run the dev script. This should only appear once and will not affect your local app server. We are working on improving this! + +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` + +If you'd prefer not to use Docker, you can also use Fly's Wireguard VPN to connect to a development database (or even your production database). You can find the instructions to set up Wireguard [here](https://fly.io/docs/reference/private-networking/#install-your-wireguard-app), and the instructions for creating a development database [here](https://fly.io/docs/reference/postgres/). + +### 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 create border-server-a1df + fly create border-server-a1df-staging + ``` + +- 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 border-server-a1df + fly secrets set SESSION_SECRET=$(openssl rand -hex 32) --app border-server-a1df-staging + ``` + + > **Note:** When creating the staging secret, you may get a warning from the Fly CLI that looks like this: + > + > ``` + > WARN app flag 'border-server-a1df-staging' does not match app name in config file 'border-server-a1df' + > ``` + > + > This simply means that the current directory contains a config that references the production app we created in the first step. Ignore this warning and proceed to create the secret. + + If you don't have openssl installed, you can also use [1password](https://1password.com/generate-password) to generate a random secret, just replace `$(openssl rand -hex 32)` with the generated secret. + +- Create a database for both your staging and production environments. Run the following: + + ```sh + fly postgres create --name border-server-a1df-db + fly postgres attach --postgres-app border-server-a1df-db --app border-server-a1df + + fly postgres create --name border-server-a1df-staging-db + fly postgres attach --postgres-app border-server-a1df-staging-db --app border-server-a1df-staging + ``` + + > **Note:** You'll get the same warning for the same reason when attaching the staging database that you did in the `fly set secret` step above. No worries. Proceed! + +Fly will take care of setting the `DATABASE_URL` secret for you. + +Now that every 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. + +### Multi-region deploys + +Once you have your site and database running in a single region, you can add more regions by following [Fly's Scaling](https://fly.io/docs/reference/scaling/) and [Multi-region PostgreSQL](https://fly.io/docs/getting-started/multi-region-databases/) docs. + +Make certain to set a `PRIMARY_REGION` environment variable for your app. You can use `[env]` config in the `fly.toml` to set that to the region you want to use as the primary region for both your app and database. + +#### Testing your app in other regions + +Install the [ModHeader](https://modheader.com/) browser extension (or something similar) and use it to load your app with the header `fly-prefer-region` set to the region name you would like to test. + +You can check the `x-fly-region` header on the response to know which region your request was handled by. + +## 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..990a05f --- /dev/null +++ b/app/db.server.ts @@ -0,0 +1,62 @@ +import { PrismaClient } from "@prisma/client"; +import invariant from "tiny-invariant"; + +let prisma: PrismaClient; + +declare global { + var __db__: PrismaClient; +} + +// 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 = getClient(); +} else { + if (!global.__db__) { + global.__db__ = getClient(); + } + prisma = global.__db__; +} + +function getClient() { + const { DATABASE_URL } = process.env; + invariant(typeof DATABASE_URL === "string", "DATABASE_URL env var not set"); + + const databaseUrl = new URL(DATABASE_URL); + + const isLocalHost = databaseUrl.hostname === "localhost"; + + const PRIMARY_REGION = isLocalHost ? null : process.env.PRIMARY_REGION; + const FLY_REGION = isLocalHost ? null : process.env.FLY_REGION; + + const isReadReplicaRegion = !PRIMARY_REGION || PRIMARY_REGION === FLY_REGION; + + if (!isLocalHost) { + databaseUrl.host = `${FLY_REGION}.${databaseUrl.host}`; + if (!isReadReplicaRegion) { + // 5433 is the read-replica port + databaseUrl.port = "5433"; + } + } + + console.log(`🔌 setting up prisma client to ${databaseUrl.host}`); + // NOTE: during development if you change anything in this function, remember + // that this only runs once per server restart and won't automatically be + // re-run per request like everything else is. So if you need to change + // something in this file, you'll need to manually restart the server. + const client = new PrismaClient({ + datasources: { + db: { + url: databaseUrl.toString(), + }, + }, + }); + // connect eagerly + client.$connect(); + + return client; +} + +export { prisma }; diff --git a/app/entry.client.tsx b/app/entry.client.tsx new file mode 100644 index 0000000..a19979b --- /dev/null +++ b/app/entry.client.tsx @@ -0,0 +1,4 @@ +import { hydrate } from "react-dom"; +import { RemixBrowser } from "remix"; + +hydrate(, document); diff --git a/app/entry.server.tsx b/app/entry.server.tsx new file mode 100644 index 0000000..cae2067 --- /dev/null +++ b/app/entry.server.tsx @@ -0,0 +1,21 @@ +import { renderToString } from "react-dom/server"; +import { RemixServer } from "remix"; +import type { EntryContext } from "remix"; + +export default function handleRequest( + request: Request, + responseStatusCode: number, + responseHeaders: Headers, + remixContext: EntryContext +) { + const markup = renderToString( + + ); + + responseHeaders.set("Content-Type", "text/html"); + + return new Response("" + markup, { + status: responseStatusCode, + headers: responseHeaders, + }); +} diff --git a/app/models/note.server.ts b/app/models/note.server.ts new file mode 100644 index 0000000..ba56b53 --- /dev/null +++ b/app/models/note.server.ts @@ -0,0 +1,53 @@ +import type { User, Note } from "@prisma/client"; + +import { prisma } from "~/db.server"; + +export type { Note } from "@prisma/client"; + +export function getNote({ + id, + userId, +}: Pick & { + userId: User["id"]; +}) { + return prisma.note.findFirst({ + 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..645da04 --- /dev/null +++ b/app/models/user.server.ts @@ -0,0 +1,59 @@ +import type { Password, User } from "@prisma/client"; +import bcrypt from "@node-rs/bcrypt"; + +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.verify(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..e38495e --- /dev/null +++ b/app/root.tsx @@ -0,0 +1,50 @@ +import { + json, + Links, + LiveReload, + Meta, + Outlet, + Scripts, + ScrollRestoration, +} from "remix"; +import type { LinksFunction, MetaFunction, LoaderFunction } from "remix"; + +import tailwindStylesheetUrl from "./styles/tailwind.css"; +import { getUser } from "./session.server"; + +export const links: LinksFunction = () => { + return [{ rel: "stylesheet", href: tailwindStylesheetUrl }]; +}; + +export const meta: MetaFunction = () => ({ + charset: "utf-8", + title: "Remix Notes", + viewport: "width=device-width,initial-scale=1", +}); + +type LoaderData = { + user: Awaited>; +}; + +export const loader: LoaderFunction = async ({ request }) => { + return json({ + user: await getUser(request), + }); +}; + +export default function App() { + return ( + + + + + + + + + + + + + ); +} diff --git a/app/routes/healthcheck.tsx b/app/routes/healthcheck.tsx new file mode 100644 index 0000000..8ca82e9 --- /dev/null +++ b/app/routes/healthcheck.tsx @@ -0,0 +1,23 @@ +// learn more: https://fly.io/docs/reference/configuration/#services-http_checks +import type { LoaderFunction } from "remix"; +import { prisma } from "~/db.server"; + +export const loader: LoaderFunction = async ({ request }) => { + const host = + request.headers.get("X-Forwarded-Host") ?? request.headers.get("host"); + + try { + // 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(`http://${host}`, { 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/index.tsx b/app/routes/index.tsx new file mode 100644 index 0000000..06e849b --- /dev/null +++ b/app/routes/index.tsx @@ -0,0 +1,137 @@ +import { Link } from "remix"; +import { useOptionalUser } from "~/utils"; + +export default function Index() { + const user = useOptionalUser(); + return ( +
+
+
+
+
+ BB King playing blues on his Les Paul guitar +
+
+
+

+ + Blues 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/158238105-e7279a0c-1640-40db-86b0-3d3a10aab824.svg", + alt: "PostgreSQL", + href: "https://www.postgresql.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/join.tsx b/app/routes/join.tsx new file mode 100644 index 0000000..06b0c65 --- /dev/null +++ b/app/routes/join.tsx @@ -0,0 +1,179 @@ +import * as React from "react"; +import type { ActionFunction, LoaderFunction, MetaFunction } from "remix"; +import { + Form, + Link, + redirect, + useSearchParams, + json, + useActionData, +} from "remix"; + +import { getUserId, createUserSession } from "~/session.server"; + +import { createUser, getUserByEmail } from "~/models/user.server"; +import { validateEmail } from "~/utils"; + +export const loader: LoaderFunction = async ({ request }) => { + const userId = await getUserId(request); + if (userId) return redirect("/"); + return json({}); +}; + +interface ActionData { + errors: { + email?: string; + password?: string; + }; +} + +export const action: ActionFunction = async ({ request }) => { + const formData = await request.formData(); + const email = formData.get("email"); + const password = formData.get("password"); + const redirectTo = formData.get("redirectTo"); + + if (!validateEmail(email)) { + return json( + { errors: { email: "Email is invalid" } }, + { status: 400 } + ); + } + + if (typeof password !== "string") { + return json( + { errors: { password: "Password is required" } }, + { status: 400 } + ); + } + + if (password.length < 8) { + return json( + { errors: { 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" } }, + { status: 400 } + ); + } + + const user = await createUser(email, password); + + return createUserSession({ + request, + userId: user.id, + remember: false, + redirectTo: typeof redirectTo === "string" ? redirectTo : "/", + }); +}; + +export const meta: MetaFunction = () => { + return { + title: "Sign Up", + }; +}; + +export default function Join() { + const [searchParams] = useSearchParams(); + const redirectTo = searchParams.get("redirectTo") ?? undefined; + const actionData = useActionData() as ActionData; + const emailRef = React.useRef(null); + const passwordRef = React.useRef(null); + + React.useEffect(() => { + if (actionData?.errors?.email) { + emailRef.current?.focus(); + } else if (actionData?.errors?.password) { + passwordRef.current?.focus(); + } + }, [actionData]); + + return ( +
+
+
+
+ +
+ + {actionData?.errors?.email && ( +
+ {actionData.errors.email} +
+ )} +
+
+ +
+ +
+ + {actionData?.errors?.password && ( +
+ {actionData.errors.password} +
+ )} +
+
+ + + +
+
+ Already have an account?{" "} + + Log in + +
+
+
+
+
+ ); +} diff --git a/app/routes/login.tsx b/app/routes/login.tsx new file mode 100644 index 0000000..5ba9534 --- /dev/null +++ b/app/routes/login.tsx @@ -0,0 +1,192 @@ +import * as React from "react"; +import type { ActionFunction, LoaderFunction, MetaFunction } from "remix"; +import { + Form, + json, + Link, + useActionData, + redirect, + useSearchParams, +} from "remix"; + +import { createUserSession, getUserId } from "~/session.server"; +import { verifyLogin } from "~/models/user.server"; +import { validateEmail } from "~/utils"; + +export const loader: LoaderFunction = async ({ request }) => { + const userId = await getUserId(request); + if (userId) return redirect("/"); + return json({}); +}; + +interface ActionData { + errors?: { + email?: string; + password?: string; + }; +} + +export const action: ActionFunction = async ({ request }) => { + const formData = await request.formData(); + const email = formData.get("email"); + const password = formData.get("password"); + const redirectTo = formData.get("redirectTo"); + const remember = formData.get("remember"); + + if (!validateEmail(email)) { + return json( + { errors: { email: "Email is invalid" } }, + { status: 400 } + ); + } + + if (typeof password !== "string") { + return json( + { errors: { password: "Password is required" } }, + { status: 400 } + ); + } + + if (password.length < 8) { + return json( + { errors: { password: "Password is too short" } }, + { status: 400 } + ); + } + + const user = await verifyLogin(email, password); + + if (!user) { + return json( + { errors: { email: "Invalid email or password" } }, + { status: 400 } + ); + } + + return createUserSession({ + request, + userId: user.id, + remember: remember === "on" ? true : false, + redirectTo: typeof redirectTo === "string" ? redirectTo : "/notes", + }); +}; + +export const meta: MetaFunction = () => { + return { + title: "Login", + }; +}; + +export default function LoginPage() { + const [searchParams] = useSearchParams(); + const redirectTo = searchParams.get("redirectTo") || "/notes"; + const actionData = useActionData() as ActionData; + const emailRef = React.useRef(null); + const passwordRef = React.useRef(null); + + React.useEffect(() => { + if (actionData?.errors?.email) { + emailRef.current?.focus(); + } else if (actionData?.errors?.password) { + passwordRef.current?.focus(); + } + }, [actionData]); + + return ( +
+
+
+
+ +
+ + {actionData?.errors?.email && ( +
+ {actionData.errors.email} +
+ )} +
+
+ +
+ +
+ + {actionData?.errors?.password && ( +
+ {actionData.errors.password} +
+ )} +
+
+ + + +
+
+ + +
+
+ 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..17be85f --- /dev/null +++ b/app/routes/logout.tsx @@ -0,0 +1,11 @@ +import type { ActionFunction, LoaderFunction } from "remix"; +import { redirect } from "remix"; +import { logout } from "~/session.server"; + +export const action: ActionFunction = async ({ request }) => { + return logout(request); +}; + +export const loader: LoaderFunction = async () => { + return redirect("/"); +}; diff --git a/app/routes/notes.tsx b/app/routes/notes.tsx new file mode 100644 index 0000000..8a496a9 --- /dev/null +++ b/app/routes/notes.tsx @@ -0,0 +1,73 @@ +import { Form, json, useLoaderData, Outlet, Link, NavLink } from "remix"; +import type { LoaderFunction } from "remix"; + +import { requireUserId } from "~/session.server"; +import { useUser } from "~/utils"; +import { getNoteListItems } from "~/models/note.server"; + +type LoaderData = { + noteListItems: Awaited>; +}; + +export const loader: LoaderFunction = async ({ request }) => { + const userId = await requireUserId(request); + const noteListItems = await getNoteListItems({ userId }); + return json({ noteListItems }); +}; + +export default function NotesPage() { + const data = useLoaderData() as LoaderData; + const user = useUser(); + + return ( +
+
+

+ Notes +

+

{user.email}

+
+ +
+
+ +
+
+ + + New Note + + +
+ + {data.noteListItems.length === 0 ? ( +

No notes yet

+ ) : ( +
    + {data.noteListItems.map((note) => ( +
  1. + + `block border-b p-4 text-xl ${isActive ? "bg-white" : ""}` + } + to={note.id} + > + 📝 {note.title} + +
  2. + ))} +
+ )} +
+ +
+ +
+
+
+ ); +} diff --git a/app/routes/notes/$noteId.tsx b/app/routes/notes/$noteId.tsx new file mode 100644 index 0000000..10b4e65 --- /dev/null +++ b/app/routes/notes/$noteId.tsx @@ -0,0 +1,68 @@ +import type { LoaderFunction, ActionFunction } from "remix"; +import { redirect } from "remix"; +import { json, useLoaderData, useCatch, Form } from "remix"; +import invariant from "tiny-invariant"; +import type { Note } from "~/models/note.server"; +import { deleteNote } from "~/models/note.server"; +import { getNote } from "~/models/note.server"; +import { requireUserId } from "~/session.server"; + +type LoaderData = { + note: Note; +}; + +export const loader: LoaderFunction = async ({ request, params }) => { + const userId = await requireUserId(request); + invariant(params.noteId, "noteId not found"); + + const note = await getNote({ userId, id: params.noteId }); + if (!note) { + throw new Response("Not Found", { status: 404 }); + } + return json({ note }); +}; + +export const action: ActionFunction = async ({ request, params }) => { + const userId = await requireUserId(request); + invariant(params.noteId, "noteId not found"); + + await deleteNote({ userId, id: params.noteId }); + + return redirect("/notes"); +}; + +export default function NoteDetailsPage() { + const data = useLoaderData() as LoaderData; + + return ( +
+

{data.note.title}

+

{data.note.body}

+
+
+ +
+
+ ); +} + +export function ErrorBoundary({ error }: { error: Error }) { + console.error(error); + + return
An unexpected error occurred: {error.message}
; +} + +export function CatchBoundary() { + const caught = useCatch(); + + if (caught.status === 404) { + return
Note not found
; + } + + throw new Error(`Unexpected caught response with status: ${caught.status}`); +} diff --git a/app/routes/notes/index.tsx b/app/routes/notes/index.tsx new file mode 100644 index 0000000..30df34b --- /dev/null +++ b/app/routes/notes/index.tsx @@ -0,0 +1,12 @@ +import { Link } from "remix"; + +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..3c6fee6 --- /dev/null +++ b/app/routes/notes/new.tsx @@ -0,0 +1,116 @@ +import * as React from "react"; +import { Form, json, redirect, useActionData } from "remix"; +import type { ActionFunction } from "remix"; +import Alert from "@reach/alert"; + +import { createNote } from "~/models/note.server"; +import { requireUserId } from "~/session.server"; + +type ActionData = { + errors?: { + title?: string; + body?: string; + }; +}; + +export const action: ActionFunction = async ({ request }) => { + 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: { title: "Title is required" } }, + { status: 400 } + ); + } + + if (typeof body !== "string" || body.length === 0) { + return json( + { errors: { body: "Body is required" } }, + { status: 400 } + ); + } + + const note = await createNote({ title, body, userId }); + + return redirect(`/notes/${note.id}`); +}; + +export default function NewNotePage() { + const actionData = useActionData() as ActionData; + const titleRef = React.useRef(null); + const bodyRef = React.useRef(null); + + React.useEffect(() => { + if (actionData?.errors?.title) { + titleRef.current?.focus(); + } else if (actionData?.errors?.body) { + bodyRef.current?.focus(); + } + }, [actionData]); + + return ( +
+
+ + {actionData?.errors?.title && ( + + {actionData.errors.title} + + )} +
+ +
+