switch to remix
7
.dockerignore
Normal file
|
@ -0,0 +1,7 @@
|
||||||
|
/node_modules
|
||||||
|
*.log
|
||||||
|
.DS_Store
|
||||||
|
.env
|
||||||
|
/.cache
|
||||||
|
/public/build
|
||||||
|
/build
|
2
.env.example
Normal file
|
@ -0,0 +1,2 @@
|
||||||
|
DATABASE_URL="postgresql://postgres:postgres@localhost:5432/postgres"
|
||||||
|
SESSION_SECRET="super-duper-s3cret"
|
19
.eslintrc.js
Normal file
|
@ -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,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
211
.github/workflows/deploy.yml
vendored
Normal file
|
@ -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 }}
|
11
.gitignore
vendored
Normal file
|
@ -0,0 +1,11 @@
|
||||||
|
node_modules
|
||||||
|
|
||||||
|
/build
|
||||||
|
/public/build
|
||||||
|
.env
|
||||||
|
|
||||||
|
/cypress/screenshots
|
||||||
|
/cypress/videos
|
||||||
|
/postgres-data
|
||||||
|
|
||||||
|
/app/styles/tailwind.css
|
11
.prettierignore
Normal file
|
@ -0,0 +1,11 @@
|
||||||
|
node_modules
|
||||||
|
|
||||||
|
/build
|
||||||
|
/public/build
|
||||||
|
.env
|
||||||
|
|
||||||
|
/cypress/screenshots
|
||||||
|
/cypress/videos
|
||||||
|
/postgres-data
|
||||||
|
|
||||||
|
/app/styles/tailwind.css
|
53
Dockerfile
Normal file
|
@ -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"]
|
197
README.md
Normal file
|
@ -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 <ORIGIN_URL>
|
||||||
|
```
|
||||||
|
|
||||||
|
- 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.
|
62
app/db.server.ts
Normal file
|
@ -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 };
|
4
app/entry.client.tsx
Normal file
|
@ -0,0 +1,4 @@
|
||||||
|
import { hydrate } from "react-dom";
|
||||||
|
import { RemixBrowser } from "remix";
|
||||||
|
|
||||||
|
hydrate(<RemixBrowser />, document);
|
21
app/entry.server.tsx
Normal file
|
@ -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(
|
||||||
|
<RemixServer context={remixContext} url={request.url} />
|
||||||
|
);
|
||||||
|
|
||||||
|
responseHeaders.set("Content-Type", "text/html");
|
||||||
|
|
||||||
|
return new Response("<!DOCTYPE html>" + markup, {
|
||||||
|
status: responseStatusCode,
|
||||||
|
headers: responseHeaders,
|
||||||
|
});
|
||||||
|
}
|
53
app/models/note.server.ts
Normal file
|
@ -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<Note, "id"> & {
|
||||||
|
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<Note, "body" | "title"> & {
|
||||||
|
userId: User["id"];
|
||||||
|
}) {
|
||||||
|
return prisma.note.create({
|
||||||
|
data: {
|
||||||
|
title,
|
||||||
|
body,
|
||||||
|
user: {
|
||||||
|
connect: {
|
||||||
|
id: userId,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deleteNote({
|
||||||
|
id,
|
||||||
|
userId,
|
||||||
|
}: Pick<Note, "id"> & { userId: User["id"] }) {
|
||||||
|
return prisma.note.deleteMany({
|
||||||
|
where: { id, userId },
|
||||||
|
});
|
||||||
|
}
|
59
app/models/user.server.ts
Normal file
|
@ -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;
|
||||||
|
}
|
50
app/root.tsx
Normal file
|
@ -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<ReturnType<typeof getUser>>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const loader: LoaderFunction = async ({ request }) => {
|
||||||
|
return json<LoaderData>({
|
||||||
|
user: await getUser(request),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function App() {
|
||||||
|
return (
|
||||||
|
<html lang="en" className="h-full">
|
||||||
|
<head>
|
||||||
|
<Meta />
|
||||||
|
<Links />
|
||||||
|
</head>
|
||||||
|
<body className="h-full">
|
||||||
|
<Outlet />
|
||||||
|
<ScrollRestoration />
|
||||||
|
<Scripts />
|
||||||
|
<LiveReload />
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
);
|
||||||
|
}
|
23
app/routes/healthcheck.tsx
Normal file
|
@ -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 });
|
||||||
|
}
|
||||||
|
};
|
137
app/routes/index.tsx
Normal file
|
@ -0,0 +1,137 @@
|
||||||
|
import { Link } from "remix";
|
||||||
|
import { useOptionalUser } from "~/utils";
|
||||||
|
|
||||||
|
export default function Index() {
|
||||||
|
const user = useOptionalUser();
|
||||||
|
return (
|
||||||
|
<main className="relative min-h-screen bg-white sm:flex sm:items-center sm:justify-center">
|
||||||
|
<div className="relative sm:pb-16 sm:pt-8">
|
||||||
|
<div className="mx-auto max-w-7xl sm:px-6 lg:px-8">
|
||||||
|
<div className="relative shadow-xl sm:overflow-hidden sm:rounded-2xl">
|
||||||
|
<div className="absolute inset-0">
|
||||||
|
<img
|
||||||
|
className="h-full w-full object-cover"
|
||||||
|
src="https://user-images.githubusercontent.com/1500684/158276320-c46b661b-8eff-4a4d-82c6-cf296c987a12.jpg"
|
||||||
|
alt="BB King playing blues on his Les Paul guitar"
|
||||||
|
/>
|
||||||
|
<div className="absolute inset-0 bg-[color:rgba(27,167,254,0.5)] mix-blend-multiply" />
|
||||||
|
</div>
|
||||||
|
<div className="lg:pb-18 relative px-4 pt-16 pb-8 sm:px-6 sm:pt-24 sm:pb-14 lg:px-8 lg:pt-32">
|
||||||
|
<h1 className="text-center text-6xl font-extrabold tracking-tight sm:text-8xl lg:text-9xl">
|
||||||
|
<span className="block uppercase text-blue-500 drop-shadow-md">
|
||||||
|
Blues Stack
|
||||||
|
</span>
|
||||||
|
</h1>
|
||||||
|
<p className="mx-auto mt-6 max-w-lg text-center text-xl text-white sm:max-w-3xl">
|
||||||
|
Check the README.md file for instructions on how to get this
|
||||||
|
project deployed.
|
||||||
|
</p>
|
||||||
|
<div className="mx-auto mt-10 max-w-sm sm:flex sm:max-w-none sm:justify-center">
|
||||||
|
{user ? (
|
||||||
|
<Link
|
||||||
|
to="/notes"
|
||||||
|
className="flex items-center justify-center rounded-md border border-transparent bg-white px-4 py-3 text-base font-medium text-blue-700 shadow-sm hover:bg-blue-50 sm:px-8"
|
||||||
|
>
|
||||||
|
View Notes for {user.email}
|
||||||
|
</Link>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-4 sm:mx-auto sm:inline-grid sm:grid-cols-2 sm:gap-5 sm:space-y-0">
|
||||||
|
<Link
|
||||||
|
to="/join"
|
||||||
|
className="flex items-center justify-center rounded-md border border-transparent bg-white px-4 py-3 text-base font-medium text-blue-700 shadow-sm hover:bg-blue-50 sm:px-8"
|
||||||
|
>
|
||||||
|
Sign up
|
||||||
|
</Link>
|
||||||
|
<Link
|
||||||
|
to="/login"
|
||||||
|
className="flex items-center justify-center rounded-md bg-blue-500 px-4 py-3 font-medium text-white hover:bg-blue-600 "
|
||||||
|
>
|
||||||
|
Log In
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<a href="https://remix.run">
|
||||||
|
<img
|
||||||
|
src="https://user-images.githubusercontent.com/1500684/158298926-e45dafff-3544-4b69-96d6-d3bcc33fc76a.svg"
|
||||||
|
alt="Remix"
|
||||||
|
className="mx-auto mt-16 w-full max-w-[12rem] md:max-w-[16rem]"
|
||||||
|
/>
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mx-auto max-w-7xl py-2 px-4 sm:px-6 lg:px-8">
|
||||||
|
<div className="mt-6 flex flex-wrap justify-center gap-8">
|
||||||
|
{[
|
||||||
|
{
|
||||||
|
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) => (
|
||||||
|
<a
|
||||||
|
key={img.href}
|
||||||
|
href={img.href}
|
||||||
|
className="flex h-16 w-32 justify-center p-1 grayscale transition hover:grayscale-0 focus:grayscale-0"
|
||||||
|
>
|
||||||
|
<img alt={img.alt} src={img.src} />
|
||||||
|
</a>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
179
app/routes/join.tsx
Normal file
|
@ -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<ActionData>(
|
||||||
|
{ errors: { email: "Email is invalid" } },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof password !== "string") {
|
||||||
|
return json<ActionData>(
|
||||||
|
{ errors: { password: "Password is required" } },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (password.length < 8) {
|
||||||
|
return json<ActionData>(
|
||||||
|
{ errors: { password: "Password is too short" } },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const existingUser = await getUserByEmail(email);
|
||||||
|
if (existingUser) {
|
||||||
|
return json<ActionData>(
|
||||||
|
{ 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<HTMLInputElement>(null);
|
||||||
|
const passwordRef = React.useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
if (actionData?.errors?.email) {
|
||||||
|
emailRef.current?.focus();
|
||||||
|
} else if (actionData?.errors?.password) {
|
||||||
|
passwordRef.current?.focus();
|
||||||
|
}
|
||||||
|
}, [actionData]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-full flex-col justify-center">
|
||||||
|
<div className="mx-auto w-full max-w-md px-8">
|
||||||
|
<Form method="post" className="space-y-6" noValidate>
|
||||||
|
<div>
|
||||||
|
<label
|
||||||
|
htmlFor="email"
|
||||||
|
className="block text-sm font-medium text-gray-700"
|
||||||
|
>
|
||||||
|
Email address
|
||||||
|
</label>
|
||||||
|
<div className="mt-1">
|
||||||
|
<input
|
||||||
|
ref={emailRef}
|
||||||
|
id="email"
|
||||||
|
required
|
||||||
|
autoFocus={true}
|
||||||
|
name="email"
|
||||||
|
type="email"
|
||||||
|
autoComplete="email"
|
||||||
|
aria-invalid={actionData?.errors?.email ? true : undefined}
|
||||||
|
aria-describedby="email-error"
|
||||||
|
className="w-full rounded border border-gray-500 px-2 py-1 text-lg"
|
||||||
|
/>
|
||||||
|
{actionData?.errors?.email && (
|
||||||
|
<div className="pt-1 text-red-700" id="email-error">
|
||||||
|
{actionData.errors.email}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label
|
||||||
|
htmlFor="password"
|
||||||
|
className="block text-sm font-medium text-gray-700"
|
||||||
|
>
|
||||||
|
Password
|
||||||
|
</label>
|
||||||
|
<div className="mt-1">
|
||||||
|
<input
|
||||||
|
id="password"
|
||||||
|
ref={passwordRef}
|
||||||
|
name="password"
|
||||||
|
type="password"
|
||||||
|
autoComplete="new-password"
|
||||||
|
aria-invalid={actionData?.errors?.password ? true : undefined}
|
||||||
|
aria-describedby="password-error"
|
||||||
|
className="w-full rounded border border-gray-500 px-2 py-1 text-lg"
|
||||||
|
/>
|
||||||
|
{actionData?.errors?.password && (
|
||||||
|
<div className="pt-1 text-red-700" id="password-error">
|
||||||
|
{actionData.errors.password}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<input type="hidden" name="redirectTo" value={redirectTo} />
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
className="w-full rounded bg-blue-500 py-2 px-4 text-white hover:bg-blue-600 focus:bg-blue-400"
|
||||||
|
>
|
||||||
|
Create Account
|
||||||
|
</button>
|
||||||
|
<div className="flex items-center justify-center">
|
||||||
|
<div className="text-center text-sm text-gray-500">
|
||||||
|
Already have an account?{" "}
|
||||||
|
<Link
|
||||||
|
className="text-blue-500 underline"
|
||||||
|
to={{
|
||||||
|
pathname: "/login",
|
||||||
|
search: searchParams.toString(),
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Log in
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
192
app/routes/login.tsx
Normal file
|
@ -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<ActionData>(
|
||||||
|
{ errors: { email: "Email is invalid" } },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof password !== "string") {
|
||||||
|
return json<ActionData>(
|
||||||
|
{ errors: { password: "Password is required" } },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (password.length < 8) {
|
||||||
|
return json<ActionData>(
|
||||||
|
{ errors: { password: "Password is too short" } },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = await verifyLogin(email, password);
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
return json<ActionData>(
|
||||||
|
{ 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<HTMLInputElement>(null);
|
||||||
|
const passwordRef = React.useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
if (actionData?.errors?.email) {
|
||||||
|
emailRef.current?.focus();
|
||||||
|
} else if (actionData?.errors?.password) {
|
||||||
|
passwordRef.current?.focus();
|
||||||
|
}
|
||||||
|
}, [actionData]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-full flex-col justify-center">
|
||||||
|
<div className="mx-auto w-full max-w-md px-8">
|
||||||
|
<Form method="post" className="space-y-6" noValidate>
|
||||||
|
<div>
|
||||||
|
<label
|
||||||
|
htmlFor="email"
|
||||||
|
className="block text-sm font-medium text-gray-700"
|
||||||
|
>
|
||||||
|
Email address
|
||||||
|
</label>
|
||||||
|
<div className="mt-1">
|
||||||
|
<input
|
||||||
|
ref={emailRef}
|
||||||
|
id="email"
|
||||||
|
required
|
||||||
|
autoFocus={true}
|
||||||
|
name="email"
|
||||||
|
type="email"
|
||||||
|
autoComplete="email"
|
||||||
|
aria-invalid={actionData?.errors?.email ? true : undefined}
|
||||||
|
aria-describedby="email-error"
|
||||||
|
className="w-full rounded border border-gray-500 px-2 py-1 text-lg"
|
||||||
|
/>
|
||||||
|
{actionData?.errors?.email && (
|
||||||
|
<div className="pt-1 text-red-700" id="email-error">
|
||||||
|
{actionData.errors.email}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label
|
||||||
|
htmlFor="password"
|
||||||
|
className="block text-sm font-medium text-gray-700"
|
||||||
|
>
|
||||||
|
Password
|
||||||
|
</label>
|
||||||
|
<div className="mt-1">
|
||||||
|
<input
|
||||||
|
id="password"
|
||||||
|
ref={passwordRef}
|
||||||
|
name="password"
|
||||||
|
type="password"
|
||||||
|
autoComplete="new-password"
|
||||||
|
aria-invalid={actionData?.errors?.password ? true : undefined}
|
||||||
|
aria-describedby="password-error"
|
||||||
|
className="w-full rounded border border-gray-500 px-2 py-1 text-lg"
|
||||||
|
/>
|
||||||
|
{actionData?.errors?.password && (
|
||||||
|
<div className="pt-1 text-red-700" id="password-error">
|
||||||
|
{actionData.errors.password}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<input type="hidden" name="redirectTo" value={redirectTo} />
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
className="w-full rounded bg-blue-500 py-2 px-4 text-white hover:bg-blue-600 focus:bg-blue-400"
|
||||||
|
>
|
||||||
|
Log in
|
||||||
|
</button>
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div className="flex items-center">
|
||||||
|
<input
|
||||||
|
id="remember"
|
||||||
|
name="remember"
|
||||||
|
type="checkbox"
|
||||||
|
className="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
|
||||||
|
/>
|
||||||
|
<label
|
||||||
|
htmlFor="remember"
|
||||||
|
className="ml-2 block text-sm text-gray-900"
|
||||||
|
>
|
||||||
|
Remember me
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div className="text-center text-sm text-gray-500">
|
||||||
|
Don't have an account?{" "}
|
||||||
|
<Link
|
||||||
|
className="text-blue-500 underline"
|
||||||
|
to={{
|
||||||
|
pathname: "/join",
|
||||||
|
search: searchParams.toString(),
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Sign up
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
11
app/routes/logout.tsx
Normal file
|
@ -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("/");
|
||||||
|
};
|
73
app/routes/notes.tsx
Normal file
|
@ -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<ReturnType<typeof getNoteListItems>>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const loader: LoaderFunction = async ({ request }) => {
|
||||||
|
const userId = await requireUserId(request);
|
||||||
|
const noteListItems = await getNoteListItems({ userId });
|
||||||
|
return json<LoaderData>({ noteListItems });
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function NotesPage() {
|
||||||
|
const data = useLoaderData() as LoaderData;
|
||||||
|
const user = useUser();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex h-full min-h-screen flex-col">
|
||||||
|
<header className="flex items-center justify-between bg-slate-800 p-4 text-white">
|
||||||
|
<h1 className="text-3xl font-bold">
|
||||||
|
<Link to=".">Notes</Link>
|
||||||
|
</h1>
|
||||||
|
<p>{user.email}</p>
|
||||||
|
<Form action="/logout" method="post">
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
className="rounded bg-slate-600 py-2 px-4 text-blue-100 hover:bg-blue-500 active:bg-blue-600"
|
||||||
|
>
|
||||||
|
Logout
|
||||||
|
</button>
|
||||||
|
</Form>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<main className="flex h-full bg-white">
|
||||||
|
<div className="h-full w-80 border-r bg-gray-50">
|
||||||
|
<Link to="new" className="block p-4 text-xl text-blue-500">
|
||||||
|
+ New Note
|
||||||
|
</Link>
|
||||||
|
|
||||||
|
<hr />
|
||||||
|
|
||||||
|
{data.noteListItems.length === 0 ? (
|
||||||
|
<p className="p-4">No notes yet</p>
|
||||||
|
) : (
|
||||||
|
<ol>
|
||||||
|
{data.noteListItems.map((note) => (
|
||||||
|
<li key={note.id}>
|
||||||
|
<NavLink
|
||||||
|
className={({ isActive }) =>
|
||||||
|
`block border-b p-4 text-xl ${isActive ? "bg-white" : ""}`
|
||||||
|
}
|
||||||
|
to={note.id}
|
||||||
|
>
|
||||||
|
📝 {note.title}
|
||||||
|
</NavLink>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ol>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex-1 p-6">
|
||||||
|
<Outlet />
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
68
app/routes/notes/$noteId.tsx
Normal file
|
@ -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<LoaderData>({ 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 (
|
||||||
|
<div>
|
||||||
|
<h3 className="text-2xl font-bold">{data.note.title}</h3>
|
||||||
|
<p className="py-6">{data.note.body}</p>
|
||||||
|
<hr className="my-4" />
|
||||||
|
<Form method="post">
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
className="rounded bg-blue-500 py-2 px-4 text-white hover:bg-blue-600 focus:bg-blue-400"
|
||||||
|
>
|
||||||
|
Delete
|
||||||
|
</button>
|
||||||
|
</Form>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ErrorBoundary({ error }: { error: Error }) {
|
||||||
|
console.error(error);
|
||||||
|
|
||||||
|
return <div>An unexpected error occurred: {error.message}</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CatchBoundary() {
|
||||||
|
const caught = useCatch();
|
||||||
|
|
||||||
|
if (caught.status === 404) {
|
||||||
|
return <div>Note not found</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(`Unexpected caught response with status: ${caught.status}`);
|
||||||
|
}
|
12
app/routes/notes/index.tsx
Normal file
|
@ -0,0 +1,12 @@
|
||||||
|
import { Link } from "remix";
|
||||||
|
|
||||||
|
export default function NoteIndexPage() {
|
||||||
|
return (
|
||||||
|
<p>
|
||||||
|
No note selected. Select a note on the left, or{" "}
|
||||||
|
<Link to="new" className="text-blue-500 underline">
|
||||||
|
create a new note.
|
||||||
|
</Link>
|
||||||
|
</p>
|
||||||
|
);
|
||||||
|
}
|
116
app/routes/notes/new.tsx
Normal file
|
@ -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<ActionData>(
|
||||||
|
{ errors: { title: "Title is required" } },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof body !== "string" || body.length === 0) {
|
||||||
|
return json<ActionData>(
|
||||||
|
{ 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<HTMLInputElement>(null);
|
||||||
|
const bodyRef = React.useRef<HTMLTextAreaElement>(null);
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
if (actionData?.errors?.title) {
|
||||||
|
titleRef.current?.focus();
|
||||||
|
} else if (actionData?.errors?.body) {
|
||||||
|
bodyRef.current?.focus();
|
||||||
|
}
|
||||||
|
}, [actionData]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Form
|
||||||
|
method="post"
|
||||||
|
style={{
|
||||||
|
display: "flex",
|
||||||
|
flexDirection: "column",
|
||||||
|
gap: 8,
|
||||||
|
width: "100%",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<label className="flex w-full flex-col gap-1">
|
||||||
|
<span>Title: </span>
|
||||||
|
<input
|
||||||
|
ref={titleRef}
|
||||||
|
name="title"
|
||||||
|
className="flex-1 rounded-md border-2 border-blue-500 px-3 text-lg leading-loose"
|
||||||
|
aria-invalid={actionData?.errors?.title ? true : undefined}
|
||||||
|
aria-errormessage={
|
||||||
|
actionData?.errors?.title ? "title-error" : undefined
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
{actionData?.errors?.title && (
|
||||||
|
<Alert className="pt-1 text-red-700" id="title=error">
|
||||||
|
{actionData.errors.title}
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="flex w-full flex-col gap-1">
|
||||||
|
<span>Body: </span>
|
||||||
|
<textarea
|
||||||
|
ref={bodyRef}
|
||||||
|
name="body"
|
||||||
|
rows={8}
|
||||||
|
className="w-full flex-1 rounded-md border-2 border-blue-500 py-2 px-3 text-lg leading-6"
|
||||||
|
aria-invalid={actionData?.errors?.body ? true : undefined}
|
||||||
|
aria-errormessage={
|
||||||
|
actionData?.errors?.body ? "body-error" : undefined
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
{actionData?.errors?.body && (
|
||||||
|
<Alert className="pt-1 text-red-700" id="body=error">
|
||||||
|
{actionData.errors.body}
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="text-right">
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
className="rounded bg-blue-500 py-2 px-4 text-white hover:bg-blue-600 focus:bg-blue-400"
|
||||||
|
>
|
||||||
|
Save
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</Form>
|
||||||
|
);
|
||||||
|
}
|
96
app/session.server.ts
Normal file
|
@ -0,0 +1,96 @@
|
||||||
|
import { createCookieSessionStorage, redirect } from "remix";
|
||||||
|
import invariant from "tiny-invariant";
|
||||||
|
|
||||||
|
import type { User } from "~/models/user.server";
|
||||||
|
import { getUserById } from "~/models/user.server";
|
||||||
|
|
||||||
|
invariant(process.env.SESSION_SECRET, "SESSION_SECRET must be set");
|
||||||
|
|
||||||
|
export const sessionStorage = createCookieSessionStorage({
|
||||||
|
cookie: {
|
||||||
|
name: "__session",
|
||||||
|
httpOnly: true,
|
||||||
|
maxAge: 0,
|
||||||
|
path: "/",
|
||||||
|
sameSite: "lax",
|
||||||
|
secrets: [process.env.SESSION_SECRET],
|
||||||
|
secure: process.env.NODE_ENV === "production",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const USER_SESSION_KEY = "userId";
|
||||||
|
|
||||||
|
export async function getSession(request: Request) {
|
||||||
|
const cookie = request.headers.get("Cookie");
|
||||||
|
return sessionStorage.getSession(cookie);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getUserId(request: Request): Promise<string | undefined> {
|
||||||
|
const session = await getSession(request);
|
||||||
|
const userId = session.get(USER_SESSION_KEY);
|
||||||
|
return userId;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getUser(request: Request): Promise<null | User> {
|
||||||
|
const userId = await getUserId(request);
|
||||||
|
if (userId === undefined) return null;
|
||||||
|
|
||||||
|
const user = await getUserById(userId);
|
||||||
|
if (user) return user;
|
||||||
|
|
||||||
|
throw await logout(request);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function requireUserId(
|
||||||
|
request: Request,
|
||||||
|
redirectTo: string = new URL(request.url).pathname
|
||||||
|
): Promise<string> {
|
||||||
|
const userId = await getUserId(request);
|
||||||
|
if (!userId) {
|
||||||
|
const searchParams = new URLSearchParams([["redirectTo", redirectTo]]);
|
||||||
|
throw redirect(`/login?${searchParams}`);
|
||||||
|
}
|
||||||
|
return userId;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function requireUser(request: Request) {
|
||||||
|
const userId = await requireUserId(request);
|
||||||
|
|
||||||
|
const user = await getUserById(userId);
|
||||||
|
if (user) return user;
|
||||||
|
|
||||||
|
throw await logout(request);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createUserSession({
|
||||||
|
request,
|
||||||
|
userId,
|
||||||
|
remember,
|
||||||
|
redirectTo,
|
||||||
|
}: {
|
||||||
|
request: Request;
|
||||||
|
userId: string;
|
||||||
|
remember: boolean;
|
||||||
|
redirectTo: string;
|
||||||
|
}) {
|
||||||
|
const session = await getSession(request);
|
||||||
|
session.set(USER_SESSION_KEY, userId);
|
||||||
|
return redirect(redirectTo, {
|
||||||
|
headers: {
|
||||||
|
"Set-Cookie": await sessionStorage.commitSession(session, {
|
||||||
|
maxAge: remember
|
||||||
|
? 60 * 60 * 24 * 7 // 7 days
|
||||||
|
: undefined,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function logout(request: Request) {
|
||||||
|
const session = await getSession(request);
|
||||||
|
return redirect("/", {
|
||||||
|
headers: {
|
||||||
|
"Set-Cookie": await sessionStorage.destroySession(session),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
13
app/utils.test.ts
Normal file
|
@ -0,0 +1,13 @@
|
||||||
|
import { validateEmail } from "./utils";
|
||||||
|
|
||||||
|
test("validateEmail returns false for non-emails", () => {
|
||||||
|
expect(validateEmail(undefined)).toBe(false);
|
||||||
|
expect(validateEmail(null)).toBe(false);
|
||||||
|
expect(validateEmail("")).toBe(false);
|
||||||
|
expect(validateEmail("not-an-email")).toBe(false);
|
||||||
|
expect(validateEmail("n@")).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("validateEmail returns true for emails", () => {
|
||||||
|
expect(validateEmail("kody@example.com")).toBe(true);
|
||||||
|
});
|
47
app/utils.ts
Normal file
|
@ -0,0 +1,47 @@
|
||||||
|
import { useMemo } from "react";
|
||||||
|
import { useMatches } from "remix";
|
||||||
|
|
||||||
|
import type { User } from "~/models/user.server";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This base hook is used in other hooks to quickly search for specific data
|
||||||
|
* across all loader data using useMatches.
|
||||||
|
* @param {string} id The route id
|
||||||
|
* @returns {JSON|undefined} The router data or undefined if not found
|
||||||
|
*/
|
||||||
|
export function useMatchesData(
|
||||||
|
id: string
|
||||||
|
): Record<string, unknown> | undefined {
|
||||||
|
const matchingRoutes = useMatches();
|
||||||
|
const route = useMemo(
|
||||||
|
() => matchingRoutes.find((route) => route.id === id),
|
||||||
|
[matchingRoutes, id]
|
||||||
|
);
|
||||||
|
return route?.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isUser(user: any): user is User {
|
||||||
|
return user && typeof user === "object" && typeof user.email === "string";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useOptionalUser(): User | undefined {
|
||||||
|
const data = useMatchesData("root");
|
||||||
|
if (!data || !isUser(data.user)) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
return data.user;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useUser(): User {
|
||||||
|
const maybeUser = useOptionalUser();
|
||||||
|
if (!maybeUser) {
|
||||||
|
throw new Error(
|
||||||
|
"No user found in root loader, but user is required by useUser. If user is optional, try useOptionalUser instead."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return maybeUser;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function validateEmail(email: unknown): email is string {
|
||||||
|
return typeof email === "string" && email.length > 3 && email.includes("@");
|
||||||
|
}
|
1
cypress.json
Normal file
|
@ -0,0 +1 @@
|
||||||
|
{}
|
6
cypress/.eslintrc.js
Normal file
|
@ -0,0 +1,6 @@
|
||||||
|
module.exports = {
|
||||||
|
parserOptions: {
|
||||||
|
tsconfigRootDir: __dirname,
|
||||||
|
project: "./tsconfig.json",
|
||||||
|
},
|
||||||
|
};
|
48
cypress/e2e/smoke.ts
Normal file
|
@ -0,0 +1,48 @@
|
||||||
|
import faker from "@faker-js/faker";
|
||||||
|
|
||||||
|
describe("smoke tests", () => {
|
||||||
|
afterEach(() => {
|
||||||
|
cy.cleanupUser();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should allow you to register and login", () => {
|
||||||
|
const loginForm = {
|
||||||
|
email: `${faker.internet.userName()}@example.com`,
|
||||||
|
password: faker.internet.password(),
|
||||||
|
};
|
||||||
|
cy.then(() => ({ email: loginForm.email })).as("user");
|
||||||
|
|
||||||
|
cy.visit("/");
|
||||||
|
cy.findByRole("link", { name: /sign up/i }).click();
|
||||||
|
|
||||||
|
cy.findByRole("textbox", { name: /email/i }).type(loginForm.email);
|
||||||
|
cy.findByLabelText(/password/i).type(loginForm.password);
|
||||||
|
cy.findByRole("button", { name: /create account/i }).click();
|
||||||
|
|
||||||
|
cy.findByRole("link", { name: /notes/i }).click();
|
||||||
|
cy.findByRole("button", { name: /logout/i }).click();
|
||||||
|
cy.findByRole("link", { name: /log in/i });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should allow you to make a note", () => {
|
||||||
|
const testNote = {
|
||||||
|
title: faker.lorem.words(1),
|
||||||
|
body: faker.lorem.sentences(1),
|
||||||
|
};
|
||||||
|
cy.login();
|
||||||
|
cy.visit("/");
|
||||||
|
|
||||||
|
cy.findByRole("link", { name: /notes/i }).click();
|
||||||
|
cy.findByText("No notes yet");
|
||||||
|
|
||||||
|
cy.findByRole("link", { name: /\+ new note/i }).click();
|
||||||
|
|
||||||
|
cy.findByRole("textbox", { name: /title/i }).type(testNote.title);
|
||||||
|
cy.findByRole("textbox", { name: /body/i }).type(testNote.body);
|
||||||
|
cy.findByRole("button", { name: /save/i }).click();
|
||||||
|
|
||||||
|
cy.findByRole("button", { name: /delete/i }).click();
|
||||||
|
|
||||||
|
cy.findByText("No notes yet");
|
||||||
|
});
|
||||||
|
});
|
5
cypress/fixtures/example.json
Normal file
|
@ -0,0 +1,5 @@
|
||||||
|
{
|
||||||
|
"name": "Using fixtures to represent data",
|
||||||
|
"email": "hello@cypress.io",
|
||||||
|
"body": "Fixtures are a great way to mock data for responses to routes"
|
||||||
|
}
|
25
cypress/plugins/index.ts
Normal file
|
@ -0,0 +1,25 @@
|
||||||
|
module.exports = (
|
||||||
|
on: Cypress.PluginEvents,
|
||||||
|
config: Cypress.PluginConfigOptions
|
||||||
|
) => {
|
||||||
|
const isDev = config.watchForFileChanges;
|
||||||
|
const port = process.env.PORT ?? (isDev ? "3000" : "8811");
|
||||||
|
const configOverrides: Partial<Cypress.PluginConfigOptions> = {
|
||||||
|
baseUrl: `http://localhost:${port}`,
|
||||||
|
integrationFolder: "cypress/e2e",
|
||||||
|
video: !process.env.CI,
|
||||||
|
screenshotOnRunFailure: !process.env.CI,
|
||||||
|
};
|
||||||
|
Object.assign(config, configOverrides);
|
||||||
|
|
||||||
|
// To use this:
|
||||||
|
// cy.task('log', whateverYouWantInTheTerminal)
|
||||||
|
on("task", {
|
||||||
|
log(message) {
|
||||||
|
console.log(message);
|
||||||
|
return null;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return config;
|
||||||
|
};
|
77
cypress/support/commands.ts
Normal file
|
@ -0,0 +1,77 @@
|
||||||
|
import faker from "@faker-js/faker";
|
||||||
|
|
||||||
|
declare global {
|
||||||
|
namespace Cypress {
|
||||||
|
interface Chainable {
|
||||||
|
/**
|
||||||
|
* Logs in with a random user. Yields the user and adds an alias to the user
|
||||||
|
*
|
||||||
|
* @returns {typeof login}
|
||||||
|
* @memberof Chainable
|
||||||
|
* @example
|
||||||
|
* cy.login()
|
||||||
|
* @example
|
||||||
|
* cy.login({ email: 'whatever@example.com' })
|
||||||
|
*/
|
||||||
|
login: typeof login;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Deletes the current @user
|
||||||
|
*
|
||||||
|
* @returns {typeof cleanupUser}
|
||||||
|
* @memberof Chainable
|
||||||
|
* @example
|
||||||
|
* cy.cleanupUser()
|
||||||
|
* @example
|
||||||
|
* cy.cleanupUser({ email: 'whatever@example.com' })
|
||||||
|
*/
|
||||||
|
cleanupUser: typeof cleanupUser;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function login({
|
||||||
|
email = faker.internet.email(undefined, undefined, "example.com"),
|
||||||
|
}: {
|
||||||
|
email?: string;
|
||||||
|
} = {}) {
|
||||||
|
cy.then(() => ({ email })).as("user");
|
||||||
|
cy.exec(
|
||||||
|
`node --require esbuild-register ./cypress/support/create-user.ts "${email}"`
|
||||||
|
).then(({ stdout }) => {
|
||||||
|
const cookieValue = stdout
|
||||||
|
.replace(/.*<cookie>(?<cookieValue>.*)<\/cookie>.*/s, "$<cookieValue>")
|
||||||
|
.trim();
|
||||||
|
cy.setCookie("__session", cookieValue);
|
||||||
|
});
|
||||||
|
return cy.get("@user");
|
||||||
|
}
|
||||||
|
|
||||||
|
function cleanupUser({ email }: { email?: string } = {}) {
|
||||||
|
if (email) {
|
||||||
|
deleteUserByEmail(email);
|
||||||
|
} else {
|
||||||
|
cy.get("@user").then((user) => {
|
||||||
|
const email = (user as { email?: string }).email;
|
||||||
|
if (email) {
|
||||||
|
deleteUserByEmail(email);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
cy.clearCookie("__session");
|
||||||
|
}
|
||||||
|
|
||||||
|
function deleteUserByEmail(email: string) {
|
||||||
|
cy.exec(
|
||||||
|
`node --require esbuild-register ./cypress/support/delete-user.ts "${email}"`
|
||||||
|
);
|
||||||
|
cy.clearCookie("__session");
|
||||||
|
}
|
||||||
|
|
||||||
|
Cypress.Commands.add("login", login);
|
||||||
|
Cypress.Commands.add("cleanupUser", cleanupUser);
|
||||||
|
|
||||||
|
/*
|
||||||
|
eslint
|
||||||
|
@typescript-eslint/no-namespace: "off",
|
||||||
|
*/
|
47
cypress/support/create-user.ts
Normal file
|
@ -0,0 +1,47 @@
|
||||||
|
// Use this to create a new user and login with that user
|
||||||
|
// Simply call this with:
|
||||||
|
// node --require esbuild-register ./cypress/support/create-user.ts username@example.com
|
||||||
|
// and it will log out the cookie value you can use to interact with the server
|
||||||
|
// as that new user.
|
||||||
|
|
||||||
|
import { parse } from "cookie";
|
||||||
|
import { installGlobals } from "@remix-run/node/globals";
|
||||||
|
import { createUserSession } from "~/session.server";
|
||||||
|
import { createUser } from "~/models/user.server";
|
||||||
|
|
||||||
|
installGlobals();
|
||||||
|
|
||||||
|
async function createAndLogin(email: string) {
|
||||||
|
if (!email) {
|
||||||
|
throw new Error("email required for login");
|
||||||
|
}
|
||||||
|
if (!email.endsWith("@example.com")) {
|
||||||
|
throw new Error("All test emails must end in @example.com");
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = await createUser(email, "myreallystrongpassword");
|
||||||
|
|
||||||
|
const response = await createUserSession({
|
||||||
|
request: new Request(""),
|
||||||
|
userId: user.id,
|
||||||
|
remember: false,
|
||||||
|
redirectTo: "/",
|
||||||
|
});
|
||||||
|
|
||||||
|
const cookieValue = response.headers.get("Set-Cookie");
|
||||||
|
if (!cookieValue) {
|
||||||
|
throw new Error("Cookie missing from createUserSession response");
|
||||||
|
}
|
||||||
|
const parsedCookie = parse(cookieValue);
|
||||||
|
// we log it like this so our cypress command can parse it out and set it as
|
||||||
|
// the cookie value.
|
||||||
|
console.log(
|
||||||
|
`
|
||||||
|
<cookie>
|
||||||
|
${parsedCookie.__session}
|
||||||
|
</cookie>
|
||||||
|
`.trim()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
createAndLogin(process.argv[2]);
|
22
cypress/support/delete-user.ts
Normal file
|
@ -0,0 +1,22 @@
|
||||||
|
// Use this to delete a user by their email
|
||||||
|
// Simply call this with:
|
||||||
|
// node --require esbuild-register ./cypress/support/delete-user.ts username@example.com
|
||||||
|
// and that user will get deleted
|
||||||
|
|
||||||
|
import { installGlobals } from "@remix-run/node/globals";
|
||||||
|
import { prisma } from "~/db.server";
|
||||||
|
|
||||||
|
installGlobals();
|
||||||
|
|
||||||
|
async function deleteUser(email: string) {
|
||||||
|
if (!email) {
|
||||||
|
throw new Error("email required for login");
|
||||||
|
}
|
||||||
|
if (!email.endsWith("@example.com")) {
|
||||||
|
throw new Error("All test emails must end in @example.com");
|
||||||
|
}
|
||||||
|
|
||||||
|
await prisma.user.delete({ where: { email } });
|
||||||
|
}
|
||||||
|
|
||||||
|
deleteUser(process.argv[2]);
|
2
cypress/support/index.ts
Normal file
|
@ -0,0 +1,2 @@
|
||||||
|
import "@testing-library/cypress/add-commands";
|
||||||
|
import "./commands";
|
31
cypress/tsconfig.json
Normal file
|
@ -0,0 +1,31 @@
|
||||||
|
{
|
||||||
|
"exclude": [
|
||||||
|
"../node_modules/@types/jest",
|
||||||
|
"../node_modules/@testing-library/jest-dom"
|
||||||
|
],
|
||||||
|
"include": [
|
||||||
|
"./index.ts",
|
||||||
|
"e2e/**/*",
|
||||||
|
"plugins/**/*",
|
||||||
|
"support/**/*",
|
||||||
|
"../node_modules/cypress",
|
||||||
|
"../node_modules/@testing-library/cypress"
|
||||||
|
],
|
||||||
|
"compilerOptions": {
|
||||||
|
"baseUrl": ".",
|
||||||
|
"noEmit": true,
|
||||||
|
"types": ["node", "cypress", "@testing-library/cypress"],
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"jsx": "react",
|
||||||
|
"moduleResolution": "node",
|
||||||
|
"target": "es2019",
|
||||||
|
"strict": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"resolveJsonModule": true,
|
||||||
|
"typeRoots": ["../types", "../node_modules/@types"],
|
||||||
|
|
||||||
|
"paths": {
|
||||||
|
"~/*": ["../app/*"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
13
docker-compose.yml
Normal file
|
@ -0,0 +1,13 @@
|
||||||
|
version: "3.7"
|
||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:latest
|
||||||
|
restart: always
|
||||||
|
environment:
|
||||||
|
- POSTGRES_USER=postgres
|
||||||
|
- POSTGRES_PASSWORD=postgres
|
||||||
|
- POSTGRES_DB=postgres
|
||||||
|
ports:
|
||||||
|
- "5432:5432"
|
||||||
|
volumes:
|
||||||
|
- ./postgres-data:/var/lib/postgresql/data
|
50
fly.toml
Normal file
|
@ -0,0 +1,50 @@
|
||||||
|
app = "border-server-a1df"
|
||||||
|
kill_signal = "SIGINT"
|
||||||
|
kill_timeout = 5
|
||||||
|
processes = [ ]
|
||||||
|
|
||||||
|
[env]
|
||||||
|
PORT = "8080"
|
||||||
|
|
||||||
|
[deploy]
|
||||||
|
release_command = "npx prisma migrate deploy"
|
||||||
|
|
||||||
|
[experimental]
|
||||||
|
allowed_public_ports = [ ]
|
||||||
|
auto_rollback = true
|
||||||
|
|
||||||
|
[[services]]
|
||||||
|
internal_port = 8_080
|
||||||
|
processes = [ "app" ]
|
||||||
|
protocol = "tcp"
|
||||||
|
script_checks = [ ]
|
||||||
|
|
||||||
|
[services.concurrency]
|
||||||
|
hard_limit = 25
|
||||||
|
soft_limit = 20
|
||||||
|
type = "connections"
|
||||||
|
|
||||||
|
[[services.ports]]
|
||||||
|
handlers = [ "http" ]
|
||||||
|
port = 80
|
||||||
|
force_https = true
|
||||||
|
|
||||||
|
[[services.ports]]
|
||||||
|
handlers = [ "tls", "http" ]
|
||||||
|
port = 443
|
||||||
|
|
||||||
|
[[services.tcp_checks]]
|
||||||
|
grace_period = "1s"
|
||||||
|
interval = "15s"
|
||||||
|
restart_limit = 0
|
||||||
|
timeout = "2s"
|
||||||
|
|
||||||
|
[[services.http_checks]]
|
||||||
|
interval = 10_000
|
||||||
|
grace_period = "5s"
|
||||||
|
method = "get"
|
||||||
|
path = "/healthcheck"
|
||||||
|
protocol = "http"
|
||||||
|
timeout = 2_000
|
||||||
|
tls_skip_verify = false
|
||||||
|
headers = { }
|
7
mocks/README.md
Normal file
|
@ -0,0 +1,7 @@
|
||||||
|
# Mocks
|
||||||
|
|
||||||
|
Use this to mock any third party HTTP resources that you don't have running locally and want to have mocked for local development as well as tests.
|
||||||
|
|
||||||
|
Learn more about how to use this at [mswjs.io](https://mswjs.io/)
|
||||||
|
|
||||||
|
For an extensive example, see the [source code for kentcdodds.com](https://github.com/kentcdodds/kentcdodds.com/blob/main/mocks/start.ts)
|
2
mocks/index.js
Normal file
|
@ -0,0 +1,2 @@
|
||||||
|
require("esbuild-register/dist/node").register();
|
||||||
|
require("./start");
|
9
mocks/start.ts
Normal file
|
@ -0,0 +1,9 @@
|
||||||
|
import { setupServer } from "msw/node";
|
||||||
|
|
||||||
|
const server = setupServer();
|
||||||
|
|
||||||
|
server.listen({ onUnhandledRequest: "warn" });
|
||||||
|
console.info("🔶 Mock server running");
|
||||||
|
|
||||||
|
process.once("SIGINT", () => server.close());
|
||||||
|
process.once("SIGTERM", () => server.close());
|
41
other/pm2.config.js
Normal file
|
@ -0,0 +1,41 @@
|
||||||
|
const env = {
|
||||||
|
NODE_ENV: process.env.NODE_ENV ?? "development",
|
||||||
|
FORCE_COLOR: "1",
|
||||||
|
};
|
||||||
|
module.exports = {
|
||||||
|
apps: [
|
||||||
|
{
|
||||||
|
name: "Server",
|
||||||
|
script: [
|
||||||
|
"node",
|
||||||
|
"--inspect",
|
||||||
|
"--require ./node_modules/dotenv/config",
|
||||||
|
"--require ./mocks",
|
||||||
|
"./build/server.js",
|
||||||
|
]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(" "),
|
||||||
|
watch: ["./mocks/**/*.ts", "./build/server.js", "./.env"],
|
||||||
|
env,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Server Build",
|
||||||
|
script: "npm run build:server -- --watch",
|
||||||
|
ignore_watch: ["."],
|
||||||
|
env,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Remix",
|
||||||
|
script: "cross-env NODE_ENV=development remix watch",
|
||||||
|
ignore_watch: ["."],
|
||||||
|
env,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Tailwind",
|
||||||
|
script: "npm run generate:css -- --watch",
|
||||||
|
autorestart: false,
|
||||||
|
ignore_watch: ["."],
|
||||||
|
env,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
10968
package-lock.json
generated
Normal file
90
package.json
Normal file
|
@ -0,0 +1,90 @@
|
||||||
|
{
|
||||||
|
"name": "border-server-a1df",
|
||||||
|
"private": true,
|
||||||
|
"description": "",
|
||||||
|
"license": "",
|
||||||
|
"sideEffects": false,
|
||||||
|
"scripts": {
|
||||||
|
"build": "run-s build:*",
|
||||||
|
"build:css": "npm run generate:css -- --minify",
|
||||||
|
"build:remix": "remix build",
|
||||||
|
"build:server": "esbuild --platform=node --format=cjs ./server.ts --outdir=build",
|
||||||
|
"dev": "pm2-dev ./other/pm2.config.js",
|
||||||
|
"docker": "docker-compose up -d",
|
||||||
|
"format": "prettier --write .",
|
||||||
|
"generate:css": "tailwindcss -o ./app/styles/tailwind.css",
|
||||||
|
"postinstall": "remix setup node",
|
||||||
|
"lint": "eslint --cache --cache-location ./node_modules/.cache/eslint .",
|
||||||
|
"setup": "prisma migrate dev && prisma db seed",
|
||||||
|
"start": "cross-env NODE_ENV=production node ./build/server.js",
|
||||||
|
"start:mocks": "cross-env NODE_ENV=production node --require ./mocks --require dotenv/config ./build/server.js",
|
||||||
|
"test": "vitest",
|
||||||
|
"test:e2e:dev": "start-server-and-test dev http://localhost:3000 \"cypress open\"",
|
||||||
|
"pretest:e2e:run": "npm run build",
|
||||||
|
"test:e2e:run": "cross-env PORT=8811 start-server-and-test start:mocks http://localhost:8811 \"cypress run\"",
|
||||||
|
"typecheck": "tsc -b && tsc -b cypress",
|
||||||
|
"validate": "run-p \"test -- --run\" lint typecheck test:e2e:run"
|
||||||
|
},
|
||||||
|
"prettier": {},
|
||||||
|
"eslintIgnore": [
|
||||||
|
"/node_modules",
|
||||||
|
"/build",
|
||||||
|
"/public/build"
|
||||||
|
],
|
||||||
|
"dependencies": {
|
||||||
|
"@node-rs/bcrypt": "^1.6.0",
|
||||||
|
"@prisma/client": "^3.11.0",
|
||||||
|
"@reach/alert": "^0.16.0",
|
||||||
|
"@remix-run/express": "^1.3.2",
|
||||||
|
"@remix-run/react": "^1.3.2",
|
||||||
|
"compression": "^1.7.4",
|
||||||
|
"cross-env": "^7.0.3",
|
||||||
|
"express": "^4.17.3",
|
||||||
|
"morgan": "^1.10.0",
|
||||||
|
"react": "^17.0.2",
|
||||||
|
"react-dom": "^17.0.2",
|
||||||
|
"remix": "^1.3.2",
|
||||||
|
"tiny-invariant": "^1.2.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@faker-js/faker": "^6.0.0",
|
||||||
|
"@remix-run/dev": "^1.3.2",
|
||||||
|
"@remix-run/eslint-config": "^1.3.2",
|
||||||
|
"@testing-library/cypress": "^8.0.2",
|
||||||
|
"@testing-library/jest-dom": "^5.16.2",
|
||||||
|
"@testing-library/react": "^12.1.4",
|
||||||
|
"@testing-library/user-event": "^13.5.0",
|
||||||
|
"@types/compression": "^1.7.2",
|
||||||
|
"@types/eslint": "^8.4.1",
|
||||||
|
"@types/express": "^4.17.13",
|
||||||
|
"@types/morgan": "^1.9.3",
|
||||||
|
"@types/react": "^17.0.40",
|
||||||
|
"@types/react-dom": "^17.0.13",
|
||||||
|
"@vitejs/plugin-react": "^1.2.0",
|
||||||
|
"c8": "^7.11.0",
|
||||||
|
"cypress": "^9.5.2",
|
||||||
|
"dotenv": "^16.0.0",
|
||||||
|
"esbuild": "^0.14.27",
|
||||||
|
"esbuild-register": "^3.3.2",
|
||||||
|
"eslint": "^8.11.0",
|
||||||
|
"eslint-config-prettier": "^8.5.0",
|
||||||
|
"happy-dom": "^2.49.0",
|
||||||
|
"msw": "^0.39.2",
|
||||||
|
"npm-run-all": "^4.1.5",
|
||||||
|
"pm2": "^5.2.0",
|
||||||
|
"prettier": "^2.6.0",
|
||||||
|
"prettier-plugin-tailwindcss": "^0.1.8",
|
||||||
|
"prisma": "^3.11.0",
|
||||||
|
"start-server-and-test": "^1.14.0",
|
||||||
|
"tailwindcss": "^3.0.23",
|
||||||
|
"typescript": "^4.6.2",
|
||||||
|
"vite-tsconfig-paths": "^3.4.1",
|
||||||
|
"vitest": "^0.7.4"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=14"
|
||||||
|
},
|
||||||
|
"prisma": {
|
||||||
|
"seed": "node --require esbuild-register prisma/seed.ts"
|
||||||
|
}
|
||||||
|
}
|
39
prisma/migrations/20220224172159_init/migration.sql
Normal file
|
@ -0,0 +1,39 @@
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "User" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"email" TEXT NOT NULL,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "User_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "Password" (
|
||||||
|
"hash" TEXT NOT NULL,
|
||||||
|
"userId" TEXT NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "Note" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"title" TEXT NOT NULL,
|
||||||
|
"body" TEXT NOT NULL,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
"userId" TEXT NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "Note_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "Password_userId_key" ON "Password"("userId");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "Password" ADD CONSTRAINT "Password_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "Note" ADD CONSTRAINT "Note_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
3
prisma/migrations/migration_lock.toml
Normal file
|
@ -0,0 +1,3 @@
|
||||||
|
# Please do not edit this file manually
|
||||||
|
# It should be added in your version-control system (i.e. Git)
|
||||||
|
provider = "postgresql"
|
38
prisma/schema.prisma
Normal file
|
@ -0,0 +1,38 @@
|
||||||
|
datasource db {
|
||||||
|
provider = "postgresql"
|
||||||
|
url = env("DATABASE_URL")
|
||||||
|
}
|
||||||
|
|
||||||
|
generator client {
|
||||||
|
provider = "prisma-client-js"
|
||||||
|
}
|
||||||
|
|
||||||
|
model User {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
email String @unique
|
||||||
|
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
|
password Password?
|
||||||
|
notes Note[]
|
||||||
|
}
|
||||||
|
|
||||||
|
model Password {
|
||||||
|
hash String
|
||||||
|
|
||||||
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade, onUpdate: Cascade)
|
||||||
|
userId String @unique
|
||||||
|
}
|
||||||
|
|
||||||
|
model Note {
|
||||||
|
id String @id @default(cuid())
|
||||||
|
title String
|
||||||
|
body String
|
||||||
|
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade, onUpdate: Cascade)
|
||||||
|
userId String
|
||||||
|
}
|
53
prisma/seed.ts
Normal file
|
@ -0,0 +1,53 @@
|
||||||
|
import { PrismaClient } from "@prisma/client";
|
||||||
|
import bcrypt from "@node-rs/bcrypt";
|
||||||
|
|
||||||
|
const prisma = new PrismaClient();
|
||||||
|
|
||||||
|
async function seed() {
|
||||||
|
const email = "rachel@remix.run";
|
||||||
|
|
||||||
|
// cleanup the existing database
|
||||||
|
await prisma.user.delete({ where: { email } }).catch(() => {
|
||||||
|
// no worries if it doesn't exist yet
|
||||||
|
});
|
||||||
|
|
||||||
|
const hashedPassword = await bcrypt.hash("racheliscool", 10);
|
||||||
|
|
||||||
|
const user = await prisma.user.create({
|
||||||
|
data: {
|
||||||
|
email,
|
||||||
|
password: {
|
||||||
|
create: {
|
||||||
|
hash: hashedPassword,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await prisma.note.create({
|
||||||
|
data: {
|
||||||
|
title: "My first note",
|
||||||
|
body: "Hello, world!",
|
||||||
|
userId: user.id,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await prisma.note.create({
|
||||||
|
data: {
|
||||||
|
title: "My second note",
|
||||||
|
body: "Hello, world!",
|
||||||
|
userId: user.id,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log(`Database has been seeded. 🌱`);
|
||||||
|
}
|
||||||
|
|
||||||
|
seed()
|
||||||
|
.catch((e) => {
|
||||||
|
console.error(e);
|
||||||
|
process.exit(1);
|
||||||
|
})
|
||||||
|
.finally(async () => {
|
||||||
|
await prisma.$disconnect();
|
||||||
|
});
|
BIN
public/favicon.ico
Normal file
After Width: | Height: | Size: 17 KiB |
BIN
public/images/00b9a62e09a1e452d6840170849e8ac06f6d3ef5.png
Normal file
After Width: | Height: | Size: 526 KiB |
BIN
public/images/083c19cc935001ee0508aff3b948da62b6a093f6.png
Normal file
After Width: | Height: | Size: 897 KiB |
BIN
public/images/18717998311ff5e68b1246dbdb43cbc0fa00a35d.png
Normal file
After Width: | Height: | Size: 573 KiB |
BIN
public/images/27ef3d62a0e42bf4ac60d426f2f172e1790ec0fd.png
Normal file
After Width: | Height: | Size: 236 KiB |
BIN
public/images/2d876cff5940a8724340a5798c1c8e48880c675f.png
Normal file
After Width: | Height: | Size: 622 KiB |
BIN
public/images/359032c610e13a8f370594b200b9ddf8b29aa8af.png
Normal file
After Width: | Height: | Size: 588 KiB |
BIN
public/images/3fd73db5d33e9b6597e6975eb654e89b89b5db5c.png
Normal file
After Width: | Height: | Size: 1.9 MiB |
BIN
public/images/420efee31f0b0a3fe39cb7409dbe9c3a3e0a0e3a.png
Normal file
After Width: | Height: | Size: 1.7 KiB |
BIN
public/images/46461aaea39b18a4a3da2e6d3cf253006f2d6193.png
Normal file
After Width: | Height: | Size: 653 KiB |
BIN
public/images/4718aad9a4b04c3cfb049bb7cbf2bd35c2e2eb11.png
Normal file
After Width: | Height: | Size: 569 KiB |
BIN
public/images/537ab433b4dbf1c225e5809ad53d690ee73438d8.png
Normal file
After Width: | Height: | Size: 346 KiB |
BIN
public/images/558efce86af3043bda6ac5078e1801dc7b587de7.png
Normal file
After Width: | Height: | Size: 1.9 MiB |
BIN
public/images/68439f85ae83ce6429b845234e28de62a88b1f88.png
Normal file
After Width: | Height: | Size: 686 KiB |
BIN
public/images/950172e5379f52079835a2b295e93de1d8a8fbf3.png
Normal file
After Width: | Height: | Size: 140 KiB |
BIN
public/images/984f18d4bcc76669bcbd8971f962d1b75716dd11.png
Normal file
After Width: | Height: | Size: 11 KiB |
BIN
public/images/babb8c618b2c8eafaad9bc3fac3304a1837ac4fb.png
Normal file
After Width: | Height: | Size: 1 MiB |
BIN
public/images/bd04ee3a8e6c35c39f8670c034a5ea7fd15ca3f1.png
Normal file
After Width: | Height: | Size: 938 KiB |
BIN
public/images/beaee5e90d93bfafa5f5f55acb23abfd28ad180c.png
Normal file
After Width: | Height: | Size: 470 KiB |
BIN
public/images/c30260bb120bf1379f075802653c8eb86da7a7e9.png
Normal file
After Width: | Height: | Size: 92 KiB |
BIN
public/images/e0de1bf39208a3c1230bca5bc69561e9d2f0971f.png
Normal file
After Width: | Height: | Size: 7.4 KiB |
BIN
public/images/e89b3a70625c980c3d68869f5cdb1da9baa447f8.png
Normal file
After Width: | Height: | Size: 36 KiB |
7
remix.config.js
Normal file
|
@ -0,0 +1,7 @@
|
||||||
|
/**
|
||||||
|
* @type {import('@remix-run/dev').AppConfig}
|
||||||
|
*/
|
||||||
|
module.exports = {
|
||||||
|
cacheDirectory: "./node_modules/.cache/remix",
|
||||||
|
ignoredRouteFiles: [".*", "**/*.css", "**/*.test.{js,jsx,ts,tsx}"],
|
||||||
|
};
|
2
remix.env.d.ts
vendored
Normal file
|
@ -0,0 +1,2 @@
|
||||||
|
/// <reference types="@remix-run/dev" />
|
||||||
|
/// <reference types="@remix-run/node/globals" />
|
105
server.ts
Normal file
|
@ -0,0 +1,105 @@
|
||||||
|
import path from "path";
|
||||||
|
import express from "express";
|
||||||
|
import compression from "compression";
|
||||||
|
import morgan from "morgan";
|
||||||
|
import { createRequestHandler } from "@remix-run/express";
|
||||||
|
|
||||||
|
const app = express();
|
||||||
|
|
||||||
|
app.use((req, res, next) => {
|
||||||
|
// helpful headers:
|
||||||
|
res.set("x-fly-region", process.env.FLY_REGION ?? "unknown");
|
||||||
|
res.set("Strict-Transport-Security", `max-age=${60 * 60 * 24 * 365 * 100}`);
|
||||||
|
|
||||||
|
// /clean-urls/ -> /clean-urls
|
||||||
|
if (req.path.endsWith("/") && req.path.length > 1) {
|
||||||
|
const query = req.url.slice(req.path.length);
|
||||||
|
const safepath = req.path.slice(0, -1).replace(/\/+/g, "/");
|
||||||
|
res.redirect(301, safepath + query);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
next();
|
||||||
|
});
|
||||||
|
|
||||||
|
// if we're not in the primary region, then we need to make sure all
|
||||||
|
// non-GET/HEAD/OPTIONS requests hit the primary region rather than read-only
|
||||||
|
// Postgres DBs.
|
||||||
|
// learn more: https://fly.io/docs/getting-started/multi-region-databases/#replay-the-request
|
||||||
|
app.all("*", function getReplayResponse(req, res, next) {
|
||||||
|
const { method, path: pathname } = req;
|
||||||
|
const { PRIMARY_REGION, FLY_REGION } = process.env;
|
||||||
|
|
||||||
|
const isMethodReplayable = !["GET", "OPTIONS", "HEAD"].includes(method);
|
||||||
|
const isReadOnlyRegion =
|
||||||
|
FLY_REGION && PRIMARY_REGION && FLY_REGION !== PRIMARY_REGION;
|
||||||
|
|
||||||
|
const shouldReplay = isMethodReplayable && isReadOnlyRegion;
|
||||||
|
|
||||||
|
if (!shouldReplay) return next();
|
||||||
|
|
||||||
|
const logInfo = {
|
||||||
|
pathname,
|
||||||
|
method,
|
||||||
|
PRIMARY_REGION,
|
||||||
|
FLY_REGION,
|
||||||
|
};
|
||||||
|
console.info(`Replaying:`, logInfo);
|
||||||
|
res.set("fly-replay", `region=${PRIMARY_REGION}`);
|
||||||
|
return res.sendStatus(409);
|
||||||
|
});
|
||||||
|
|
||||||
|
app.use(compression());
|
||||||
|
|
||||||
|
// http://expressjs.com/en/advanced/best-practice-security.html#at-a-minimum-disable-x-powered-by-header
|
||||||
|
app.disable("x-powered-by");
|
||||||
|
|
||||||
|
// Remix fingerprints its assets so we can cache forever.
|
||||||
|
app.use(
|
||||||
|
"/build",
|
||||||
|
express.static("public/build", { immutable: true, maxAge: "1y" })
|
||||||
|
);
|
||||||
|
|
||||||
|
// Everything else (like favicon.ico) is cached for an hour. You may want to be
|
||||||
|
// more aggressive with this caching.
|
||||||
|
app.use(express.static("public", { maxAge: "1h" }));
|
||||||
|
|
||||||
|
app.use(morgan("tiny"));
|
||||||
|
|
||||||
|
const MODE = process.env.NODE_ENV;
|
||||||
|
const BUILD_DIR = path.join(process.cwd(), "build");
|
||||||
|
|
||||||
|
app.all(
|
||||||
|
"*",
|
||||||
|
MODE === "production"
|
||||||
|
? createRequestHandler({ build: require(BUILD_DIR) })
|
||||||
|
: (...args) => {
|
||||||
|
purgeRequireCache();
|
||||||
|
const requestHandler = createRequestHandler({
|
||||||
|
build: require(BUILD_DIR),
|
||||||
|
mode: MODE,
|
||||||
|
});
|
||||||
|
return requestHandler(...args);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
const port = process.env.PORT || 3000;
|
||||||
|
|
||||||
|
app.listen(port, () => {
|
||||||
|
// require the built app so we're ready when the first request comes in
|
||||||
|
require(BUILD_DIR);
|
||||||
|
console.log(`✅ app ready: http://localhost:${port}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
function purgeRequireCache() {
|
||||||
|
// purge require cache on requests for "server side HMR" this won't const
|
||||||
|
// you have in-memory objects between requests in development,
|
||||||
|
// alternatively you can set up nodemon/pm2-dev to restart the server on
|
||||||
|
// file changes, we prefer the DX of this though, so we've included it
|
||||||
|
// for you by default
|
||||||
|
for (const key in require.cache) {
|
||||||
|
if (key.startsWith(BUILD_DIR)) {
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
|
||||||
|
delete require.cache[key];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
7
tailwind.config.js
Normal file
|
@ -0,0 +1,7 @@
|
||||||
|
module.exports = {
|
||||||
|
content: ["./app/**/*.{ts,tsx,jsx,js}"],
|
||||||
|
theme: {
|
||||||
|
extend: {},
|
||||||
|
},
|
||||||
|
plugins: [],
|
||||||
|
};
|
4
test/setup-test-env.ts
Normal file
|
@ -0,0 +1,4 @@
|
||||||
|
import { installGlobals } from "@remix-run/node/globals";
|
||||||
|
import "@testing-library/jest-dom/extend-expect";
|
||||||
|
|
||||||
|
installGlobals();
|
24
tsconfig.json
Normal file
|
@ -0,0 +1,24 @@
|
||||||
|
{
|
||||||
|
"exclude": ["./cypress"],
|
||||||
|
"include": ["remix.env.d.ts", "**/*.ts", "**/*.tsx"],
|
||||||
|
"compilerOptions": {
|
||||||
|
"lib": ["DOM", "DOM.Iterable", "ES2019"],
|
||||||
|
"types": ["vitest/globals"],
|
||||||
|
"isolatedModules": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"jsx": "react-jsx",
|
||||||
|
"module": "ES2020",
|
||||||
|
"moduleResolution": "node",
|
||||||
|
"resolveJsonModule": true,
|
||||||
|
"target": "ES2019",
|
||||||
|
"strict": true,
|
||||||
|
"baseUrl": ".",
|
||||||
|
"paths": {
|
||||||
|
"~/*": ["./app/*"]
|
||||||
|
},
|
||||||
|
"skipLibCheck": true,
|
||||||
|
|
||||||
|
// Remix takes care of building everything in `remix build`.
|
||||||
|
"noEmit": true
|
||||||
|
}
|
||||||
|
}
|
15
vitest.config.ts
Normal file
|
@ -0,0 +1,15 @@
|
||||||
|
/// <reference types="vitest" />
|
||||||
|
/// <reference types="vite/client" />
|
||||||
|
|
||||||
|
import { defineConfig } from "vite";
|
||||||
|
import react from "@vitejs/plugin-react";
|
||||||
|
import tsconfigPaths from "vite-tsconfig-paths";
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [react(), tsconfigPaths()],
|
||||||
|
test: {
|
||||||
|
globals: true,
|
||||||
|
environment: "happy-dom",
|
||||||
|
setupFiles: ["./test/setup-test-env.ts"],
|
||||||
|
},
|
||||||
|
});
|