Compare commits
2 commits
83bc981152
...
6591e0987f
Author | SHA1 | Date | |
---|---|---|---|
6591e0987f | |||
d369880579 |
|
@ -1,7 +0,0 @@
|
|||
/node_modules
|
||||
*.log
|
||||
.DS_Store
|
||||
.env
|
||||
/.cache
|
||||
/public/build
|
||||
/build
|
19
.eslintrc.js
|
@ -1,19 +0,0 @@
|
|||
/**
|
||||
* @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,
|
||||
},
|
||||
},
|
||||
};
|
3
.eslintrc.json
Normal file
|
@ -0,0 +1,3 @@
|
|||
{
|
||||
"extends": "next/core-web-vitals"
|
||||
}
|
211
.github/workflows/deploy.yml
vendored
|
@ -1,211 +0,0 @@
|
|||
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 }}
|
36
.gitignore
vendored
|
@ -1,11 +1,33 @@
|
|||
node_modules
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
/.pnp
|
||||
.pnp.js
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# next.js
|
||||
/.next/
|
||||
/out/
|
||||
|
||||
# production
|
||||
/build
|
||||
/public/build
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
*.pem
|
||||
|
||||
# debug
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
.pnpm-debug.log*
|
||||
|
||||
# local env files
|
||||
.env*.local
|
||||
.env
|
||||
|
||||
/cypress/screenshots
|
||||
/cypress/videos
|
||||
/postgres-data
|
||||
|
||||
/app/styles/tailwind.css
|
||||
# vercel
|
||||
.vercel
|
||||
|
|
|
@ -1,11 +0,0 @@
|
|||
node_modules
|
||||
|
||||
/build
|
||||
/public/build
|
||||
.env
|
||||
|
||||
/cypress/screenshots
|
||||
/cypress/videos
|
||||
/postgres-data
|
||||
|
||||
/app/styles/tailwind.css
|
53
Dockerfile
|
@ -1,53 +0,0 @@
|
|||
# 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"]
|
201
README.md
|
@ -1,197 +1,34 @@
|
|||
# Remix Blues Stack
|
||||
This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).
|
||||
|
||||
![The Remix Blues Stack](https://repository-images.githubusercontent.com/461012689/37d5bd8b-fa9c-4ab0-893c-f0a199d5012d)
|
||||
## Getting Started
|
||||
|
||||
Learn more about [Remix Stacks](https://remix.run/stacks).
|
||||
First, run the development server:
|
||||
|
||||
```
|
||||
npx create-remix --template remix-run/blues-stack
|
||||
```bash
|
||||
npm run dev
|
||||
# or
|
||||
yarn dev
|
||||
```
|
||||
|
||||
## What's in the stack
|
||||
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
|
||||
|
||||
- [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)
|
||||
You can start editing the page by modifying `pages/index.js`. The page auto-updates as you edit the file.
|
||||
|
||||
Not a fan of bits of the stack? Fork it, change it, and use `npx create-remix --template your/repo`! Make it your own.
|
||||
[API routes](https://nextjs.org/docs/api-routes/introduction) can be accessed on [http://localhost:3000/api/hello](http://localhost:3000/api/hello). This endpoint can be edited in `pages/api/hello.js`.
|
||||
|
||||
## Development
|
||||
The `pages/api` directory is mapped to `/api/*`. Files in this directory are treated as [API routes](https://nextjs.org/docs/api-routes/introduction) instead of React pages.
|
||||
|
||||
- Start the Postgres Database in [Docker](https://www.docker.com/get-started):
|
||||
## Learn More
|
||||
|
||||
```sh
|
||||
npm run docker
|
||||
```
|
||||
To learn more about Next.js, take a look at the following resources:
|
||||
|
||||
> **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.
|
||||
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
|
||||
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
|
||||
|
||||
- Initial setup:
|
||||
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome!
|
||||
|
||||
```sh
|
||||
npm run setup
|
||||
```
|
||||
## Deploy on Vercel
|
||||
|
||||
- Start dev server:
|
||||
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
|
||||
|
||||
```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.
|
||||
Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.
|
||||
|
|
|
@ -1,62 +0,0 @@
|
|||
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 };
|
|
@ -1,124 +0,0 @@
|
|||
import axios from 'axios';
|
||||
import { prisma } from "~/db.server";
|
||||
import { createUserSession } from '~/session.server';
|
||||
|
||||
export interface DiscordUser {
|
||||
id: string;
|
||||
username: string;
|
||||
discriminator: string;
|
||||
avatar: string;
|
||||
bot?: boolean;
|
||||
system?: boolean;
|
||||
mfa_enabled?: boolean;
|
||||
}
|
||||
|
||||
export interface AccessTokenResponse {
|
||||
access_token: string;
|
||||
expires: number;
|
||||
refresh_token: string;
|
||||
}
|
||||
|
||||
export function getAccessToken(code: string): Promise<AccessTokenResponse> {
|
||||
return new Promise(
|
||||
(resolve, reject) => {
|
||||
const body = new FormData();
|
||||
body.append("grant_type", "authorization_code");
|
||||
body.append("code", code);
|
||||
body.append("redirect_url", process.env.DISCORD_REDIRECT_URI || "");
|
||||
|
||||
axios.post("https://discord.com/api/oauth2/token", body)
|
||||
.then((res) => {
|
||||
const { access_token, refresh_token, expires_in } = res.data;
|
||||
|
||||
resolve({
|
||||
access_token,
|
||||
refresh_token,
|
||||
expires: Date.now() + expires_in * 1000
|
||||
});
|
||||
})
|
||||
.catch(reject);
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
export async function authorize(access_code: string): Promise<AccessTokenResponse | undefined> {
|
||||
return new Promise(
|
||||
(resolve, reject) => {
|
||||
const formData = new FormData();
|
||||
|
||||
formData.append("client_id", process.env.DISCORD_CLIENT_ID || "");
|
||||
formData.append("client_secret", process.env.DISCORD_CLIENT_SECRET || "");
|
||||
formData.append("grant_type", "authorization_code");
|
||||
formData.append("redirect_uri", process.env.DISCORD_REDIRECT_URI || "");
|
||||
formData.append("scope", "identify");
|
||||
formData.append("code", access_code);
|
||||
|
||||
axios.post("https://discord.com/api/oauth2/token", formData)
|
||||
.then((res) => {
|
||||
const { access_token, refresh_token, expires_in } = res.data;
|
||||
|
||||
resolve({
|
||||
access_token,
|
||||
refresh_token,
|
||||
expires: Date.now() + expires_in * 1000
|
||||
});
|
||||
})
|
||||
.catch(reject);
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
export function getDiscordUser(token: string): Promise<DiscordUser> {
|
||||
return new Promise(
|
||||
(resolve, reject) => {
|
||||
axios.get("https://discord.com/api/users/@me", {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`
|
||||
}
|
||||
})
|
||||
.then(
|
||||
(res) => {
|
||||
resolve(res.data);
|
||||
}
|
||||
)
|
||||
.catch(reject);
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
export async function discordLogin(request: Request, code: string): Promise<Response> {
|
||||
return new Promise(
|
||||
(resolve, reject) => {
|
||||
getAccessToken(code)
|
||||
.then((token) => {
|
||||
getDiscordUser(token.access_token)
|
||||
.then(async (user) => {
|
||||
prisma.discordUser.upsert({
|
||||
create: {
|
||||
discord_id: user.id,
|
||||
access_token: token.access_token,
|
||||
refresh_token: token.refresh_token,
|
||||
expires: new Date(token.expires),
|
||||
username: user.username,
|
||||
discriminator: user.discriminator,
|
||||
},
|
||||
update: {
|
||||
discord_id: user.id,
|
||||
access_token: token.access_token,
|
||||
refresh_token: token.refresh_token,
|
||||
expires: new Date(token.expires),
|
||||
username: user.username,
|
||||
discriminator: user.discriminator,
|
||||
},
|
||||
where: {
|
||||
discord_id: user.id
|
||||
}
|
||||
})
|
||||
.then(async () => {
|
||||
resolve(await createUserSession({request, discord_id: user.id, redirectTo: '/'}));
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
)
|
||||
}
|
|
@ -1,4 +0,0 @@
|
|||
import { hydrate } from "react-dom";
|
||||
import { RemixBrowser } from "remix";
|
||||
|
||||
hydrate(<RemixBrowser />, document);
|
|
@ -1,21 +0,0 @@
|
|||
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,
|
||||
});
|
||||
}
|
|
@ -1,65 +0,0 @@
|
|||
|
||||
import { prisma } from "~/db.server";
|
||||
import type {User} from "@prisma/client";
|
||||
import { AccessTokenResponse, DiscordUser } from "~/discord/index";
|
||||
export type {User, Border} from "@prisma/client";
|
||||
|
||||
export async function getUserByDiscordId(discord_id: User["discord_id"]) {
|
||||
return prisma.user.findUnique({ where: { discord_id: discord_id || undefined }});
|
||||
}
|
||||
|
||||
export async function getUserById(id: User["id"]) {
|
||||
return prisma.user.findUnique({ where: { id } });
|
||||
}
|
||||
|
||||
/// SHOULD ONLY BE USED WITH A CORRESPONDING OAUTH TOKEN
|
||||
export async function createUser(discord_id: User["discord_id"]) {
|
||||
|
||||
return prisma.user.create({
|
||||
data: {
|
||||
discord_id
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function createDiscordLogin(discord_id: DiscordUser["id"], token_response: AccessTokenResponse) {
|
||||
return prisma.discordUser.create({
|
||||
data: {
|
||||
discord_id,
|
||||
access_token: token_response.access_token,
|
||||
refresh_token: token_response.refresh_token,
|
||||
expires: new Date(token_response.expires)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export type SessionInformation = {
|
||||
bearer_token: string,
|
||||
refresh_token: string
|
||||
};
|
||||
|
||||
export async function discordIdentify(bearer_token: string, refresh_token: string): Promise<DiscordUser | SessionInformation | undefined> {
|
||||
let user_info = await (
|
||||
await fetch("https://discord.com/api/users/@me", {
|
||||
headers: {
|
||||
Authorization: `Bearer ${bearer_token}`
|
||||
}
|
||||
})
|
||||
).json();
|
||||
|
||||
if (!user_info["id"]) {
|
||||
const form_data = new FormData();
|
||||
form_data.append("client_id", process.env.DISCORD_CLIENT_ID || "");
|
||||
form_data.append("client_secret", process.env.DISCORD_CLIENT_SECRET || "");
|
||||
form_data.append("grant_type", "refresh_token");
|
||||
form_data.append("refresh_token", refresh_token);
|
||||
let refresh_info = await (await fetch("https://discord.com/api/oauth2/token", {
|
||||
method: "POST",
|
||||
body: form_data
|
||||
})).json();
|
||||
|
||||
return refresh_info;
|
||||
}
|
||||
|
||||
return user_info;
|
||||
}
|
40
app/root.tsx
|
@ -1,40 +0,0 @@
|
|||
import {
|
||||
json,
|
||||
Links,
|
||||
LiveReload,
|
||||
Meta,
|
||||
Outlet,
|
||||
Scripts,
|
||||
ScrollRestoration,
|
||||
useLoaderData,
|
||||
} from "remix";
|
||||
import type { LinksFunction, MetaFunction, LoaderFunction } from "remix";
|
||||
|
||||
import tailwindStylesheetUrl from "./styles/tailwind.css";
|
||||
|
||||
export const links: LinksFunction = () => {
|
||||
return [{ rel: "stylesheet", href: tailwindStylesheetUrl }];
|
||||
};
|
||||
|
||||
export const meta: MetaFunction = () => ({
|
||||
charset: "utf-8",
|
||||
title: "Border Selector",
|
||||
viewport: "width=device-width,initial-scale=1",
|
||||
});
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
|
@ -1,23 +0,0 @@
|
|||
// 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 });
|
||||
}
|
||||
};
|
|
@ -1,23 +0,0 @@
|
|||
import { json, Link, LoaderFunction, useLoaderData } from "remix";
|
||||
import { getUser, getSession } from "~/session.server";
|
||||
import { useOptionalUser } from "~/utils";
|
||||
|
||||
export const loader: LoaderFunction = async ({ request }) => {
|
||||
const user_info = await getUser(request);
|
||||
return json(user_info);
|
||||
}
|
||||
|
||||
export default function Index() {
|
||||
const discordUser = useLoaderData();
|
||||
console.log("discordUser is", discordUser);
|
||||
return (
|
||||
<main className="relative min-h-screen bg-white sm:flex sm:items-center sm:justify-center">
|
||||
<h1>Do you love the color of the sky?</h1>
|
||||
<br />
|
||||
<Link
|
||||
to="/loginstart">
|
||||
Log in
|
||||
</Link>
|
||||
</main>
|
||||
);
|
||||
}
|
|
@ -1,39 +0,0 @@
|
|||
import * as React from "react";
|
||||
import type { ActionFunction, LoaderFunction, MetaFunction } from "remix";
|
||||
import {
|
||||
Form,
|
||||
json,
|
||||
Link,
|
||||
useActionData,
|
||||
redirect,
|
||||
useSearchParams,
|
||||
} from "remix";
|
||||
import { discordLogin } from "~/discord";
|
||||
|
||||
import { createUserSession, getUserId } from "~/session.server";
|
||||
|
||||
export const loader: LoaderFunction = async ({ request }) => {
|
||||
const userId = await getUserId(request);
|
||||
if (userId) return redirect("/");
|
||||
|
||||
const url = new URL(await request.url);
|
||||
const accessCode = url.searchParams.get("code") || "";
|
||||
|
||||
const response = await discordLogin(request, accessCode);
|
||||
console.log(response);
|
||||
return ""
|
||||
};
|
||||
|
||||
export const meta: MetaFunction = () => {
|
||||
return {
|
||||
title: "Login",
|
||||
};
|
||||
};
|
||||
|
||||
export default function LoginPage() {
|
||||
return (
|
||||
<div className="flex min-h-full flex-col justify-center">
|
||||
<p>Error logging in.</p>
|
||||
</div>
|
||||
)
|
||||
}
|
|
@ -1,25 +0,0 @@
|
|||
import type { LoaderFunction, MetaFunction } from "remix";
|
||||
import {
|
||||
json,
|
||||
redirect,
|
||||
} from "remix";
|
||||
import { getUserId } from "~/session.server";
|
||||
|
||||
export const loader: LoaderFunction = async ({ request }) => {
|
||||
const userId = await getUserId(request);
|
||||
if (userId) return redirect("/");
|
||||
const client_id = process.env.DISCORD_CLIENT_ID || "";
|
||||
const redirect_uri = process.env.DISCORD_REDIRECT_URI || "";
|
||||
return redirect(`https://discord.com/api/oauth2/authorize?client_id=${client_id}` +
|
||||
`&response_type=code&redirect_uri=${encodeURIComponent(redirect_uri)}&scope=identify`);
|
||||
};
|
||||
|
||||
export const meta: MetaFunction = () => {
|
||||
return {
|
||||
title: "Login",
|
||||
};
|
||||
};
|
||||
|
||||
export default function LoginPage() {
|
||||
return <div></div>
|
||||
}
|
|
@ -1,11 +0,0 @@
|
|||
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("/");
|
||||
};
|
|
@ -1,97 +0,0 @@
|
|||
import { createCookieSessionStorage, redirect } from "remix";
|
||||
import invariant from "tiny-invariant";
|
||||
|
||||
import { discordIdentify, User, SessionInformation } from "~/models/user.server";
|
||||
import { getUserByDiscordId } 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";
|
||||
const BEARER_TOKEN_KEY = "bearerToken";
|
||||
const REFRESH_TOKEN_KEY = "refreshToken";
|
||||
|
||||
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 getUserByDiscordId(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(`/loginstart?${searchParams}`);
|
||||
}
|
||||
return userId;
|
||||
}
|
||||
|
||||
export async function requireUser(request: Request) {
|
||||
const session = await getSession(request);
|
||||
const user_id = session.get(USER_SESSION_KEY);
|
||||
const client_id = process.env.DISCORD_CLIENT_ID || "";
|
||||
const redirect_uri = process.env.DISCORD_REDIRECT_URI || "";
|
||||
if (!user_id) {
|
||||
return redirect(`https://discord.com/api/oauth2/authorize?client_id=${client_id}` +
|
||||
`&response_type=code&redirect_uri=${encodeURIComponent(redirect_uri)}&scope=identify`);
|
||||
}
|
||||
}
|
||||
|
||||
export async function createUserSession({
|
||||
request,
|
||||
discord_id,
|
||||
redirectTo,
|
||||
}: {
|
||||
request: Request;
|
||||
discord_id: string;
|
||||
redirectTo: string;
|
||||
}) {
|
||||
const session = await getSession(request);
|
||||
session.set(USER_SESSION_KEY, discord_id);
|
||||
console.log(discord_id);
|
||||
return redirect(redirectTo, {
|
||||
headers: {
|
||||
"Set-Cookie": await sessionStorage.commitSession(session, {
|
||||
maxAge: 60 * 60 * 24 * 7 // 7 days
|
||||
}),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function logout(request: Request) {
|
||||
const session = await getSession(request);
|
||||
return redirect("/", {
|
||||
headers: {
|
||||
"Set-Cookie": await sessionStorage.destroySession(session),
|
||||
},
|
||||
});
|
||||
}
|
44
app/utils.ts
|
@ -1,44 +0,0 @@
|
|||
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.discord_id === "string";
|
||||
}
|
||||
|
||||
export function useOptionalUser(): User | undefined {
|
||||
const data = useMatchesData("root");
|
||||
console.log(data)
|
||||
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;
|
||||
}
|
|
@ -1 +0,0 @@
|
|||
{}
|
|
@ -1,6 +0,0 @@
|
|||
module.exports = {
|
||||
parserOptions: {
|
||||
tsconfigRootDir: __dirname,
|
||||
project: "./tsconfig.json",
|
||||
},
|
||||
};
|
|
@ -1,48 +0,0 @@
|
|||
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");
|
||||
});
|
||||
});
|
|
@ -1,5 +0,0 @@
|
|||
{
|
||||
"name": "Using fixtures to represent data",
|
||||
"email": "hello@cypress.io",
|
||||
"body": "Fixtures are a great way to mock data for responses to routes"
|
||||
}
|
|
@ -1,25 +0,0 @@
|
|||
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;
|
||||
};
|
|
@ -1,77 +0,0 @@
|
|||
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",
|
||||
*/
|
|
@ -1,47 +0,0 @@
|
|||
// 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]);
|
|
@ -1,22 +0,0 @@
|
|||
// 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]);
|
|
@ -1,2 +0,0 @@
|
|||
import "@testing-library/cypress/add-commands";
|
||||
import "./commands";
|
|
@ -1,31 +0,0 @@
|
|||
{
|
||||
"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/*"]
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,13 +0,0 @@
|
|||
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
|
@ -1,50 +0,0 @@
|
|||
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 = { }
|
|
@ -1,7 +0,0 @@
|
|||
# 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)
|
|
@ -1,2 +0,0 @@
|
|||
require("esbuild-register/dist/node").register();
|
||||
require("./start");
|
|
@ -1,9 +0,0 @@
|
|||
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());
|
11
next.config.js
Normal file
|
@ -0,0 +1,11 @@
|
|||
/** @type {import('next').NextConfig} */
|
||||
|
||||
const webpack = require("webpack");
|
||||
const { parsed: environment } = require("dotenv").config();
|
||||
|
||||
module.exports = {
|
||||
webpack(config) {
|
||||
config.plugins.push(new webpack.EnvironmentPlugin(environment));
|
||||
return config;
|
||||
},
|
||||
};
|
|
@ -1,41 +0,0 @@
|
|||
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
97
package.json
|
@ -1,92 +1,23 @@
|
|||
{
|
||||
"name": "border-server-a1df",
|
||||
"name": "borders",
|
||||
"version": "0.1.0",
|
||||
"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 -i ./styles/tailwind.css -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",
|
||||
"db:generate": "prisma generate",
|
||||
"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"
|
||||
"dev": "next dev",
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"lint": "next lint"
|
||||
},
|
||||
"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",
|
||||
"axios": "^0.26.1",
|
||||
"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"
|
||||
"dotenv": "^16.0.0",
|
||||
"next": "12.1.4",
|
||||
"next-auth": "^4.3.1",
|
||||
"prisma": "^3.12.0",
|
||||
"react": "18.0.0",
|
||||
"react-dom": "18.0.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"
|
||||
"eslint": "8.13.0",
|
||||
"eslint-config-next": "12.1.4"
|
||||
}
|
||||
}
|
||||
|
|
12
pages/_app.js
Normal file
|
@ -0,0 +1,12 @@
|
|||
import "../styles/globals.css";
|
||||
import { SessionProvider } from "next-auth/react";
|
||||
|
||||
function MyApp({ Component, pageProps: { session, ...pageProps } }) {
|
||||
return (
|
||||
<SessionProvider session={session}>
|
||||
<Component {...pageProps} />
|
||||
</SessionProvider>
|
||||
);
|
||||
}
|
||||
|
||||
export default MyApp;
|
11
pages/api/auth/[...nextauth].js
Normal file
|
@ -0,0 +1,11 @@
|
|||
import NextAuth from "next-auth";
|
||||
import DiscordProvider from "next-auth/providers/discord";
|
||||
|
||||
export default NextAuth({
|
||||
providers: [
|
||||
DiscordProvider({
|
||||
clientId: process.env.DISCORD_CLIENT_ID,
|
||||
clientSecret: process.env.DISCORD_CLIENT_SECRET,
|
||||
}),
|
||||
],
|
||||
});
|
5
pages/api/hello.js
Normal file
|
@ -0,0 +1,5 @@
|
|||
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
|
||||
|
||||
export default function handler(req, res) {
|
||||
res.status(200).json({ name: 'John Doe' })
|
||||
}
|
31
pages/index.js
Normal file
|
@ -0,0 +1,31 @@
|
|||
import { useSession, signIn, signOut } from "next-auth/react";
|
||||
import Head from "next/head";
|
||||
import Image from "next/image";
|
||||
import styles from "../styles/Home.module.css";
|
||||
|
||||
export default function Home() {
|
||||
const { data: session } = useSession();
|
||||
return (
|
||||
<div className={styles.container}>
|
||||
<Head>
|
||||
<title>Create Next App</title>
|
||||
<meta name="description" content="Generated by create next app" />
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
</Head>
|
||||
|
||||
<main className={styles.main}>
|
||||
<h1 className={styles.title}>Steam Borders</h1>
|
||||
|
||||
<p className={styles.description}>
|
||||
{session ? `Signed in as ${session.user.name}` : "Not signed in"}
|
||||
<br />
|
||||
{session ? (
|
||||
<button onClick={() => signOut()}>Sign Out</button>
|
||||
) : (
|
||||
<button onClick={() => signIn()}>Sign In</button>
|
||||
)}
|
||||
</p>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
7531
pnpm-lock.yaml
|
@ -1,39 +0,0 @@
|
|||
-- 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;
|
|
@ -1,42 +0,0 @@
|
|||
/*
|
||||
Warnings:
|
||||
|
||||
- You are about to drop the column `email` on the `User` table. All the data in the column will be lost.
|
||||
- You are about to drop the `Note` table. If the table is not empty, all the data it contains will be lost.
|
||||
- You are about to drop the `Password` table. If the table is not empty, all the data it contains will be lost.
|
||||
- A unique constraint covering the columns `[discord_id]` on the table `User` will be added. If there are existing duplicate values, this will fail.
|
||||
|
||||
*/
|
||||
-- DropForeignKey
|
||||
ALTER TABLE "Note" DROP CONSTRAINT "Note_userId_fkey";
|
||||
|
||||
-- DropForeignKey
|
||||
ALTER TABLE "Password" DROP CONSTRAINT "Password_userId_fkey";
|
||||
|
||||
-- DropIndex
|
||||
DROP INDEX "User_email_key";
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "User" DROP COLUMN "email",
|
||||
ADD COLUMN "border_id" TEXT,
|
||||
ADD COLUMN "discord_id" TEXT;
|
||||
|
||||
-- DropTable
|
||||
DROP TABLE "Note";
|
||||
|
||||
-- DropTable
|
||||
DROP TABLE "Password";
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Border" (
|
||||
"id" TEXT NOT NULL,
|
||||
"filename" TEXT NOT NULL,
|
||||
|
||||
CONSTRAINT "Border_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Border_filename_key" ON "Border"("filename");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "User_discord_id_key" ON "User"("discord_id");
|
|
@ -1,3 +0,0 @@
|
|||
# Please do not edit this file manually
|
||||
# It should be added in your version-control system (i.e. Git)
|
||||
provider = "postgresql"
|
|
@ -1,33 +1,22 @@
|
|||
datasource db {
|
||||
provider = "postgresql"
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
// This is your Prisma schema file,
|
||||
// learn more about it in the docs: https://pris.ly/d/prisma-schema
|
||||
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
}
|
||||
|
||||
datasource db {
|
||||
provider = "sqlite"
|
||||
url = "file:./borders.db"
|
||||
}
|
||||
|
||||
model User {
|
||||
id String @id @default(cuid())
|
||||
discord_id String? @unique
|
||||
border_id String?
|
||||
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
id Int @id @default(autoincrement())
|
||||
discordId String @unique
|
||||
username String
|
||||
discriminator String
|
||||
avatar String?
|
||||
borderUrl String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
}
|
||||
|
||||
model DiscordUser {
|
||||
id String @id @default(cuid())
|
||||
discord_id String @unique
|
||||
access_token String?
|
||||
refresh_token String?
|
||||
expires DateTime?
|
||||
|
||||
username String?
|
||||
discriminator String?
|
||||
}
|
||||
|
||||
model Border {
|
||||
id String @id @default(cuid())
|
||||
filename String @unique
|
||||
}
|
|
@ -1,31 +0,0 @@
|
|||
import { PrismaClient } from "@prisma/client";
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
async function seed() {
|
||||
const discord_id = "123601647258697730";
|
||||
const border_id = 'test';
|
||||
|
||||
// cleanup the existing database
|
||||
await prisma.user.delete({ where: { discord_id } }).catch(() => {
|
||||
// no worries if it doesn't exist yet
|
||||
});
|
||||
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
discord_id,
|
||||
border_id
|
||||
},
|
||||
});
|
||||
|
||||
console.log(`Database has been seeded. 🌱`);
|
||||
}
|
||||
|
||||
seed()
|
||||
.catch((e) => {
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
})
|
||||
.finally(async () => {
|
||||
await prisma.$disconnect();
|
||||
});
|
Before Width: | Height: | Size: 17 KiB After Width: | Height: | Size: 25 KiB |
Before Width: | Height: | Size: 526 KiB |
Before Width: | Height: | Size: 897 KiB |
Before Width: | Height: | Size: 573 KiB |
Before Width: | Height: | Size: 236 KiB |
Before Width: | Height: | Size: 622 KiB |
Before Width: | Height: | Size: 588 KiB |
Before Width: | Height: | Size: 1.9 MiB |
Before Width: | Height: | Size: 1.7 KiB |
Before Width: | Height: | Size: 653 KiB |
Before Width: | Height: | Size: 569 KiB |
Before Width: | Height: | Size: 346 KiB |
Before Width: | Height: | Size: 1.9 MiB |
Before Width: | Height: | Size: 686 KiB |
Before Width: | Height: | Size: 140 KiB |
Before Width: | Height: | Size: 11 KiB |
Before Width: | Height: | Size: 1 MiB |
Before Width: | Height: | Size: 938 KiB |
Before Width: | Height: | Size: 470 KiB |
Before Width: | Height: | Size: 92 KiB |
Before Width: | Height: | Size: 7.4 KiB |
Before Width: | Height: | Size: 36 KiB |
BIN
public/sky.png
Before Width: | Height: | Size: 118 KiB |
4
public/vercel.svg
Normal file
|
@ -0,0 +1,4 @@
|
|||
<svg width="283" height="64" viewBox="0 0 283 64" fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M141.04 16c-11.04 0-19 7.2-19 18s8.96 18 20 18c6.67 0 12.55-2.64 16.19-7.09l-7.65-4.42c-2.02 2.21-5.09 3.5-8.54 3.5-4.79 0-8.86-2.5-10.37-6.5h28.02c.22-1.12.35-2.28.35-3.5 0-10.79-7.96-17.99-19-17.99zm-9.46 14.5c1.25-3.99 4.67-6.5 9.45-6.5 4.79 0 8.21 2.51 9.45 6.5h-18.9zM248.72 16c-11.04 0-19 7.2-19 18s8.96 18 20 18c6.67 0 12.55-2.64 16.19-7.09l-7.65-4.42c-2.02 2.21-5.09 3.5-8.54 3.5-4.79 0-8.86-2.5-10.37-6.5h28.02c.22-1.12.35-2.28.35-3.5 0-10.79-7.96-17.99-19-17.99zm-9.45 14.5c1.25-3.99 4.67-6.5 9.45-6.5 4.79 0 8.21 2.51 9.45 6.5h-18.9zM200.24 34c0 6 3.92 10 10 10 4.12 0 7.21-1.87 8.8-4.92l7.68 4.43c-3.18 5.3-9.14 8.49-16.48 8.49-11.05 0-19-7.2-19-18s7.96-18 19-18c7.34 0 13.29 3.19 16.48 8.49l-7.68 4.43c-1.59-3.05-4.68-4.92-8.8-4.92-6.07 0-10 4-10 10zm82.48-29v46h-9V5h9zM36.95 0L73.9 64H0L36.95 0zm92.38 5l-27.71 48L73.91 5H84.3l17.32 30 17.32-30h10.39zm58.91 12v9.69c-1-.29-2.06-.49-3.2-.49-5.81 0-10 4-10 10V51h-9V17h9v9.2c0-5.08 5.91-9.2 13.2-9.2z" fill="#000"/>
|
||||
</svg>
|
After Width: | Height: | Size: 1.1 KiB |
|
@ -1,7 +0,0 @@
|
|||
/**
|
||||
* @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
|
@ -1,2 +0,0 @@
|
|||
/// <reference types="@remix-run/dev" />
|
||||
/// <reference types="@remix-run/node/globals" />
|
105
server.ts
|
@ -1,105 +0,0 @@
|
|||
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];
|
||||
}
|
||||
}
|
||||
}
|
116
styles/Home.module.css
Normal file
|
@ -0,0 +1,116 @@
|
|||
.container {
|
||||
padding: 0 2rem;
|
||||
}
|
||||
|
||||
.main {
|
||||
min-height: 100vh;
|
||||
padding: 4rem 0;
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.footer {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
padding: 2rem 0;
|
||||
border-top: 1px solid #eaeaea;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.footer a {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
flex-grow: 1;
|
||||
}
|
||||
|
||||
.title a {
|
||||
color: #0070f3;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.title a:hover,
|
||||
.title a:focus,
|
||||
.title a:active {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.title {
|
||||
margin: 0;
|
||||
line-height: 1.15;
|
||||
font-size: 4rem;
|
||||
}
|
||||
|
||||
.title,
|
||||
.description {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.description {
|
||||
margin: 4rem 0;
|
||||
line-height: 1.5;
|
||||
font-size: 1.5rem;
|
||||
}
|
||||
|
||||
.code {
|
||||
background: #fafafa;
|
||||
border-radius: 5px;
|
||||
padding: 0.75rem;
|
||||
font-size: 1.1rem;
|
||||
font-family: Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono,
|
||||
Bitstream Vera Sans Mono, Courier New, monospace;
|
||||
}
|
||||
|
||||
.grid {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-wrap: wrap;
|
||||
max-width: 800px;
|
||||
}
|
||||
|
||||
.card {
|
||||
margin: 1rem;
|
||||
padding: 1.5rem;
|
||||
text-align: left;
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
border: 1px solid #eaeaea;
|
||||
border-radius: 10px;
|
||||
transition: color 0.15s ease, border-color 0.15s ease;
|
||||
max-width: 300px;
|
||||
}
|
||||
|
||||
.card:hover,
|
||||
.card:focus,
|
||||
.card:active {
|
||||
color: #0070f3;
|
||||
border-color: #0070f3;
|
||||
}
|
||||
|
||||
.card h2 {
|
||||
margin: 0 0 1rem 0;
|
||||
font-size: 1.5rem;
|
||||
}
|
||||
|
||||
.card p {
|
||||
margin: 0;
|
||||
font-size: 1.25rem;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.logo {
|
||||
height: 1em;
|
||||
margin-left: 0.5rem;
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.grid {
|
||||
width: 100%;
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
16
styles/globals.css
Normal file
|
@ -0,0 +1,16 @@
|
|||
html,
|
||||
body {
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen,
|
||||
Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
|
||||
}
|
||||
|
||||
a {
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
|
@ -1,9 +0,0 @@
|
|||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
html {
|
||||
background-image: url("/sky.png");
|
||||
background-repeat: no-repeat;
|
||||
background-size: cover;
|
||||
}
|
|
@ -1,7 +0,0 @@
|
|||
module.exports = {
|
||||
content: ["./app/**/*.{ts,tsx,jsx,js}"],
|
||||
theme: {
|
||||
extend: {},
|
||||
},
|
||||
plugins: [],
|
||||
};
|
|
@ -1,4 +0,0 @@
|
|||
import { installGlobals } from "@remix-run/node/globals";
|
||||
import "@testing-library/jest-dom/extend-expect";
|
||||
|
||||
installGlobals();
|
|
@ -1,24 +0,0 @@
|
|||
{
|
||||
"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
|
||||
}
|
||||
}
|
|
@ -1,15 +0,0 @@
|
|||
/// <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"],
|
||||
},
|
||||
});
|