Skip to content

Commit

Permalink
feat: use prisma for db (#4034)
Browse files Browse the repository at this point in the history
  • Loading branch information
bigint authored Nov 19, 2023
1 parent 4ec6da0 commit 48df9c6
Show file tree
Hide file tree
Showing 32 changed files with 444 additions and 666 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ jobs:

- name: Run Tests 🧪
env:
SUPABASE_KEY: ${{ secrets.SUPABASE_KEY }}
DATABASE_URL: ${{ secrets.DATABASE_URL }}
SECRET: ${{ secrets.SECRET }}
EVER_ACCESS_KEY: ${{ secrets.EVER_ACCESS_KEY }}
EVER_ACCESS_SECRET: ${{ secrets.EVER_ACCESS_SECRET }}
Expand Down
2 changes: 1 addition & 1 deletion apps/api/.env.example
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
SUPABASE_KEY=""
DATABASE_URL=""
CLICKHOUSE_PASSWORD=""
SECRET="secret"
LIVEPEER_API_KEY=""
Expand Down
99 changes: 99 additions & 0 deletions apps/api/db/migrations/20231119154855_init/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
-- CreateEnum
CREATE TYPE "StaffPickType" AS ENUM ('PROFILE', 'GROUP');

-- CreateTable
CREATE TABLE "Verified" (
"id" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

-- CreateTable
CREATE TABLE "StaffPick" (
"id" TEXT NOT NULL,
"type" "StaffPickType" NOT NULL,
"score" INTEGER NOT NULL DEFAULT 0,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

-- CreateTable
CREATE TABLE "Preference" (
"id" TEXT NOT NULL,
"isPride" BOOLEAN NOT NULL DEFAULT false,
"highSignalNotificationFilter" BOOLEAN NOT NULL DEFAULT false,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

-- CreateTable
CREATE TABLE "MembershipNft" (
"id" TEXT NOT NULL,
"dismissedOrMinted" BOOLEAN NOT NULL DEFAULT false,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

-- CreateTable
CREATE TABLE "Group" (
"id" TEXT NOT NULL,
"slug" TEXT NOT NULL,
"name" TEXT NOT NULL,
"description" TEXT NOT NULL,
"avatar" TEXT NOT NULL,
"tags" TEXT[],
"lens" TEXT,
"x" TEXT,
"discord" TEXT,
"instagram" TEXT,
"featured" BOOLEAN NOT NULL DEFAULT false,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

-- CreateTable
CREATE TABLE "Pro" (
"profileId" TEXT NOT NULL,
"hash" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"expiresAt" TIMESTAMP(3),

CONSTRAINT "Pro_pkey" PRIMARY KEY ("profileId")
);

-- CreateTable
CREATE TABLE "Feature" (
"id" TEXT NOT NULL,
"key" TEXT NOT NULL,
"name" TEXT NOT NULL,
"description" TEXT NOT NULL,
"priority" INTEGER NOT NULL DEFAULT 0,
"enabled" BOOLEAN NOT NULL DEFAULT true,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

-- CreateTable
CREATE TABLE "ProfileFeature" (
"profileId" TEXT NOT NULL,
"featureId" TEXT NOT NULL,
"enabled" BOOLEAN NOT NULL DEFAULT true,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

CONSTRAINT "ProfileFeature_pkey" PRIMARY KEY ("profileId","featureId")
);

-- CreateIndex
CREATE UNIQUE INDEX "Group_slug_key" ON "Group"("slug");

-- CreateIndex
CREATE UNIQUE INDEX "Feature_key_key" ON "Feature"("key");

-- AddForeignKey
ALTER TABLE "ProfileFeature" ADD CONSTRAINT "ProfileFeature_featureId_fkey" FOREIGN KEY ("featureId") REFERENCES "Feature"("id") ON DELETE CASCADE ON UPDATE CASCADE;
3 changes: 3 additions & 0 deletions apps/api/db/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"
83 changes: 83 additions & 0 deletions apps/api/db/schema.prisma
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}

generator client {
provider = "prisma-client-js"
}

model Verified {
id String @id @default(uuid())
createdAt DateTime @default(now())
}

model StaffPick {
id String @id @default(uuid())
type StaffPickType
score Int @default(0)
createdAt DateTime @default(now())
}

model Preference {
id String @id @default(uuid())
isPride Boolean @default(false)
highSignalNotificationFilter Boolean @default(false)
createdAt DateTime @default(now())
}

model MembershipNft {
id String @id @default(uuid())
dismissedOrMinted Boolean @default(false)
createdAt DateTime @default(now())
}

model Group {
id String @id @default(uuid())
slug String @unique
name String
description String
avatar String
tags String[]
lens String?
x String?
discord String?
instagram String?
featured Boolean @default(false)
createdAt DateTime @default(now())
}

model Pro {
profileId String @id
hash String
createdAt DateTime @default(now())
expiresAt DateTime?
}

model Feature {
id String @id @default(uuid())
key String @unique
name String
description String
priority Int @default(0)
enabled Boolean @default(true)
createdAt DateTime @default(now())
// Relations
profiles ProfileFeature[]
}

model ProfileFeature {
profileId String
featureId String
feature Feature @relation(fields: [featureId], references: [id], onDelete: Cascade)
enabled Boolean @default(true)
createdAt DateTime @default(now())
@@id([profileId, featureId])
}

enum StaffPickType {
PROFILE
GROUP
}
7 changes: 6 additions & 1 deletion apps/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@
"lint:fix": "eslint . --fix --ext .js,.ts,.tsx",
"prettier": "prettier --check \"**/*.{js,ts,tsx,md}\" --cache",
"prettier:fix": "prettier --write \"**/*.{js,ts,tsx,md}\" --cache",
"prisma:format": "prisma format --schema ./db/schema.prisma",
"prisma:generate": "prisma generate --schema ./db/schema.prisma",
"prisma:migrate": "prisma migrate dev --schema ./db/schema.prisma",
"prisma:studio": "prisma studio --schema ./db/schema.prisma",
"start": "next start --port 4785",
"test:dev": "vitest run",
"typecheck": "tsc --pretty"
Expand All @@ -20,7 +24,7 @@
"@hey/data": "workspace:*",
"@hey/lib": "workspace:*",
"@irys/sdk": "^0.0.4",
"@supabase/supabase-js": "^2.38.4",
"@prisma/client": "^5.6.0",
"axios": "^1.6.2",
"fast-xml-parser": "^4.3.2",
"ioredis": "^5.3.2",
Expand All @@ -40,6 +44,7 @@
"@types/react": "^18.2.37",
"@types/request-ip": "^0.0.41",
"@types/ua-parser-js": "^0.7.39",
"prisma": "^5.6.0",
"typescript": "^5.2.2",
"vitest": "^0.34.5"
}
Expand Down
27 changes: 13 additions & 14 deletions apps/api/pages/api/feature/getFeatureFlags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Errors } from '@hey/data/errors';
import allowCors from '@utils/allowCors';
import { CACHE_AGE } from '@utils/constants';
import createRedisClient from '@utils/createRedisClient';
import createSupabaseClient from '@utils/createSupabaseClient';
import prisma from '@utils/prisma';
import type { NextApiRequest, NextApiResponse } from 'next';

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
Expand All @@ -23,19 +23,18 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
.json({ success: true, cached: true, features: JSON.parse(cache) });
}

const client = createSupabaseClient();
const { data, error } = await client
.from('profile-features')
.select('profile_id, enabled, features!inner(key, enabled)')
.eq('features.enabled', true)
.eq('profile_id', id)
.eq('enabled', true);

if (error) {
throw error;
}

const features = data.map((feature: any) => feature.features?.key);
const data = await prisma.profileFeature.findMany({
where: {
profileId: id as string,
enabled: true,
feature: { enabled: true }
},
select: {
feature: { select: { key: true } }
}
});

const features = data.map((feature: any) => feature.feature?.key);
await redis.set(`features:${id}`, JSON.stringify(features));

return res
Expand Down
13 changes: 5 additions & 8 deletions apps/api/pages/api/feature/getVerified.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import allowCors from '@utils/allowCors';
import { CACHE_AGE } from '@utils/constants';
import createRedisClient from '@utils/createRedisClient';
import createSupabaseClient from '@utils/createSupabaseClient';
import prisma from '@utils/prisma';
import type { NextApiRequest, NextApiResponse } from 'next';

const handler = async (_req: NextApiRequest, res: NextApiResponse) => {
Expand All @@ -16,14 +16,11 @@ const handler = async (_req: NextApiRequest, res: NextApiResponse) => {
.json({ success: true, cached: true, result: JSON.parse(cache) });
}

const client = createSupabaseClient();
const { data, error } = await client.from('verified').select('*');
const data = await prisma.verified.findMany({
select: { id: true }
});

if (error) {
throw error;
}

const ids = data.map((item) => item.id);
const ids = data.map((item: any) => item.id);
await redis.set('verified', JSON.stringify(ids));

return res
Expand Down
23 changes: 17 additions & 6 deletions apps/api/pages/api/group/featuredGroups.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,26 @@
import allowCors from '@utils/allowCors';
import { CACHE_AGE } from '@utils/constants';
import createSupabaseClient from '@utils/createSupabaseClient';
import createRedisClient from '@utils/createRedisClient';
import prisma from '@utils/prisma';
import type { NextApiRequest, NextApiResponse } from 'next';

const handler = async (_req: NextApiRequest, res: NextApiResponse) => {
try {
const client = createSupabaseClient();
const { data } = await client
.from('groups')
.select('*')
.eq('featured', true);
const redis = createRedisClient();
const cache = await redis.get('featured-groups');

if (cache) {
return res
.status(200)
.setHeader('Cache-Control', CACHE_AGE)
.json({ success: true, cached: true, result: JSON.parse(cache) });
}

const data = await prisma.group.findMany({
where: { featured: true },
orderBy: { createdAt: 'desc' }
});
await redis.set('featured-groups', JSON.stringify(data));

return res
.status(200)
Expand Down
23 changes: 16 additions & 7 deletions apps/api/pages/api/group/getGroup.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { Errors } from '@hey/data/errors';
import allowCors from '@utils/allowCors';
import { CACHE_AGE } from '@utils/constants';
import createSupabaseClient from '@utils/createSupabaseClient';
import createRedisClient from '@utils/createRedisClient';
import prisma from '@utils/prisma';
import type { NextApiRequest, NextApiResponse } from 'next';

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
Expand All @@ -12,12 +13,20 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
}

try {
const client = createSupabaseClient();
const { data } = await client
.from('groups')
.select('*')
.eq('slug', slug)
.single();
const redis = createRedisClient();
const cache = await redis.get(`group:${slug}`);

if (cache) {
return res
.status(200)
.setHeader('Cache-Control', CACHE_AGE)
.json({ success: true, cached: true, result: JSON.parse(cache) });
}

const data = await prisma.group.findUnique({
where: { slug: slug as string }
});
await redis.set(`group:${slug}`, JSON.stringify(data));

return res
.status(200)
Expand Down
15 changes: 4 additions & 11 deletions apps/api/pages/api/internal/feature/getAllFeatureFlags.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,13 @@
import allowCors from '@utils/allowCors';
import { CACHE_AGE } from '@utils/constants';
import createSupabaseClient from '@utils/createSupabaseClient';
import prisma from '@utils/prisma';
import type { NextApiRequest, NextApiResponse } from 'next';

const handler = async (_req: NextApiRequest, res: NextApiResponse) => {
try {
const client = createSupabaseClient();

const { data, error } = await client
.from('features')
.select('*')
.order('priority', { ascending: false });

if (error) {
throw error;
}
const data = await prisma.feature.findMany({
orderBy: { priority: 'desc' }
});

return res
.status(200)
Expand Down
Loading

3 comments on commit 48df9c6

@vercel
Copy link

@vercel vercel bot commented on 48df9c6 Nov 19, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

prerender – ./apps/prerender

prerender-git-main-heyxyz.vercel.app
prerender-heyxyz.vercel.app
prerender.hey.xyz

@vercel
Copy link

@vercel vercel bot commented on 48df9c6 Nov 19, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

api – ./apps/api

hey-api.vercel.app
api-git-main-heyxyz.vercel.app
api-heyxyz.vercel.app
api.hey.xyz

@vercel
Copy link

@vercel vercel bot commented on 48df9c6 Nov 19, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

web – ./apps/web

web-git-main-heyxyz.vercel.app
web-heyxyz.vercel.app
heyxyz.vercel.app
hey.xyz

Please sign in to comment.