begin working on db schema

This commit is contained in:
keyan 2021-03-25 14:29:24 -05:00
parent 53a3236b0d
commit 341b3a291a
21 changed files with 3363 additions and 99 deletions

1
.gitignore vendored
View File

@ -25,6 +25,7 @@ yarn-debug.log*
yarn-error.log*
# local env files
.env
.env.local
.env.development.local
.env.test.local

14
api/models/index.js Normal file
View File

@ -0,0 +1,14 @@
import { PrismaClient } from '@prisma/client'
let prisma
if (process.env.NODE_ENV === 'production') {
prisma = new PrismaClient()
} else {
if (!global.prisma) {
global.prisma = new PrismaClient()
}
prisma = global.prisma
}
export default prisma

4
api/resolvers/index.js Normal file
View File

@ -0,0 +1,4 @@
import user from './user'
import message from './message'
export default [user, message]

29
api/resolvers/message.js Normal file
View File

@ -0,0 +1,29 @@
import { UserInputError } from 'apollo-server-micro'
export default {
Query: {
messages: async (parent, args, { models }) =>
await models.message.findMany(),
message: async (parent, { id }, { models }) =>
await models.message.findUnique({ where: { id } })
},
Mutation: {
createMessage: async (parent, { text }, { me, models }) => {
if (!text) {
throw new UserInputError('Must have text', { argumentName: 'text' })
}
return await models.message.create({
data: { text, userId: me.id }
})
},
deleteMessage: async (parent, { id }, { models }) =>
await models.message.delete({ where: { id } })
},
Message: {
user: async (message, args, { models }) =>
await models.user.findUnique({ where: { id: message.userId } })
}
}

19
api/resolvers/user.js Normal file
View File

@ -0,0 +1,19 @@
export default {
Query: {
me: async (parent, args, { models, me }) =>
me ? await models.user.findUnique({ where: { id: me.id } }) : null,
user: async (parent, { id }, { models }) =>
await models.user.findUnique({ where: { id } }),
users: async (parent, args, { models }) =>
await models.user.findMany()
},
User: {
messages: async (user, args, { models }) =>
await models.message.findMany({
where: {
userId: user.id
}
})
}
}

20
api/typeDefs/index.js Normal file
View File

@ -0,0 +1,20 @@
import { gql } from 'apollo-server-micro'
import user from './user'
import message from './message'
const link = gql`
type Query {
_: Boolean
}
type Mutation {
_: Boolean
}
type Subscription {
_: Boolean
}
`
export default [link, user, message]

19
api/typeDefs/message.js Normal file
View File

@ -0,0 +1,19 @@
import { gql } from 'apollo-server-micro'
export default gql`
extend type Query {
messages: [Message!]!
message(id: ID!): Message!
}
extend type Mutation {
createMessage(text: String!): Message!
deleteMessage(id: ID!): Boolean!
}
type Message {
id: ID!
text: String!
user: User!
}
`

15
api/typeDefs/user.js Normal file
View File

@ -0,0 +1,15 @@
import { gql } from 'apollo-server-micro'
export default gql`
extend type Query {
me: User
user(id: ID!): User
users: [User!]
}
type User {
id: ID!
name: String
messages: [Message!]
}
`

28
components/header.js Normal file
View File

@ -0,0 +1,28 @@
import { signOut, signIn, useSession } from 'next-auth/client'
export default function Header () {
const [session, loading] = useSession()
if (loading) {
return <p>Validating session ...</p>
}
if (session) {
return (
<>
<p>
{session.user.name} ({session.user.email})
</p>
<button onClick={() => signOut()}>
<a>Log out</a>
</button>
</>
)
}
return (
<button onClick={() => signIn()}>
<a>Log in</a>
</button>
)
}

View File

@ -8,8 +8,32 @@
"start": "next start"
},
"dependencies": {
"@prisma/client": "^2.19.0",
"apollo-server-micro": "^2.21.2",
"graphql": "^15.5.0",
"next": "10.0.9",
"next-auth": "^3.13.3",
"react": "17.0.1",
"react-dom": "17.0.1"
"react-dom": "17.0.1",
"swr": "^0.5.4"
},
"standard": {
"parser": "babel-eslint",
"plugins": [
"eslint-plugin-compat"
],
"extends": [
"plugin:compat/recommended"
],
"env": {
"browser": true
}
},
"devDependencies": {
"babel-eslint": "^10.1.0",
"eslint": "^7.22.0",
"eslint-plugin-compat": "^3.9.0",
"prisma": "2.19.0",
"standard": "^16.0.3"
}
}

View File

@ -1,6 +1,6 @@
import '../styles/globals.css'
function MyApp({ Component, pageProps }) {
function MyApp ({ Component, pageProps }) {
return <Component {...pageProps} />
}

View File

@ -0,0 +1,22 @@
import { NextApiHandler } from 'next'
import NextAuth from 'next-auth'
import Providers from 'next-auth/providers'
import Adapters from 'next-auth/adapters'
import prisma from '../../../api/models'
export default (req, res) => NextAuth(req, res, options)
const options = {
providers: [
Providers.GitHub({
clientId: process.env.GITHUB_ID,
clientSecret: process.env.GITHUB_SECRET,
}),
Providers.Email({
server: process.env.EMAIL_SERVER,
from: process.env.EMAIL_FROM
})
],
adapter: Adapters.Prisma.Adapter({ prisma }),
secret: process.env.SECRET,
}

21
pages/api/graphql.js Normal file
View File

@ -0,0 +1,21 @@
import { ApolloServer } from 'apollo-server-micro'
import resolvers from '../../api/resolvers'
import models from '../../api/models'
import typeDefs from '../../api/typeDefs'
const apolloServer = new ApolloServer({
typeDefs,
resolvers,
context: async () => ({
models,
me: await models.user.findUnique({ where: { name: 'k00b' } })
})
})
export const config = {
api: {
bodyParser: false
}
}
export default apolloServer.createHandler({ path: '/api/graphql' })

View File

@ -1,6 +0,0 @@
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
export default (req, res) => {
res.statusCode = 200
res.json({ name: 'John Doe' })
}

View File

@ -1,65 +1,31 @@
import Head from 'next/head'
import styles from '../styles/Home.module.css'
import useSWR from 'swr'
import Header from '../components/header'
const fetcher = (query) =>
fetch('/api/graphql', {
method: 'POST',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({ query })
})
.then((res) => res.json())
.then((json) => json.data)
export default function Index () {
const { data, error } = useSWR('{ users { name } }', fetcher)
if (error) return <div>Failed to load</div>
if (!data) return <div>Loading...</div>
const { users } = data
export default function Home() {
return (
<div className={styles.container}>
<Head>
<title>Create Next App</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<main className={styles.main}>
<h1 className={styles.title}>
Welcome to <a href="https://nextjs.org">Next.js!</a>
</h1>
<p className={styles.description}>
Get started by editing{' '}
<code className={styles.code}>pages/index.js</code>
</p>
<div className={styles.grid}>
<a href="https://nextjs.org/docs" className={styles.card}>
<h3>Documentation &rarr;</h3>
<p>Find in-depth information about Next.js features and API.</p>
</a>
<a href="https://nextjs.org/learn" className={styles.card}>
<h3>Learn &rarr;</h3>
<p>Learn about Next.js in an interactive course with quizzes!</p>
</a>
<a
href="https://github.com/vercel/next.js/tree/master/examples"
className={styles.card}
>
<h3>Examples &rarr;</h3>
<p>Discover and deploy boilerplate example Next.js projects.</p>
</a>
<a
href="https://vercel.com/import?filter=next.js&utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
className={styles.card}
>
<h3>Deploy &rarr;</h3>
<p>
Instantly deploy your Next.js site to a public URL with Vercel.
</p>
</a>
</div>
</main>
<footer className={styles.footer}>
<a
href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Powered by{' '}
<img src="/vercel.svg" alt="Vercel Logo" className={styles.logo} />
</a>
</footer>
<div>
<Header />
{users.map((user, i) => (
<div key={i}>{user.name}</div>
))}
</div>
)
}

View File

@ -0,0 +1,147 @@
-- CreateTable
CREATE TABLE "users" (
"id" SERIAL NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
"name" TEXT,
"email" TEXT,
"email_verified" TIMESTAMP(3),
"image" TEXT,
PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Message" (
"id" SERIAL NOT NULL,
"text" TEXT NOT NULL,
"userId" INTEGER NOT NULL,
PRIMARY KEY ("id")
);
-- Edit: create extension for path
CREATE EXTENSION ltree;
-- CreateTable
CREATE TABLE "Item" (
"id" SERIAL NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
"text" TEXT NOT NULL,
"url" TEXT NOT NULL,
"userId" INTEGER NOT NULL,
"parentId" INTEGER,
"parentPath" LTREE,
PRIMARY KEY ("id")
);
-- Edit: create index for path
CREATE INDEX "Item.parentPath_index" ON "Item" USING GIST ("parentPath");
-- Edit: create trigger for path
CREATE OR REPLACE FUNCTION update_item_parent_path() RETURNS TRIGGER AS $$
DECLARE
path ltree;
BEGIN
IF NEW.parent_id IS NULL THEN
NEW.parent_path = 'root'::ltree;
ELSEIF TG_OP = 'INSERT' OR OLD.parent_id IS NULL OR OLD.parent_id != NEW.parent_id THEN
SELECT parent_path || id::text FROM "Item" WHERE id = NEW.parent_id INTO path;
IF path IS NULL THEN
RAISE EXCEPTION 'Invalid parent_id %', NEW.parent_id;
END IF;
NEW.parent_path = path;
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER parent_path_tgr
BEFORE INSERT OR UPDATE ON "Item"
FOR EACH ROW EXECUTE PROCEDURE update_item_parent_path();
-- CreateTable
CREATE TABLE "accounts" (
"id" SERIAL NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
"compound_id" TEXT NOT NULL,
"user_id" INTEGER NOT NULL,
"provider_type" TEXT NOT NULL,
"provider_id" TEXT NOT NULL,
"provider_account_id" TEXT NOT NULL,
"refresh_token" TEXT,
"access_token" TEXT,
"access_token_expires" TIMESTAMP(3),
PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "sessions" (
"id" SERIAL NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
"user_id" INTEGER NOT NULL,
"expires" TIMESTAMP(3) NOT NULL,
"session_token" TEXT NOT NULL,
"access_token" TEXT NOT NULL,
PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "verification_requests" (
"id" SERIAL NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
"identifier" TEXT NOT NULL,
"token" TEXT NOT NULL,
"expires" TIMESTAMP(3) NOT NULL,
PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "users.name_unique" ON "users"("name");
-- CreateIndex
CREATE UNIQUE INDEX "users.email_unique" ON "users"("email");
-- CreateIndex
CREATE INDEX "Item.userId_index" ON "Item"("userId");
-- CreateIndex
CREATE INDEX "Item.parentId_index" ON "Item"("parentId");
-- CreateIndex
CREATE UNIQUE INDEX "accounts.compound_id_unique" ON "accounts"("compound_id");
-- CreateIndex
CREATE INDEX "accounts.provider_account_id_index" ON "accounts"("provider_account_id");
-- CreateIndex
CREATE INDEX "accounts.provider_id_index" ON "accounts"("provider_id");
-- CreateIndex
CREATE INDEX "accounts.user_id_index" ON "accounts"("user_id");
-- CreateIndex
CREATE UNIQUE INDEX "sessions.session_token_unique" ON "sessions"("session_token");
-- CreateIndex
CREATE UNIQUE INDEX "sessions.access_token_unique" ON "sessions"("access_token");
-- CreateIndex
CREATE UNIQUE INDEX "verification_requests.token_unique" ON "verification_requests"("token");
-- AddForeignKey
ALTER TABLE "Message" ADD FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Item" ADD FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Item" ADD FOREIGN KEY ("parentId") REFERENCES "Item"("id") ON DELETE SET NULL ON UPDATE CASCADE;

View File

@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (i.e. Git)
provider = "postgresql"

91
prisma/schema.prisma Normal file
View File

@ -0,0 +1,91 @@
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
model User {
id Int @id @default(autoincrement())
createdAt DateTime @default(now()) @map(name: "created_at")
updatedAt DateTime @updatedAt @map(name: "updated_at")
name String? @unique
email String? @unique
emailVerified DateTime? @map(name: "email_verified")
image String?
item Item[]
messages Message[]
@@map(name: "users")
}
model Message {
id Int @id @default(autoincrement())
text String
user User @relation(fields: [userId], references: [id])
userId Int
}
model Item {
id Int @id @default(autoincrement())
createdAt DateTime @default(now()) @map(name: "created_at")
updatedAt DateTime @updatedAt @map(name: "updated_at")
text String
url String
user User @relation(fields: [userId], references: [id])
userId Int
parent Item? @relation("ParentChildren", fields: [parentId], references: [id])
parentId Int?
children Item[] @relation("ParentChildren")
parentPath Unsupported("LTREE")?
@@index([userId])
@@index([parentId])
}
model Account {
id Int @id @default(autoincrement())
createdAt DateTime @default(now()) @map(name: "created_at")
updatedAt DateTime @updatedAt @map(name: "updated_at")
compoundId String @unique @map(name: "compound_id")
userId Int @map(name: "user_id")
providerType String @map(name: "provider_type")
providerId String @map(name: "provider_id")
providerAccountId String @map(name: "provider_account_id")
refreshToken String? @map(name: "refresh_token")
accessToken String? @map(name: "access_token")
accessTokenExpires DateTime? @map(name: "access_token_expires")
@@index([providerAccountId])
@@index([providerId])
@@index([userId])
@@map(name: "accounts")
}
model Session {
id Int @id @default(autoincrement())
createdAt DateTime @default(now()) @map(name: "created_at")
updatedAt DateTime @updatedAt @map(name: "updated_at")
userId Int @map(name: "user_id")
expires DateTime
sessionToken String @unique @map(name: "session_token")
accessToken String @unique @map(name: "access_token")
@@map(name: "sessions")
}
model VerificationRequest {
id Int @id @default(autoincrement())
createdAt DateTime @default(now()) @map(name: "created_at")
updatedAt DateTime @updatedAt @map(name: "updated_at")
identifier String
token String @unique
expires DateTime
@@map(name: "verification_requests")
}

42
prisma/seed.js Normal file
View File

@ -0,0 +1,42 @@
const { PrismaClient } = require('@prisma/client')
const prisma = new PrismaClient()
async function main () {
const k00b = await prisma.user.upsert({
where: { name: 'k00b' },
update: {},
create: {
name: 'k00b',
messages: {
create: {
text: 'Hello world'
}
}
}
})
const satoshi = await prisma.user.upsert({
where: { name: 'satoshi' },
update: {},
create: {
name: 'satoshi',
messages: {
create: [
{
text: 'Peer to peer digital cash'
},
{
text: 'Reengineer the world'
}
]
}
}
})
console.log({ k00b, satoshi })
}
main()
.catch(e => {
console.error(e)
process.exit(1)
})
.finally(async () => {
await prisma.$disconnect()
})

View File

@ -1,4 +0,0 @@
<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>

Before

Width:  |  Height:  |  Size: 1.1 KiB

2863
yarn.lock

File diff suppressed because it is too large Load Diff