Skip to content

Commit

Permalink
feat: initialises prisma orm (#124)
Browse files Browse the repository at this point in the history
* feat: initialises prisma orm

* chore: specifies prisma schema path
  • Loading branch information
ixahmedxi committed Jul 1, 2023
1 parent db95ce9 commit 8ccfe76
Show file tree
Hide file tree
Showing 16 changed files with 376 additions and 500 deletions.
1 change: 1 addition & 0 deletions apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
},
"dependencies": {
"@noodle/api": "workspace:^",
"@noodle/db": "workspace:^",
"@noodle/ui": "workspace:^",
"@tanstack/react-query": "^4.29.19",
"@trpc/client": "^10.33.0",
Expand Down
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,5 +59,8 @@
"patchedDependencies": {
"@types/[email protected]": "patches/@[email protected]"
}
},
"prisma": {
"schema": "packages/db/prisma/schema.prisma"
}
}
4 changes: 3 additions & 1 deletion packages/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@noodle/db": "workspace:^",
"@trpc/next": "^10.33.0",
"@trpc/server": "^10.33.0",
"superjson": "^1.12.4",
Expand All @@ -43,6 +44,7 @@
"@vitest/coverage-v8": "^0.32.2",
"eslint-config-noodle": "workspace:^",
"vite": "^4.3.9",
"vitest": "^0.32.2"
"vitest": "^0.32.2",
"vitest-mock-extended": "^1.1.3"
}
}
2 changes: 2 additions & 0 deletions packages/api/src/root.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { greetingRouter } from './routers/greeting';
import { userRouter } from './routers/user';
import { createRouter } from './setup/trpc';

export const appRouter = createRouter({
greeting: greetingRouter,
user: userRouter,
});

export type AppRouter = typeof appRouter;
9 changes: 9 additions & 0 deletions packages/api/src/routers/user/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { createRouter, publicProcedure } from '../../setup/trpc';

export const userRouter = createRouter({
find: createRouter({
all: publicProcedure.query(async ({ ctx }) => {
return await ctx.prisma.user.findMany();
}),
}),
});
36 changes: 36 additions & 0 deletions packages/api/src/routers/user/user.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { type User } from '@noodle/db';

import { userRouter } from '.';
import { prismaMock } from '../../../vitest.setup';
import { createInnerContext } from '../../setup/context';

describe('User router', () => {
let caller: ReturnType<typeof userRouter.createCaller>;

beforeEach(() => {
caller = userRouter.createCaller(createInnerContext({}));
});

it('should return all users', async () => {
const users: User[] = [
{
id: '1',
name: 'John Doe',
email: '[email protected]',
emailVerified: new Date(),
image: 'https://example.com/johndoe.png',
},
{
id: '2',
name: 'Jane Doe',
email: '[email protected]',
emailVerified: new Date(),
image: 'https://example.com/janedoe.png',
},
];

prismaMock.user.findMany.mockResolvedValue(users);

await expect(caller.find.all()).resolves.toEqual(users);
});
});
4 changes: 3 additions & 1 deletion packages/api/src/setup/context.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import { type CreateNextContextOptions } from '@trpc/server/adapters/next';

import { prisma } from '@noodle/db';

// TODO: add session as an option to provide to context type
// eslint-disable-next-line
type ContextOptions = {};

export const createInnerContext = (opts: ContextOptions) => {
// TODO: create the db connection here and pass it in the return object
return {
...opts,
prisma,
};
};

Expand Down
16 changes: 16 additions & 0 deletions packages/api/vitest.setup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import type { PrismaClient } from '@noodle/db';
import type { DeepMockProxy } from 'vitest-mock-extended';
import { mockDeep, mockReset } from 'vitest-mock-extended';

import { prisma } from '@noodle/db';

vi.mock('@noodle/db', () => ({
__esModule: true,
prisma: mockDeep<PrismaClient>(),
}));

beforeEach(() => {
mockReset(prismaMock);
});

export const prismaMock = prisma as unknown as DeepMockProxy<PrismaClient>;
28 changes: 28 additions & 0 deletions packages/db/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"name": "@noodle/db",
"version": "0.1.0",
"private": true,
"description": "Noodle's prisma database package",
"license": "AGPL-3.0",
"author": "Ahmed Elsakaan",
"type": "module",
"main": "./dist/index.js",
"scripts": {
"db:push": "prisma db push",
"dev": "tsc -p tsconfig.build.json --watch",
"lint": "eslint . --max-warnings 0 --report-unused-disable-directives",
"lint:fix": "pnpm run lint --fix",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@prisma/client": "^4.16.2"
},
"devDependencies": {
"@noodle/tsconfig": "workspace:^",
"eslint-config-noodle": "workspace:^",
"prisma": "^4.16.2"
},
"volta": {
"extends": "../../package.json"
}
}
52 changes: 52 additions & 0 deletions packages/db/prisma/schema.prisma
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
generator client {
provider = "prisma-client-js"
previewFeatures = ["jsonProtocol"]
}

datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
directUrl = env("DIRECT_URL")
}

model Account {
id String @id @default(cuid())
userId String
type String
provider String
providerAccountId String
refresh_token String? @db.Text
access_token String? @db.Text
expires_at Int?
token_type String?
scope String?
id_token String? @db.Text
session_state String?
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@unique([provider, providerAccountId])
}

model Session {
id String @id @default(cuid())
sessionToken String @unique
userId String
expires DateTime
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
}

model User {
id String @id @default(cuid())
name String?
email String? @unique
emailVerified DateTime?
image String?
accounts Account[]
sessions Session[]
}

model VerificationToken {
identifier String
token String @unique
expires DateTime
@@unique([identifier, token])
}
13 changes: 13 additions & 0 deletions packages/db/project.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"sourceRoot": "packages/db",
"targets": {
"build": {
"executor": "nx:run-commands",
"options": {
"commands": ["prisma generate", "tsc -p tsconfig.build.json"],
"parallel": false,
"cwd": "packages/db"
}
}
}
}
16 changes: 16 additions & 0 deletions packages/db/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { PrismaClient } from '@prisma/client';

export * from '@prisma/client';

const globalForPrisma = globalThis as { prisma?: PrismaClient };

export const prisma =
globalForPrisma.prisma ??
new PrismaClient({
log:
process.env['NODE_ENV'] === 'development'
? ['query', 'error', 'warn']
: ['error'],
});

if (process.env['NODE_ENV'] !== 'production') globalForPrisma.prisma = prisma;
10 changes: 10 additions & 0 deletions packages/db/tsconfig.build.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"noEmit": false,
"outDir": "dist",
"declarationMap": true
},
"include": ["src/**/*.ts"],
"exclude": ["src/**/*.test.ts", "src/**/*.spec.ts"]
}
9 changes: 9 additions & 0 deletions packages/db/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"extends": "@noodle/tsconfig/base.json",
"compilerOptions": {
"noEmit": true,
"types": ["vitest/globals"]
},
"exclude": ["./coverage/**/*"],
"include": ["**/*.ts"]
}
3 changes: 2 additions & 1 deletion packages/test-utils/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
{
"extends": "@noodle/tsconfig/react.json",
"compilerOptions": {
"noEmit": true
"noEmit": true,
"types": ["vitest/globals"]
},
"include": ["**/*.ts", "**/*.tsx"]
}
Loading

0 comments on commit 8ccfe76

Please sign in to comment.