Add beer post, brewery post GET service and page

Add prettier, eslint config
This commit is contained in:
Aaron William Po
2023-01-22 20:56:33 -05:00
parent a434e1bb98
commit 0065525f5c
29 changed files with 8696 additions and 6977 deletions

View File

@@ -1,3 +1,10 @@
{
"extends": "next/core-web-vitals"
"extends": ["next/core-web-vitals", "airbnb-base", "airbnb-typescript", "prettier"],
"rules": {
"arrow-body-style": "off",
"import/extensions": "off"
},
"parserOptions": {
"project": ["./tsconfig.json"]
}
}

2
.prettierignore Normal file
View File

@@ -0,0 +1,2 @@
node_modules
.next

6
.prettierrc Normal file
View File

@@ -0,0 +1,6 @@
{
"semi": true,
"trailingComma": "all",
"singleQuote": true,
"printWidth": 90
}

15
components/Layout.tsx Normal file
View File

@@ -0,0 +1,15 @@
import { FC, ReactNode } from 'react';
import Navbar from './Navbar';
const Layout: FC<{ children: ReactNode }> = ({ children }) => {
return (
<div className="flex h-screen flex-col">
<header className="top-0">
<Navbar />
</header>
<div className="top-0 h-full flex-1 animate-in fade-in">{children}</div>
</div>
);
};
export default Layout;

88
components/Navbar.tsx Normal file
View File

@@ -0,0 +1,88 @@
/* eslint-disable jsx-a11y/no-noninteractive-tabindex */
/* eslint-disable jsx-a11y/label-has-associated-control */
/* eslint-disable jsx-a11y/label-has-for */
import Link from 'next/link';
import { useRouter } from 'next/router';
import { useEffect, useState } from 'react';
interface Page {
slug: string;
name: string;
}
const Navbar = () => {
const router = useRouter();
const [currentURL, setCurrentURL] = useState('/');
useEffect(() => {
setCurrentURL(router.asPath);
}, [router.asPath]);
const pages: Page[] = [
{ slug: '/beers', name: 'Beers' },
{ slug: '/breweries', name: 'Breweries' },
];
return (
<nav className="navbar bg-base-300">
<div className="flex-1">
<Link className="btn-ghost btn text-3xl normal-case" href="/">
<span className="cursor-pointer text-xl font-bold">Aaron William Po</span>
</Link>
</div>
<div className="hidden flex-none lg:block">
<ul className="menu menu-horizontal p-0">
{pages.map((page) => {
return (
<li key={page.slug}>
<Link tabIndex={0} href={page.slug}>
<span
className={`text-lg uppercase ${
currentURL === page.slug ? 'font-extrabold' : 'font-semibold'
} text-base-content`}
>
{page.name}
</span>
</Link>
</li>
);
})}
</ul>
</div>
<div className="flex-none lg:hidden">
<div className="dropdown-end dropdown">
<label tabIndex={0} className="btn-ghost btn-circle btn">
<div className="w-10 rounded-full">
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
className="inline-block h-5 w-5 stroke-white"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M4 6h16M4 12h16M4 18h16"
/>
</svg>
</div>
</label>
<ul
tabIndex={0}
className="dropdown-content menu rounded-box menu-compact mt-3 w-48 bg-base-100 p-2 shadow"
>
{pages.map((page) => (
<li key={page.slug}>
<Link href={page.slug}>
<span className="select-none">{page.name}</span>
</Link>
</li>
))}
</ul>
</div>
</div>
</nav>
);
};
export default Navbar;

View File

@@ -1,6 +1,6 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
}
};
module.exports = nextConfig
module.exports = nextConfig;

14875
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,34 +1,44 @@
{
"name": "my-project",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"prismaDev": "dotenv -e .env.local prisma migrate dev"
},
"dependencies": {
"@next/font": "13.1.2",
"@prisma/client": "^4.8.1",
"@types/node": "18.11.18",
"@types/react": "18.0.26",
"@types/react-dom": "18.0.10",
"daisyui": "^2.47.0",
"eslint": "8.32.0",
"eslint-config-next": "13.1.2",
"next": "13.1.2",
"react": "18.2.0",
"react-dom": "18.2.0",
"typescript": "4.9.4"
},
"devDependencies": {
"autoprefixer": "^10.4.13",
"dotenv-cli": "^6.0.0",
"postcss": "^8.4.21",
"prisma": "^4.8.1",
"tailwindcss": "^3.2.4",
"ts-node": "^10.9.1"
}
"name": "my-project",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"format": "npx prettier . --write",
"prismaDev": "dotenv -e .env.local prisma migrate dev"
},
"dependencies": {
"@next/font": "13.1.2",
"@prisma/client": "^4.8.1",
"@types/node": "18.11.18",
"@types/react": "18.0.26",
"@types/react-dom": "18.0.10",
"daisyui": "^2.47.0",
"eslint": "8.32.0",
"eslint-config-next": "13.1.2",
"next": "13.1.2",
"react": "18.2.0",
"react-dom": "18.2.0",
"typescript": "4.9.4"
},
"devDependencies": {
"@faker-js/faker": "^7.6.0",
"autoprefixer": "^10.4.13",
"dotenv-cli": "^6.0.0",
"postcss": "^8.4.21",
"prisma": "^4.8.1",
"tailwindcss": "^3.2.4",
"eslint": "^8.30.0",
"eslint-config-airbnb-base": "15.0.0",
"eslint-config-airbnb-typescript": "17.0.0",
"eslint-config-next": "^13.0.7",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-react": "^7.31.11",
"prettier": "^2.8.1",
"prettier-plugin-tailwindcss": "^0.2.1",
"ts-node": "^10.9.1"
}
}

View File

@@ -1,6 +1,6 @@
import '@/styles/globals.css'
import type { AppProps } from 'next/app'
import '@/styles/globals.css';
import type { AppProps } from 'next/app';
export default function App({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />
return <Component {...pageProps} />;
}

View File

@@ -1,4 +1,4 @@
import { Html, Head, Main, NextScript } from 'next/document'
import { Html, Head, Main, NextScript } from 'next/document';
export default function Document() {
return (
@@ -9,5 +9,5 @@ export default function Document() {
<NextScript />
</body>
</Html>
)
);
}

View File

@@ -1,10 +0,0 @@
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from "next";
type Data = {
name: string;
};
export default function handler(req: NextApiRequest, res: NextApiResponse<Data>) {
res.status(200).json({ name: "John Doe" });
}

27
pages/beers/[id].tsx Normal file
View File

@@ -0,0 +1,27 @@
import { GetServerSideProps, NextPage } from 'next';
import BeerPostQueryResult from '@/services/BeerPost/types/BeerPostQueryResult';
import getBeerPostById from '@/services/BeerPost/getBeerPostById';
import Layout from '@/components/Layout';
interface BeerPageProps {
beerPost: BeerPostQueryResult;
}
const BeerByIdPage: NextPage<BeerPageProps> = ({ beerPost }) => {
return (
<Layout>
<main>
<h1 className="text-3xl font-bold underline">{beerPost.name}</h1>
</main>
</Layout>
);
};
export const getServerSideProps: GetServerSideProps<BeerPageProps> = async (context) => {
const beerPost = await getBeerPostById(context.params!.id! as string);
return !beerPost
? { notFound: true }
: { props: { beerPost: JSON.parse(JSON.stringify(beerPost)) } };
};
export default BeerByIdPage;

104
pages/beers/index.tsx Normal file
View File

@@ -0,0 +1,104 @@
import { GetServerSideProps, NextPage } from 'next';
import getAllBeerPosts from '@/services/BeerPost/getAllBeerPosts';
import BeerPostQueryResult from '@/services/BeerPost/types/BeerPostQueryResult';
import Link from 'next/link';
import { useRouter } from 'next/router';
import DBClient from '@/prisma/client';
import Layout from '@/components/Layout';
import { FC } from 'react';
interface BeerPageProps {
initialBeerPosts: BeerPostQueryResult[];
pageCount: number;
}
interface PaginationProps {
pageNum: number;
pageCount: number;
}
const Pagination: FC<PaginationProps> = ({ pageCount, pageNum }) => {
const router = useRouter();
return (
<div className="btn-group">
<button
className="btn"
disabled={pageNum <= 1}
onClick={async () =>
router.push({ pathname: '/beers', query: { page_num: pageNum - 1 } })
}
>
«
</button>
<button className="btn">Page {pageNum}</button>
<button
className="btn"
disabled={pageNum >= pageCount}
onClick={async () =>
router.push({ pathname: '/beers', query: { page_num: pageNum + 1 } })
}
>
»
</button>
</div>
);
};
const BeerCard: FC<{ post: BeerPostQueryResult }> = ({ post }) => {
return (
<div className="card h-52 bg-base-200 p-6" key={post.id}>
<div className="card-content space-y-3">
<div>
<h2 className="text-3xl font-bold">
<Link href={`/beers/${post.id}`}>{post.name}</Link>
</h2>
<h3 className="text-xl font-semibold">{post.brewery.name}</h3>
</div>
<div>
<p>{post.description}</p>
</div>
</div>
</div>
);
};
const BeerPage: NextPage<BeerPageProps> = ({ initialBeerPosts, pageCount }) => {
const router = useRouter();
const { query } = router;
const pageNum = parseInt(query.page_num as string, 10) || 1;
return (
<Layout>
<div className="flex items-center justify-center">
<main className="mt-10 flex w-8/12 flex-col space-y-4">
<h1 className="card-title text-5xl font-bold">Beer Posts</h1>
<div className="space-y-4">
{initialBeerPosts.map((post) => {
return <BeerCard post={post} key={post.id} />;
})}
</div>
<Pagination pageNum={pageNum} pageCount={pageCount} />
</main>
</div>
</Layout>
);
};
export const getServerSideProps: GetServerSideProps<BeerPageProps> = async (context) => {
const { query } = context;
const pageNumber = parseInt(query.page_num as string, 10) || 1;
const pageSize = 9;
const numberOfPosts = await DBClient.instance.beerPost.count();
const pageCount = numberOfPosts ? Math.ceil(numberOfPosts / pageSize) : 0;
const beerPosts = await getAllBeerPosts(pageNumber, pageSize);
return {
props: { initialBeerPosts: JSON.parse(JSON.stringify(beerPosts)), pageCount },
};
};
export default BeerPage;

26
pages/breweries/[id].tsx Normal file
View File

@@ -0,0 +1,26 @@
import { GetServerSideProps, NextPage } from 'next';
import BeerPostQueryResult from '@/services/BeerPost/types/BeerPostQueryResult';
import getBreweryPostById from '@/services/BreweryPost/getBreweryPostById';
interface BreweryPageProps {
breweryPost: BeerPostQueryResult;
}
const BreweryByIdPage: NextPage<BreweryPageProps> = ({ breweryPost }) => {
return (
<>
<h1 className="text-3xl font-bold underline">{breweryPost.name}</h1>
</>
);
};
export const getServerSideProps: GetServerSideProps<BreweryPageProps> = async (
context,
) => {
const breweryPost = await getBreweryPostById(context.params!.id! as string);
return !breweryPost
? { notFound: true }
: { props: { breweryPost: JSON.parse(JSON.stringify(breweryPost)) } };
};
export default BreweryByIdPage;

35
pages/breweries/index.tsx Normal file
View File

@@ -0,0 +1,35 @@
import { GetServerSideProps, NextPage } from 'next';
import Link from 'next/link';
import getAllBreweryPosts from '@/services/BreweryPost/getAllBreweryPosts';
import GetAllBreweryPostsQueryResult from '@/services/BreweryPost/types/BreweryPostQueryResult';
interface BreweryPageProps {
breweryPosts: GetAllBreweryPostsQueryResult[];
}
const BreweryPage: NextPage<BreweryPageProps> = ({ breweryPosts }) => {
return (
<>
<h1 className="text-3xl font-bold underline">Brewery Posts</h1>
{breweryPosts.map((post) => {
return (
<div key={post.id}>
<h2>
<Link href={`/breweries/${post.id}`}>{post.name}</Link>
</h2>
</div>
);
})}
</>
);
};
export const getServerSideProps: GetServerSideProps<BreweryPageProps> = async () => {
const breweryPosts = await getAllBreweryPosts();
return {
props: { breweryPosts: JSON.parse(JSON.stringify(breweryPosts)) },
};
};
export default BreweryPage;

View File

@@ -1,24 +1,7 @@
import { PrismaClient } from "@prisma/client";
import type { BeerPost } from "@prisma/client";
import { GetServerSideProps, NextPage } from "next";
import { NextPage } from 'next';
export const getServerSideProps: GetServerSideProps<{}> = async () => {
const prisma = new PrismaClient();
const beerPosts = await prisma.beerPost.findMany();
return {
props: {
beerPosts,
},
};
};
interface HomePageProps {
beerPosts: BeerPost[];
}
const Home: NextPage<HomePageProps> = ({ beerPosts }) => {
console.log(beerPosts);
return <h1 className="text-3xl font-bold underline">Hello world!</h1>;
const Home: NextPage = () => {
return <h1 className="text-3xl font-bold underline">Hello world!</h1>;
};
export default Home;

View File

@@ -3,4 +3,4 @@ module.exports = {
tailwindcss: {},
autoprefixer: {},
},
}
};

11
prisma/client.ts Normal file
View File

@@ -0,0 +1,11 @@
import { PrismaClient } from '@prisma/client';
const DBClient = {
instance: new PrismaClient(),
};
export type IDBClient = typeof DBClient;
Object.freeze(DBClient);
export default DBClient;

View File

@@ -0,0 +1,18 @@
/*
Warnings:
- Added the required column `description` to the `BeerPost` table without a default value. This is not possible if the table is not empty.
- Added the required column `description` to the `BreweryPost` table without a default value. This is not possible if the table is not empty.
- Added the required column `dateOfBirth` to the `User` table without a default value. This is not possible if the table is not empty.
- Added the required column `username` to the `User` table without a default value. This is not possible if the table is not empty.
*/
-- AlterTable
ALTER TABLE "BeerPost" ADD COLUMN "description" TEXT NOT NULL;
-- AlterTable
ALTER TABLE "BreweryPost" ADD COLUMN "description" TEXT NOT NULL;
-- AlterTable
ALTER TABLE "User" ADD COLUMN "dateOfBirth" TIMESTAMP(3) NOT NULL,
ADD COLUMN "username" TEXT NOT NULL;

View File

@@ -12,11 +12,13 @@ datasource db {
model User {
id String @id @default(cuid())
username String
firstName String
lastName String
email String
createdAt DateTime @default(now()) @db.Timestamptz(3)
updatedAt DateTime? @updatedAt @db.Timestamptz(3)
dateOfBirth DateTime
beerPosts BeerPost[]
beerTypes BeerType[]
breweryPosts BreweryPost[]
@@ -29,6 +31,7 @@ model BeerPost {
name String
ibu Float
abv Float
description String
postedBy User @relation(fields: [postedById], references: [id])
postedById String
brewery BreweryPost @relation(fields: [breweryId], references: [id])
@@ -66,6 +69,7 @@ model BreweryPost {
name String
location String
beers BeerPost[]
description String
createdAt DateTime @default(now()) @db.Timestamptz(3)
updatedAt DateTime? @updatedAt @db.Timestamptz(3)
postedBy User @relation(fields: [postedById], references: [id])

126
prisma/seed.ts Normal file
View File

@@ -0,0 +1,126 @@
import { BeerPost, BeerType, BreweryPost, PrismaClient, User } from '@prisma/client';
import { faker } from '@faker-js/faker';
const prisma = new PrismaClient();
const createNewUsers = () => {
const userPromises: Promise<User>[] = [];
Array.from({ length: 100 }).forEach(() => {
const firstName = faker.name.firstName();
const lastName = faker.name.lastName();
const email = faker.internet.email(firstName, lastName, 'example.com');
userPromises.push(
prisma.user.create({
data: {
firstName,
lastName,
email,
username: `${firstName[0]}.${lastName}`,
dateOfBirth: faker.date.birthdate({ mode: 'age', min: 19 }),
},
}),
);
});
return Promise.all(userPromises);
};
const createNewBreweryPosts = (users: User[]) => {
const breweryPromises: Promise<BreweryPost>[] = [];
Array.from({ length: 100 }).forEach(() => {
const name = `${faker.commerce.productName()} Brewing Company`;
const location = faker.address.cityName();
const description = faker.lorem.lines();
const user = users[Math.floor(Math.random() * users.length)];
breweryPromises.push(
prisma.breweryPost.create({
data: { name, location, description, postedBy: { connect: { id: user.id } } },
}),
);
});
return Promise.all(breweryPromises);
};
const createNewBeerTypes = (users: User[]) => {
const beerTypePromises: Promise<BeerType>[] = [];
const types = [
'IPA',
'Pilsner',
'Stout',
'Lager',
'Wheat Beer',
'Belgian Ale',
'Pale Ale',
'Brown Ale',
'Sour Beer',
'Porter',
'Bock',
'Rauchbier',
'Sasion',
'Kolsch',
'Helles',
'Weizenbock',
'Doppelbock',
'Eisbock',
'Barley Wine',
];
types.forEach((type) => {
const user = users[Math.floor(Math.random() * users.length)];
beerTypePromises.push(
prisma.beerType.create({
data: { name: type, postedBy: { connect: { id: user.id } } },
}),
);
});
return Promise.all(beerTypePromises);
};
const createNewBeerPosts = (
users: User[],
breweryPosts: BreweryPost[],
beerTypes: BeerType[],
) => {
const beerPostPromises: Promise<BeerPost>[] = [];
Array.from({ length: 100 }).forEach(() => {
const user = users[Math.floor(Math.random() * users.length)];
const beerType = beerTypes[Math.floor(Math.random() * beerTypes.length)];
const breweryPost = breweryPosts[Math.floor(Math.random() * breweryPosts.length)];
beerPostPromises.push(
prisma.beerPost.create({
data: {
abv: 10,
ibu: 10,
name: `${faker.commerce.productName()} ${beerType.name}`,
description: faker.lorem.lines(),
brewery: { connect: { id: breweryPost.id } },
postedBy: { connect: { id: user.id } },
type: { connect: { id: beerType.id } },
},
}),
);
});
return Promise.all(beerPostPromises);
};
async function main() {
const users = await createNewUsers();
const breweryPosts = await createNewBreweryPosts(users);
const beerTypes = await createNewBeerTypes(users);
const beerPosts = await createNewBeerPosts(users, breweryPosts, beerTypes);
console.log({ users, breweryPosts, beerTypes, beerPosts });
}
main().then(() => {
console.log('Seeded database.');
});

View File

@@ -0,0 +1,35 @@
import DBClient from '@/prisma/client';
import BeerPostQueryResult from './types/BeerPostQueryResult';
const prisma = DBClient.instance;
const getAllBeerPosts = async (pageNum: number, pageSize: number) => {
const skip = (pageNum - 1) * pageSize;
const beerPosts: BeerPostQueryResult[] = await prisma.beerPost.findMany({
select: {
id: true,
name: true,
brewery: {
select: {
name: true,
id: true,
},
},
description: true,
postedBy: {
select: {
firstName: true,
lastName: true,
id: true,
},
},
},
take: pageSize,
skip,
});
return beerPosts;
};
export default getAllBeerPosts;

View File

@@ -0,0 +1,33 @@
import DBClient from '@/prisma/client';
import BeerPostQueryResult from './types/BeerPostQueryResult';
const prisma = DBClient.instance;
const getBeerPostById = async (id: string) => {
const beerPost: BeerPostQueryResult | null = await prisma.beerPost.findFirst({
select: {
id: true,
name: true,
brewery: {
select: {
name: true,
id: true,
},
},
postedBy: {
select: {
firstName: true,
lastName: true,
id: true,
},
},
},
where: {
id,
},
});
return beerPost;
};
export default getBeerPostById;

View File

@@ -0,0 +1,14 @@
export default interface BeerPostQueryResult {
id: string;
name: string;
brewery: {
id: string;
name: string;
};
description: string;
postedBy: {
id: string;
firstName: string;
lastName: string;
};
}

View File

@@ -0,0 +1,21 @@
import DBClient from '@/prisma/client';
import GetAllBreweryPostsQueryResult from './types/BreweryPostQueryResult';
const prisma = DBClient.instance;
const getAllBreweryPosts = async () => {
const breweryPosts: GetAllBreweryPostsQueryResult[] = await prisma.breweryPost.findMany(
{
select: {
id: true,
location: true,
name: true,
postedBy: { select: { firstName: true, lastName: true, id: true } },
},
},
);
return breweryPosts;
};
export default getAllBreweryPosts;

View File

@@ -0,0 +1,29 @@
import DBClient from '@/prisma/client';
import GetAllBreweryPostsQueryResult from './types/BreweryPostQueryResult';
const prisma = DBClient.instance;
const getBreweryPostById = async (id: string) => {
const breweryPost: GetAllBreweryPostsQueryResult | null =
await prisma.breweryPost.findFirst({
select: {
id: true,
location: true,
name: true,
postedBy: {
select: {
firstName: true,
lastName: true,
id: true,
},
},
},
where: {
id,
},
});
return breweryPost;
};
export default getBreweryPostById;

View File

@@ -0,0 +1,10 @@
export default interface GetAllBreweryPostsQueryResult {
id: string;
location: string;
name: string;
postedBy: {
id: string;
firstName: string;
lastName: string;
};
}

View File

@@ -1,12 +1,12 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
content: ["./pages/**/*.{js,ts,jsx,tsx}", "./components/**/*.{js,ts,jsx,tsx}"],
theme: {
extend: {},
},
plugins: [require("daisyui")],
daisyui: {
logs: false,
themes: ["coffee"],
},
content: ['./pages/**/*.{js,ts,jsx,tsx}', './components/**/*.{js,ts,jsx,tsx}'],
theme: {
extend: {},
},
plugins: [require('daisyui')],
daisyui: {
logs: false,
themes: ['garden'],
},
};

View File

@@ -1,24 +1,24 @@
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "CommonJS",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"baseUrl": ".",
"paths": {
"@/*": ["./*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "CommonJS",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"baseUrl": ".",
"paths": {
"@/*": ["./*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}