Skip to content

Commit

Permalink
implement graphql backend, automate type generation
Browse files Browse the repository at this point in the history
  • Loading branch information
geovla93 committed Sep 1, 2022
1 parent f98ff29 commit 2ed335e
Show file tree
Hide file tree
Showing 51 changed files with 7,632 additions and 404 deletions.
3 changes: 3 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "next/core-web-vitals"
}
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ yarn-error.log*
.pnpm-debug.log*

# local env files
.env
.env*.local

# vercel
Expand Down
4 changes: 4 additions & 0 deletions .prettierrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"singleQuote": true,
"trailingComma": "all"
}
9 changes: 9 additions & 0 deletions codegen.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
overwrite: true
schema: "./src/graphql/generated/schema.graphql"
documents: "./src/graphql/operations/**/*.graphql"
generates:
./src/graphql/generated/codegen.ts:
plugins:
- "typescript"
- "typescript-operations"
- "typescript-react-apollo"
39 changes: 37 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,55 @@
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
"start": "next start",
"lint": "next lint",
"generate:nexus": "tsnd -r tsconfig-paths/register -P tsconfig.nexus.json --transpile-only ./src/graphql/schema.ts",
"generate:codegen": "graphql-codegen --config codegen.yml",
"generate:graphql": "yarn generate:nexus && yarn generate:codegen",
"prisma:migrate": "prisma migrate dev",
"prisma:seed": "prisma db seed"
},
"dependencies": {
"@apollo/client": "^3.6.9",
"@prisma/client": "^4.3.0",
"@types/micro-cors": "^0.1.2",
"apollo-server-micro": "^3.10.2",
"argon2": "^0.29.1",
"cloudinary": "^1.31.0",
"formidable": "^2.0.1",
"graphql": "^16.6.0",
"graphql-scalars": "^1.18.0",
"micro": "^9.4.1",
"micro-cors": "^0.1.1",
"next": "latest",
"next-auth": "^4.10.3",
"nexus": "^1.3.0",
"react": "18.1.0",
"react-dom": "18.1.0"
"react-dom": "18.1.0",
"zod": "^3.18.0"
},
"devDependencies": {
"@graphql-codegen/cli": "2.12.0",
"@graphql-codegen/typescript": "2.7.3",
"@graphql-codegen/typescript-operations": "2.5.3",
"@graphql-codegen/typescript-react-apollo": "3.3.3",
"@types/formidable": "^2.0.5",
"@types/node": "17.0.35",
"@types/react": "18.0.9",
"@types/react-dom": "18.0.5",
"autoprefixer": "^10.4.7",
"eslint": "8.23.0",
"eslint-config-next": "12.2.5",
"eslint-config-prettier": "^8.5.0",
"postcss": "^8.4.14",
"prettier": "^2.7.1",
"prettier-plugin-tailwindcss": "^0.1.13",
"prisma": "^4.3.0",
"tailwindcss": "^3.1.2",
"ts-node-dev": "^2.0.0",
"typescript": "4.7.2"
},
"prisma": {
"seed": "tsnd -P tsconfig.nexus.json prisma/seed.ts"
}
}
8 changes: 0 additions & 8 deletions pages/_app.tsx

This file was deleted.

13 changes: 0 additions & 13 deletions pages/api/hello.ts

This file was deleted.

86 changes: 0 additions & 86 deletions pages/index.tsx

This file was deleted.

39 changes: 39 additions & 0 deletions prisma/migrations/20220901160133_init/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
-- CreateTable
CREATE TABLE "users" (
"id" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
"firstName" TEXT NOT NULL,
"lastName" TEXT NOT NULL,
"email" TEXT NOT NULL,
"password" TEXT NOT NULL,

CONSTRAINT "users_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "events" (
"id" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
"name" TEXT NOT NULL,
"slug" TEXT NOT NULL,
"venue" TEXT NOT NULL,
"address" TEXT NOT NULL,
"performers" TEXT[],
"date" TEXT NOT NULL,
"time" TEXT NOT NULL,
"image" TEXT,
"userId" TEXT NOT NULL,

CONSTRAINT "events_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX "users_email_key" ON "users"("email");

-- CreateIndex
CREATE UNIQUE INDEX "events_slug_key" ON "events"("slug");

-- AddForeignKey
ALTER TABLE "events" ADD CONSTRAINT "events_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/*
Warnings:
- Added the required column `description` to the `events` table without a default value. This is not possible if the table is not empty.
*/
-- AlterTable
ALTER TABLE "events" ADD COLUMN "description" TEXT NOT NULL;
3 changes: 3 additions & 0 deletions prisma/migrations/migration_lock.toml
Original file line number Diff line number Diff line change
@@ -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"
43 changes: 43 additions & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// 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 = "postgresql"
url = env("DATABASE_URL")
}

model User {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
firstName String
lastName String
email String @unique
password String
events Event[]
@@map("users")
}

model Event {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
name String
slug String @unique
venue String
address String
performers String[]
date String
time String
description String
image String?
userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@map("events")
}
19 changes: 19 additions & 0 deletions prisma/seed.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { PrismaClient } from '@prisma/client';

import { events } from '../src/utils/data.json';

const prisma = new PrismaClient();

export async function main() {
try {
console.log(`Start seeding ...`);
await prisma.event.createMany({ data: events });
console.log(`Seeding finished.`);
} catch (err) {
console.error(err);
process.exit(1);
} finally {
await prisma.$disconnect();
}
}
main();
67 changes: 67 additions & 0 deletions src/graphql/client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { IncomingMessage, ServerResponse } from 'http';
import { useMemo } from 'react';
import {
ApolloClient,
HttpLink,
InMemoryCache,
NormalizedCacheObject,
} from '@apollo/client';

let apolloClient: ApolloClient<NormalizedCacheObject> | undefined;

export type ResolverContext = {
req?: IncomingMessage;
res?: ServerResponse;
};

function createIsomorphLink(context: ResolverContext = {}) {
if (typeof window === 'undefined') {
const { SchemaLink } = require('@apollo/client/link/schema');
const { schema } = require('./schema');

return new SchemaLink({ schema, context });
} else {
const { HttpLink } = require('@apollo/client');
return new HttpLink({
uri: '/api/graphql',
credentials: 'same-origin',
});
}
}

function createApolloClient(context?: ResolverContext) {
return new ApolloClient({
ssrMode: typeof window === 'undefined',
link: new HttpLink({
uri: 'http://localhost:3000/api/graphql',
credentials: 'same-origin',
}),
cache: new InMemoryCache(),
});
}

export function initializeApollo(
initialState: any = null,
// Pages with Next.js data fetching methods, like `getStaticProps`, can send
// a custom context which will be used by `SchemaLink` to server render pages
context?: ResolverContext,
) {
const _apolloClient = apolloClient ?? createApolloClient(context);

// If your page has Next.js data fetching methods that use Apollo Client, the initial state
// get hydrated here
if (initialState) {
_apolloClient.cache.restore(initialState);
}
// For SSG and SSR always create a new Apollo Client
if (typeof window === 'undefined') return _apolloClient;
// Create the Apollo Client once in the client
if (!apolloClient) apolloClient = _apolloClient;

return _apolloClient;
}

export function useApollo(initialState: any) {
const store = useMemo(() => initializeApollo(initialState), [initialState]);
return store;
}
Loading

0 comments on commit 2ed335e

Please sign in to comment.