From 4e0dc08e290997ff180da2c1c5fb45145eb12a9f Mon Sep 17 00:00:00 2001 From: Luke Bunselmeyer Date: Sun, 7 May 2023 11:03:30 -0400 Subject: [PATCH] - Clean up - Removed notes - Updated readme - DB - Updated initial db schema - Updated db seed - Created source, station, and tag models - Libs - Create content source importer - UI - Added content source UI & routes - Updated page layout - Created component --- README.md | 179 +----------------- app/components/breadcrumbs.tsx | 18 ++ app/components/page-layout.tsx | 29 ++- app/db.server.ts | 37 +++- app/lib/importer.server.ts | 24 +++ app/models/note.server.ts | 52 ----- app/models/source.server.ts | 34 ++++ app/models/station.server.ts | 71 +++++++ app/models/tag.server.ts | 12 ++ app/root.tsx | 52 ++++- app/routes/_index.tsx | 2 +- app/routes/login.tsx | 4 +- app/routes/notes.$noteId.tsx | 70 ------- app/routes/notes._index.tsx | 12 -- app/routes/notes.new.tsx | 109 ----------- app/routes/notes.tsx | 70 ------- app/routes/sources.$id.tsx | 87 +++++++++ app/routes/sources._index.tsx | 34 ++++ app/routes/sources.tsx | 7 + app/utils.ts | 89 ++++++--- cypress/e2e/smoke.cy.ts | 55 ++---- package-lock.json | 92 ++++++++- package.json | 2 + .../20220713162558_init/migration.sql | 31 --- .../migration.sql | 96 ++++++++++ prisma/schema.prisma | 90 +++++++-- prisma/seed.ts | 81 ++++---- remix.config.js | 25 +-- tailwind.config.ts | 10 +- 29 files changed, 792 insertions(+), 682 deletions(-) create mode 100644 app/components/breadcrumbs.tsx create mode 100644 app/lib/importer.server.ts delete mode 100644 app/models/note.server.ts create mode 100644 app/models/source.server.ts create mode 100644 app/models/station.server.ts create mode 100644 app/models/tag.server.ts delete mode 100644 app/routes/notes.$noteId.tsx delete mode 100644 app/routes/notes._index.tsx delete mode 100644 app/routes/notes.new.tsx delete mode 100644 app/routes/notes.tsx create mode 100644 app/routes/sources.$id.tsx create mode 100644 app/routes/sources._index.tsx create mode 100644 app/routes/sources.tsx delete mode 100644 prisma/migrations/20220713162558_init/migration.sql create mode 100644 prisma/migrations/20230507113043_initial_migration/migration.sql diff --git a/README.md b/README.md index 7394b8a..31c71df 100644 --- a/README.md +++ b/README.md @@ -1,180 +1,15 @@ -# Remix Indie Stack - -![The Remix Indie Stack](https://repository-images.githubusercontent.com/465928257/a241fa49-bd4d-485a-a2a5-5cb8e4ee0abf) - -Learn more about [Remix Stacks](https://remix.run/stacks). - -```sh -npx create-remix@latest --template remix-run/indie-stack -``` - -## What's in the stack - -- [Fly app deployment](https://fly.io) with [Docker](https://www.docker.com/) -- Production-ready [SQLite Database](https://sqlite.org) -- Healthcheck endpoint for [Fly backups region fallbacks](https://fly.io/docs/reference/configuration/#services-http_checks) -- [GitHub Actions](https://github.com/features/actions) for deploy on merge to production and staging environments -- Email/Password Authentication with [cookie-based sessions](https://remix.run/utils/sessions#md-createcookiesessionstorage) -- Database ORM with [Prisma](https://prisma.io) -- Styling with [Tailwind](https://tailwindcss.com/) -- End-to-end testing with [Cypress](https://cypress.io) -- Local third party request mocking with [MSW](https://mswjs.io) -- Unit testing with [Vitest](https://vitest.dev) and [Testing Library](https://testing-library.com) -- Code formatting with [Prettier](https://prettier.io) -- Linting with [ESLint](https://eslint.org) -- Static Types with [TypeScript](https://typescriptlang.org) - -Not a fan of bits of the stack? Fork it, change it, and use `npx create-remix --template your/repo`! Make it your own. - -## Quickstart - -Click this button to create a [Gitpod](https://gitpod.io) workspace with the project set up and Fly pre-installed - -[![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/remix-run/indie-stack/tree/main) +# Awesome Radio ## Development -- This step only applies if you've opted out of having the CLI install dependencies for you: +### Running - ```sh - npx remix init - ``` - -- Initial setup: _If you just generated this project, this step has been done for you._ - - ```sh - npm run setup - ``` - -- Start dev server: - - ```sh - npm run dev - ``` - -This starts your app in development mode, rebuilding assets on file changes. - -The database seed script creates a new user with some data you can use to get started: - -- Email: `rachel@remix.run` -- Password: `racheliscool` - -### Relevant code: - -This is a pretty simple note-taking app, but it's a good example of how you can build a full stack app with Prisma and Remix. The main functionality is creating users, logging in and out, and creating and deleting notes. - -- creating users, and logging in and out [./app/models/user.server.ts](./app/models/user.server.ts) -- user sessions, and verifying them [./app/session.server.ts](./app/session.server.ts) -- creating, and deleting notes [./app/models/note.server.ts](./app/models/note.server.ts) - -## Deployment - -This Remix Stack comes with two GitHub Actions that handle automatically deploying your app to production and staging environments. - -Prior to your first deployment, you'll need to do a few things: - -- [Install Fly](https://fly.io/docs/getting-started/installing-flyctl/) - -- Sign up and log in to Fly - - ```sh - fly auth signup - ``` - - > **Note:** If you have more than one Fly account, ensure that you are signed into the same account in the Fly CLI as you are in the browser. In your terminal, run `fly auth whoami` and ensure the email matches the Fly account signed into the browser. - -- Create two apps on Fly, one for staging and one for production: - - ```sh - fly apps create tunein-radio-stations-1ae3 - fly apps create tunein-radio-stations-1ae3-staging - ``` - - > **Note:** Make sure this name matches the `app` set in your `fly.toml` file. Otherwise, you will not be able to deploy. - - - Initialize Git. - - ```sh - git init - ``` - -- Create a new [GitHub Repository](https://repo.new), and then add it as the remote for your project. **Do not push your app yet!** - - ```sh - git remote add origin - ``` - -- Add a `FLY_API_TOKEN` to your GitHub repo. To do this, go to your user settings on Fly and create a new [token](https://web.fly.io/user/personal_access_tokens/new), then add it to [your repo secrets](https://docs.github.com/en/actions/security-guides/encrypted-secrets) with the name `FLY_API_TOKEN`. - -- Add a `SESSION_SECRET` to your fly app secrets, to do this you can run the following commands: - - ```sh - fly secrets set SESSION_SECRET=$(openssl rand -hex 32) --app tunein-radio-stations-1ae3 - fly secrets set SESSION_SECRET=$(openssl rand -hex 32) --app tunein-radio-stations-1ae3-staging - ``` - - If you don't have openssl installed, you can also use [1Password](https://1password.com/password-generator) to generate a random secret, just replace `$(openssl rand -hex 32)` with the generated secret. - -- Create a persistent volume for the sqlite database for both your staging and production environments. Run the following: - - ```sh - fly volumes create data --size 1 --app tunein-radio-stations-1ae3 - fly volumes create data --size 1 --app tunein-radio-stations-1ae3-staging - ``` - -Now that everything is set up you can commit and push your changes to your repo. Every commit to your `main` branch will trigger a deployment to your production environment, and every commit to your `dev` branch will trigger a deployment to your staging environment. - -### Connecting to your database - -The sqlite database lives at `/data/sqlite.db` in your deployed application. You can connect to the live database by running `fly ssh console -C database-cli`. - -### Getting Help with Deployment - -If you run into any issues deploying to Fly, make sure you've followed all of the steps above and if you have, then post as many details about your deployment (including your app name) to [the Fly support community](https://community.fly.io). They're normally pretty responsive over there and hopefully can help resolve any of your deployment issues and questions. - -## GitHub Actions - -We use GitHub Actions for continuous integration and deployment. Anything that gets into the `main` branch will be deployed to production after running tests/build/etc. Anything in the `dev` branch will be deployed to staging. - -## Testing - -### Cypress - -We use Cypress for our End-to-End tests in this project. You'll find those in the `cypress` directory. As you make changes, add to an existing file or create a new file in the `cypress/e2e` directory to test your changes. - -We use [`@testing-library/cypress`](https://testing-library.com/cypress) for selecting elements on the page semantically. - -To run these tests in development, run `npm run test:e2e:dev` which will start the dev server for the app as well as the Cypress client. Make sure the database is running in docker as described above. - -We have a utility for testing authenticated features without having to go through the login flow: - -```ts -cy.login(); -// you are now logged in as a new user +```shell +npm run dev ``` -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: +### Testing -```ts -afterEach(() => { - cy.cleanupUser(); -}); +```shell +npm run test ``` - -That way, we can keep your local db clean and keep your tests isolated from one another. - -### Vitest - -For lower level tests of utilities and individual components, we use `vitest`. We have DOM-specific assertion helpers via [`@testing-library/jest-dom`](https://testing-library.com/jest-dom). - -### Type Checking - -This project uses TypeScript. It's recommended to get TypeScript set up for your editor to get a really great in-editor experience with type checking and auto-complete. To run type checking across the whole project, run `npm run typecheck`. - -### Linting - -This project uses ESLint for linting. That is configured in `.eslintrc.js`. - -### Formatting - -We use [Prettier](https://prettier.io/) for auto-formatting in this project. It's recommended to install an editor plugin (like the [VSCode Prettier plugin](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode)) to get auto-formatting on save. There's also a `npm run format` script you can run to format all files in the project. diff --git a/app/components/breadcrumbs.tsx b/app/components/breadcrumbs.tsx new file mode 100644 index 0000000..5537f21 --- /dev/null +++ b/app/components/breadcrumbs.tsx @@ -0,0 +1,18 @@ +import type { ReactNode } from "react"; + +export type BreadcrumbsProps = { + children: ReactNode | ReactNode[]; +} + +export function Breadcrumbs({ children }: BreadcrumbsProps) { + const links = Array.isArray(children) ? children : [children]; + return ( +
+
    + {links.map((c, i) => { + return
  • {c}
  • ; + })} +
+
+ ); +} diff --git a/app/components/page-layout.tsx b/app/components/page-layout.tsx index 9749ae8..50d3048 100644 --- a/app/components/page-layout.tsx +++ b/app/components/page-layout.tsx @@ -1,4 +1,5 @@ import { RadioIcon } from "@heroicons/react/24/solid"; +import { NavLink } from "@remix-run/react"; import type { ReactNode } from "react"; export type PageLayoutProps = { @@ -31,19 +32,35 @@ export function PageLayout({ children }: PageLayoutProps) { - - - {children} +
+ {children} +
    -
  • +
  • Awesome Radio

  • -
  • Sidebar Item 1
  • -
  • Sidebar Item 2
  • +
  • + Listen +
  • +
  • + Music +
  • +
  • + Sports +
  • +
  • + News & Talk +
  • +
  • + Manage Content +
  • +
  • + Sources +
diff --git a/app/db.server.ts b/app/db.server.ts index 643c762..6ae7623 100644 --- a/app/db.server.ts +++ b/app/db.server.ts @@ -1,9 +1,32 @@ import { PrismaClient } from "@prisma/client"; +function createPrismaClient() { + return new PrismaClient({ + // log: [ + // { + // emit: "stdout", + // level: "query" + // }, + // { + // emit: "stdout", + // level: "error" + // }, + // { + // emit: "stdout", + // level: "info" + // }, + // { + // emit: "stdout", + // level: "warn" + // } + // ] + }); +} + let prisma: PrismaClient; declare global { - var __db__: PrismaClient | undefined; + var __db__: PrismaClient | undefined; } // This is needed because in development we don't want to restart @@ -11,13 +34,13 @@ declare global { // create a new connection to the DB with every change either. // In production, we'll have a single connection to the DB. if (process.env.NODE_ENV === "production") { - prisma = new PrismaClient(); + prisma = createPrismaClient(); } else { - if (!global.__db__) { - global.__db__ = new PrismaClient(); - } - prisma = global.__db__; - prisma.$connect(); + if (!global.__db__) { + global.__db__ = createPrismaClient(); + } + prisma = global.__db__; + prisma.$connect(); } export { prisma }; diff --git a/app/lib/importer.server.ts b/app/lib/importer.server.ts new file mode 100644 index 0000000..4ec423d --- /dev/null +++ b/app/lib/importer.server.ts @@ -0,0 +1,24 @@ +import type { ContentSource } from "@prisma/client"; +import { fetch } from "@remix-run/node"; +import { importStations } from "~/models/station.server"; + + +export async function importSource(source: ContentSource) { + switch (source.type) { + case "json": + return importRemoteJson(source); + default: + throw new Error("Unsupported source"); + + } +} + +export async function importRemoteJson(source: ContentSource) { + const response = await fetch(source.connectionUrl); + if (!response.ok) { + throw new Error("Failed to fetch source"); + } + const { data } = await response.json(); + return importStations(data); + +} diff --git a/app/models/note.server.ts b/app/models/note.server.ts deleted file mode 100644 index f385491..0000000 --- a/app/models/note.server.ts +++ /dev/null @@ -1,52 +0,0 @@ -import type { User, Note } from "@prisma/client"; - -import { prisma } from "~/db.server"; - -export function getNote({ - id, - userId, -}: Pick & { - userId: User["id"]; -}) { - return prisma.note.findFirst({ - select: { id: true, body: true, title: true }, - where: { id, userId }, - }); -} - -export function getNoteListItems({ userId }: { userId: User["id"] }) { - return prisma.note.findMany({ - where: { userId }, - select: { id: true, title: true }, - orderBy: { updatedAt: "desc" }, - }); -} - -export function createNote({ - body, - title, - userId, -}: Pick & { - userId: User["id"]; -}) { - return prisma.note.create({ - data: { - title, - body, - user: { - connect: { - id: userId, - }, - }, - }, - }); -} - -export function deleteNote({ - id, - userId, -}: Pick & { userId: User["id"] }) { - return prisma.note.deleteMany({ - where: { id, userId }, - }); -} diff --git a/app/models/source.server.ts b/app/models/source.server.ts new file mode 100644 index 0000000..ccac163 --- /dev/null +++ b/app/models/source.server.ts @@ -0,0 +1,34 @@ +import { prisma } from "~/db.server"; + +export type SourceInput = { + id?: string; + name: string; + description?: string; + connectionUrl: string; + type: string; + +}; + +export function saveSource({ id, name, description, connectionUrl, type }: SourceInput) { + const data = { name, description, connectionUrl, type }; + if (id) { + return prisma.contentSource.update({ + where: { id }, + data + }); + } + return prisma.contentSource.create({ + data + }); +} + + +export function getSources() { + return prisma.contentSource.findMany({ + orderBy: [{ name: "asc" }] + }); +} + +export function getSource(id: string) { + return prisma.contentSource.findUnique({ where: { id } }); +} diff --git a/app/models/station.server.ts b/app/models/station.server.ts new file mode 100644 index 0000000..a699950 --- /dev/null +++ b/app/models/station.server.ts @@ -0,0 +1,71 @@ +import type { PrismaClient, Station, Tag } from "@prisma/client"; +import { prisma } from "~/db.server"; +import { upsertTagOnName } from "~/models/tag.server"; +import { slugify } from "~/utils"; + +export type StationInput = { + id?: string + name: string; + description: string; + streamUrl: string; + imgUrl: string; + reliability: number; + popularity: number; + tags: string[] +}; + +export type PrismaTxClient = Omit; + +export function upsertStationOnStreamUrl(input: StationInput, p: PrismaTxClient = prisma) { + return p.station.upsert({ + where: { streamUrl: input.streamUrl }, + create: { + name: input.name, + slug: slugify(input.name), + description: input.description, + imgUrl: input.imgUrl, + streamUrl: input.streamUrl, + reliability: input.reliability, + popularity: input.popularity + }, + update: { + name: input.name, + slug: slugify(input.name), + description: input.description, + imgUrl: input.imgUrl, + reliability: input.reliability, + popularity: input.popularity + } + }); +} + +export function deleteStationTags(station: Station, p: PrismaTxClient = prisma) { + return p.stationTag.deleteMany({ where: { stationId: station.id } }); +} + +export function createStationTag(station: Station, tag: Tag, p: PrismaTxClient = prisma) { + return p.stationTag.create({ + data: { + tagId: tag.id, + stationId: station.id + } + }); +} + +export async function importStations(stationsInput: StationInput[]) { + return prisma.$transaction(async (tx) => { + const stations: Station[] = []; + for (const stationInput of stationsInput) { + const station = await upsertStationOnStreamUrl(stationInput, tx); + await deleteStationTags(station, tx); + for (const tagName of stationInput.tags) { + const tag = await upsertTagOnName(tagName, tx); + await createStationTag(station, tag, tx); + } + stations.push(station); + } + return stations; + }); + + +} diff --git a/app/models/tag.server.ts b/app/models/tag.server.ts new file mode 100644 index 0000000..b95142a --- /dev/null +++ b/app/models/tag.server.ts @@ -0,0 +1,12 @@ +import { prisma } from "~/db.server"; +import type { PrismaTxClient } from "~/models/station.server"; +import { slugify } from "~/utils"; + +export function upsertTagOnName(tag: string, p: PrismaTxClient = prisma) { + const slug = slugify(tag); + return p.tag.upsert({ + where: { name: tag }, + create: { name: tag, slug }, + update: { slug } + }); +} diff --git a/app/root.tsx b/app/root.tsx index 160fa22..5a5bba8 100644 --- a/app/root.tsx +++ b/app/root.tsx @@ -1,7 +1,16 @@ import { cssBundleHref } from "@remix-run/css-bundle"; import type { LinksFunction, LoaderArgs } from "@remix-run/node"; import { json } from "@remix-run/node"; -import { Links, LiveReload, Meta, Outlet, Scripts, ScrollRestoration } from "@remix-run/react"; +import { + isRouteErrorResponse, + Links, + LiveReload, + Meta, + Outlet, + Scripts, + ScrollRestoration, + useRouteError +} from "@remix-run/react"; import type { ReactNode } from "react"; import { PageLayout } from "~/components/page-layout"; @@ -53,12 +62,49 @@ export default function App() { ); } -export function ErrorBoundary({ error }: { error: Error }) { +export function ErrorBoundary() { + const error = useRouteError(); + console.error(error); + if (isRouteErrorResponse(error)) { + const title = `${error.status} - ${error.statusText}`; + return ( + +
+

{title}

+
+
+ ); + } + + if (error instanceof Error) { + return ( + +
+

Yikes!

+
+
+ + + + {error.message} +
+
+

Stack Trace

+
+
{error.stack}
+
+
+
+ ); + } + return ( -
+

Sorry, something went wrong...

diff --git a/app/routes/_index.tsx b/app/routes/_index.tsx index fc3fba1..edfebff 100644 --- a/app/routes/_index.tsx +++ b/app/routes/_index.tsx @@ -2,7 +2,7 @@ import type { V2_MetaFunction } from "@remix-run/node"; import { useOptionalUser } from "~/utils"; -export const meta: V2_MetaFunction = () => [{ title: "Remix Notes" }]; +export const meta: V2_MetaFunction = () => [{ title: "Awesome Radio" }]; export default function Index() { const user = useOptionalUser(); diff --git a/app/routes/login.tsx b/app/routes/login.tsx index 25a8f92..59fa21d 100644 --- a/app/routes/login.tsx +++ b/app/routes/login.tsx @@ -62,8 +62,8 @@ export const meta: V2_MetaFunction = () => [{ title: "Login" }]; export default function LoginPage() { const [searchParams] = useSearchParams(); - const redirectTo = searchParams.get("redirectTo") || "/notes"; - const actionData = useActionData(); + const redirectTo = searchParams.get("redirectTo") || "/"; + const actionData = useActionData(); const emailRef = useRef(null); const passwordRef = useRef(null); diff --git a/app/routes/notes.$noteId.tsx b/app/routes/notes.$noteId.tsx deleted file mode 100644 index 0f83fd8..0000000 --- a/app/routes/notes.$noteId.tsx +++ /dev/null @@ -1,70 +0,0 @@ -import type { ActionArgs, LoaderArgs } from "@remix-run/node"; -import { json, redirect } from "@remix-run/node"; -import { - Form, - isRouteErrorResponse, - useLoaderData, - useRouteError, -} from "@remix-run/react"; -import invariant from "tiny-invariant"; - -import { deleteNote, getNote } from "~/models/note.server"; -import { requireUserId } from "~/session.server"; - -export const loader = async ({ params, request }: LoaderArgs) => { - const userId = await requireUserId(request); - invariant(params.noteId, "noteId not found"); - - const note = await getNote({ id: params.noteId, userId }); - if (!note) { - throw new Response("Not Found", { status: 404 }); - } - return json({ note }); -}; - -export const action = async ({ params, request }: ActionArgs) => { - const userId = await requireUserId(request); - invariant(params.noteId, "noteId not found"); - - await deleteNote({ id: params.noteId, userId }); - - return redirect("/notes"); -}; - -export default function NoteDetailsPage() { - const data = useLoaderData(); - - return ( -
-

{data.note.title}

-

{data.note.body}

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

Unknown Error

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

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

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