Skip to content

Commit

Permalink
feat(verity): singleton prisma client, review issues
Browse files Browse the repository at this point in the history
  • Loading branch information
marselkhisamov committed Jun 3, 2024
1 parent 450b5f6 commit 2ebc522
Show file tree
Hide file tree
Showing 15 changed files with 166 additions and 83 deletions.
8 changes: 5 additions & 3 deletions apps/web/app/api/deps/route.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { getAppDepsHandler } from '@verity/deps-api';
import { NextRequest } from 'next/server';

export async function GET(request: Request) {
return getAppDepsHandler(request);
import { getApplicationDependencies } from '@verity/deps-api';

export async function GET(request: NextRequest) {
return getApplicationDependencies(request);
}
3 changes: 1 addition & 2 deletions libs/auth/src/lib/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@ import NextAuth from 'next-auth';
import Keycloak from 'next-auth/providers/keycloak';

import { PrismaAdapter } from '@auth/prisma-adapter';
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();
import { prisma } from '@verity/prisma';

export const { handlers, signIn, signOut, auth } = NextAuth({
adapter: PrismaAdapter(prisma),
Expand Down
34 changes: 14 additions & 20 deletions libs/deps-api/src/lib/deps-api.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
import { PrismaClient } from '@prisma/client';
import { NextRequest, NextResponse } from 'next/server';

import { getQueryParams } from '@verity/utils';
import { prisma } from '@verity/prisma';

const prisma = new PrismaClient();

export const getAppDepsHandler = async (request: Request) => {
const { app, version } = getQueryParams(request);
export const getApplicationDependencies = async (request: NextRequest) => {
const app = request.nextUrl.searchParams.get('app');
const version = request.nextUrl.searchParams.get('version');

if (!app || !version) {
return new Response('app and version params are required', { status: 400 });
}

const rawAppVersion = await prisma.appVersion.findFirst({
const rawAppVersion = await prisma.version.findFirst({
where: {
appId: app,
value: version,
Expand All @@ -34,18 +33,13 @@ export const getAppDepsHandler = async (request: Request) => {
return new Response('app version not found', { status: 404 });
}

const dependencies = rawAppVersion.dependencies.reduce((acc, dep) => {
const appId = dep.dependencyAppVersion?.appId;

if (!appId) {
return acc;
} else {
return {
...acc,
[appId]: dep.dependencyAppVersion?.value,
};
}
}, {});
const dependencies = rawAppVersion.dependencies.reduce(
(acc, dep) => ({
...acc,
[dep.dependencyAppVersion.appId]: dep.dependencyAppVersion.value,
}),
{},
);

return new Response(JSON.stringify(dependencies), { status: 200 });
return NextResponse.json(dependencies);
};
18 changes: 18 additions & 0 deletions libs/prisma/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"extends": ["plugin:@nx/react", "../../.eslintrc.json"],
"ignorePatterns": ["!**/*"],
"overrides": [
{
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
"rules": {}
},
{
"files": ["*.ts", "*.tsx"],
"rules": {}
},
{
"files": ["*.js", "*.jsx"],
"rules": {}
}
]
}
7 changes: 7 additions & 0 deletions libs/prisma/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# prisma

This library was generated with [Nx](https://nx.dev).

## Running unit tests

Run `nx test prisma` to execute the unit tests via [Jest](https://jestjs.io).
9 changes: 9 additions & 0 deletions libs/prisma/project.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"name": "prisma",
"$schema": "../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "libs/prisma/src",
"projectType": "library",
"tags": [],
"// targets": "to see all targets run: nx show project prisma --web",
"targets": {}
}
1 change: 1 addition & 0 deletions libs/prisma/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default as prisma } from './lib/prisma-client';
15 changes: 15 additions & 0 deletions libs/prisma/src/lib/prisma-client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { PrismaClient } from '@prisma/client';

const prismaClientSingleton = () => {
return new PrismaClient();
};

declare const globalThis: {
prismaGlobal: ReturnType<typeof prismaClientSingleton>;
} & typeof global;

const prisma = globalThis.prismaGlobal ?? prismaClientSingleton();

export default prisma;

if (process.env.NODE_ENV !== 'production') globalThis.prismaGlobal = prisma;
17 changes: 17 additions & 0 deletions libs/prisma/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"compilerOptions": {
"jsx": "react-jsx",
"allowJs": false,
"esModuleInterop": false,
"allowSyntheticDefaultImports": true,
"strict": true
},
"files": [],
"include": [],
"references": [
{
"path": "./tsconfig.lib.json"
}
],
"extends": "../../tsconfig.base.json"
}
25 changes: 25 additions & 0 deletions libs/prisma/tsconfig.lib.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../dist/out-tsc",
"types": [
"node",
"@nx/react/typings/cssmodule.d.ts",
"@nx/react/typings/image.d.ts",
"next",
"@nx/next/typings/image.d.ts"
]
},
"exclude": [
"jest.config.ts",
"src/**/*.spec.ts",
"src/**/*.test.ts",
"src/**/*.spec.tsx",
"src/**/*.test.tsx",
"src/**/*.spec.js",
"src/**/*.test.js",
"src/**/*.spec.jsx",
"src/**/*.test.jsx"
],
"include": ["src/**/*.js", "src/**/*.jsx", "src/**/*.ts", "src/**/*.tsx"]
}
5 changes: 0 additions & 5 deletions libs/utils/src/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,3 @@ import { twMerge } from 'tailwind-merge';
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}

export function getQueryParams(request: Request): Record<string, string> {
const url = new URL(request.url);
return Object.fromEntries(url.searchParams.entries());
}
46 changes: 0 additions & 46 deletions prisma/migrations/20240603122534_deps_tables/migration.sql

This file was deleted.

46 changes: 46 additions & 0 deletions prisma/migrations/20240603152308_deps_tables/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
-- CreateTable
CREATE TABLE "App" (
"id" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

-- CreateTable
CREATE TABLE "Version" (
"id" SERIAL NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"value" TEXT NOT NULL,
"builtAt" TIMESTAMP(3),
"appId" TEXT NOT NULL,

CONSTRAINT "Version_pkey" PRIMARY KEY ("appId","value")
);

-- CreateTable
CREATE TABLE "Dependency" (
"id" SERIAL NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"dependantAppVersionId" INTEGER NOT NULL,
"dependencyAppVersionId" INTEGER NOT NULL,

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

-- CreateIndex
CREATE UNIQUE INDEX "App_id_key" ON "App"("id");

-- CreateIndex
CREATE UNIQUE INDEX "Version_id_key" ON "Version"("id");

-- CreateIndex
CREATE UNIQUE INDEX "Dependency_id_key" ON "Dependency"("id");

-- AddForeignKey
ALTER TABLE "Version" ADD CONSTRAINT "Version_appId_fkey" FOREIGN KEY ("appId") REFERENCES "App"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "Dependency" ADD CONSTRAINT "Dependency_dependantAppVersionId_fkey" FOREIGN KEY ("dependantAppVersionId") REFERENCES "Version"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "Dependency" ADD CONSTRAINT "Dependency_dependencyAppVersionId_fkey" FOREIGN KEY ("dependencyAppVersionId") REFERENCES "Version"("id") ON DELETE CASCADE ON UPDATE CASCADE;
14 changes: 7 additions & 7 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -80,29 +80,29 @@ model Authenticator {
model App {
id String @id @unique
createdAt DateTime @default(now())
versions AppVersion[]
versions Version[]
}

model AppVersion {
model Version {
id Int @unique @default(autoincrement())
createdAt DateTime @default(now())
value String
builtAt DateTime?
appId String
dependencies AppVersionDependency[] @relation("AppVersionDependency")
dependsOn AppVersionDependency[] @relation("AppVersionDependsOn")
dependencies Dependency[] @relation("AppVersionDependency")
dependsOn Dependency[] @relation("AppVersionDependsOn")
app App @relation(fields: [appId], references: [id])
@@id([appId, value])
}

model AppVersionDependency {
model Dependency {
id Int @id @unique @default(autoincrement())
createdAt DateTime @default(now())
dependantAppVersionId Int
dependencyAppVersionId Int
dependantAppVersion AppVersion? @relation("AppVersionDependency", fields: [dependantAppVersionId], references: [id])
dependencyAppVersion AppVersion? @relation("AppVersionDependsOn", fields: [dependencyAppVersionId], references: [id])
dependantAppVersion Version @relation("AppVersionDependency", fields: [dependantAppVersionId], references: [id], onDelete: Cascade)
dependencyAppVersion Version @relation("AppVersionDependsOn", fields: [dependencyAppVersionId], references: [id], onDelete: Cascade)
}
1 change: 1 addition & 0 deletions tsconfig.base.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"@verity/auth": ["libs/auth/src/index.ts"],
"@verity/auth/server": ["libs/auth/src/server.ts"],
"@verity/deps-api": ["libs/deps-api/src/server.ts"],
"@verity/prisma": ["libs/prisma/src/index.ts"],
"@verity/ui": ["libs/ui/src/index.ts"],
"@verity/ui/*": ["libs/ui/src/lib/*"],
"@verity/ui/server": ["libs/ui/src/server.ts"],
Expand Down

0 comments on commit 2ebc522

Please sign in to comment.