Skip to content

Commit

Permalink
feat: use internal package for Database
Browse files Browse the repository at this point in the history
  • Loading branch information
flemzord committed Apr 28, 2024
1 parent 421b5da commit 6c4234f
Show file tree
Hide file tree
Showing 26 changed files with 225 additions and 76 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/main.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ jobs:
- name: Install
uses: ./.github/actions/install
- name: Migrate Database
run: pnpm run -C ./apps/web db:migrate
run: pnpm run db:migrate
env:
DATABASE_URL: ${{ secrets.DATABASE_URL }}
- name: Build
Expand Down
10 changes: 3 additions & 7 deletions apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,16 @@
"scripts": {
"build": "nuxi build",
"dev": "nuxi dev",
"generate": "nuxt generate && pnpm run db:generate",
"generate": "nuxt generate",
"preview": "npm run build && wrangler pages dev",
"postinstall": "nuxt prepare",
"deploy:production": "npm run build && wrangler pages deploy --env=production",
"cf-typegen": "wrangler types",
"db:generate": "drizzle-kit generate:pg",
"db:migrate": "tsx server/database/migrate.ts"
"cf-typegen": "wrangler types"
},
"dependencies": {
"@getlicensed/db": "workspace:^",
"@headlessui/vue": "^1.7.20",
"@heroicons/vue": "^2.1.3",
"@neondatabase/serverless": "^0.9.1",
"@nuxt/ui": "^2.15.2",
"@nuxthub/core": "^0.5.11",
"@nuxtjs/tailwindcss": "^6.12.0",
Expand All @@ -39,9 +37,7 @@
"devDependencies": {
"@cloudflare/workers-types": "^4.20240419.0",
"dotenv": "^16.4.5",
"drizzle-kit": "^0.20.17",
"nitro-cloudflare-dev": "^0.1.4",
"pg": "^8.11.5",
"ts-node": "^10.9.2",
"tsx": "^4.7.2",
"typescript": "^5.4.5",
Expand Down
7 changes: 4 additions & 3 deletions apps/web/server/api/auth/github.get.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { schema } from '@getlicensed/db';
import { eq } from 'drizzle-orm';

async function getUserByEmail(email: string) {
return useDB()
.select()
.from(tables.users)
.where(eq(tables.users.email, email))
.from(schema.users)
.where(eq(schema.users.email, email))
.limit(1);
}

Expand All @@ -14,7 +15,7 @@ async function createUser(param: {
email: string;
}) {
return useDB()
.insert(tables.users)
.insert(schema.users)
.values({
name: param.name,
email: param.email,
Expand Down
15 changes: 0 additions & 15 deletions apps/web/server/database/migrate.ts

This file was deleted.

7 changes: 0 additions & 7 deletions apps/web/server/plugins/migrations.ts

This file was deleted.

6 changes: 4 additions & 2 deletions apps/web/server/trpc/context.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { schema } from '@getlicensed/db';
/* eslint-disable @typescript-eslint/no-unused-vars */
import type { inferAsyncReturnType } from '@trpc/server';
import { eq } from 'drizzle-orm';
import type { H3Event } from 'h3';

export type Context = inferAsyncReturnType<typeof createContext>;
Expand All @@ -8,9 +10,9 @@ export async function createContext(event: H3Event) {
const session = await requireUserSession(event);
const user = await useDB()
.select()
.from(tables.users)
.from(schema.users)
// @ts-ignore
.where(eq(tables.users.githubId, session.user.id))
.where(eq(schema.users.githubId, session.user.id))
.limit(1);

return {
Expand Down
11 changes: 6 additions & 5 deletions apps/web/server/trpc/routers/tokens.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { desc } from 'drizzle-orm';
import { schema } from '@getlicensed/db';
import { desc, eq } from 'drizzle-orm';
import { generateRandomString } from 'ts-randomstring/lib';
import { z } from 'zod';
import { protectedProcedure, t } from '~/server/trpc/trpc';
Expand All @@ -11,12 +12,12 @@ export const tokensRouter = t.router({
all: protectedProcedure.query(({ ctx }) => {
return useDB()
.select()
.from(tables.tokens)
.where(eq(tables.tokens.userId, ctx.userId))
.orderBy(desc(tables.tokens.createdAt));
.from(schema.tokens)
.where(eq(schema.tokens.userId, ctx.userId))
.orderBy(desc(schema.tokens.createdAt));
}),
add: protectedProcedure.input(AddShape).mutation(({ input, ctx }) => {
return useDB().insert(tables.tokens).values({
return useDB().insert(schema.tokens).values({
name: input.name,
userId: ctx.userId,
token: generateRandomString(),
Expand Down
8 changes: 4 additions & 4 deletions apps/web/server/utils/db.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { queryClient } from '~/server/database/db';
import * as schema from '~/server/database/schema';

export { sql, eq, and, or } from 'drizzle-orm';
import { queryClient } from '@getlicensed/db';
import * as schema from '@getlicensed/db';

export const tables = schema;

export function useDB() {
return queryClient;
}

export * from '@getlicensed/db';
5 changes: 3 additions & 2 deletions apps/web/drizzle.config.ts → internal/db/drizzle.config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { Config } from 'drizzle-kit';

export default {
schema: './server/database/schema.ts',
out: './server/database/migrations',
verbose: true,
schema: './src/schema.ts',
out: './src/migrations',
} satisfies Config;
28 changes: 28 additions & 0 deletions internal/db/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"name": "@getlicensed/db",
"version": "0.0.0",
"description": "",
"main": "./src/index.ts",
"types": "./src/index.ts",
"keywords": [],
"author": "Maxence Maireaux",
"license": "AGPL-3.0",
"scripts": {
"studio": "dotenv -e .env drizzle-kit studio ",
"db:generate": "drizzle-kit generate:pg",
"db:migrate": "tsx src/migrate.ts"
},
"devDependencies": {
"@types/node": "^20.12.7",
"dotenv-cli": "^7.4.1",
"drizzle-kit": "^0.20.17",
"drizzle-orm": "^0.30.9",
"pg": "^8.11.5",
"ts-node": "^10.9.2",
"tsx": "^4.7.2",
"typescript": "^5.4.5"
},
"dependencies": {
"@neondatabase/serverless": "^0.9.1"
}
}
31 changes: 18 additions & 13 deletions apps/web/server/database/db.ts → internal/db/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@ import { migrate as migrateNode } from 'drizzle-orm/node-postgres/migrator';
// @ts-ignore
import pg from 'pg';

export * from './types';
import * as schema from './schema';
export { schema };
export * from 'drizzle-orm';

const DATABASE_URL = process.env.DATABASE_URL;

if (!DATABASE_URL) {
Expand All @@ -24,23 +29,23 @@ export async function dbMigrate() {
if (process.env.ENVIRONMENT === 'local')
// @ts-ignore
await migrateNode(queryClient, {
migrationsFolder: 'server/database/migrations',
migrationsFolder: 'src/migrations',
});
// @ts-ignore
else
await migrateHttp(queryClient, {
migrationsFolder: 'server/database/migrations',
migrationsFolder: 'src/migrations',
});
}

// console.log('DATABASE_URL', DATABASE_URL);
// console.log('ENVIRONMENT', process.env.ENVIRONMENT);
// if (process.env.ENVIRONMENT === 'local') {
// console.log('Running in local environment');
// neonConfig.pipelineConnect = false;
// neonConfig.pipelineTLS = false;
// neonConfig.useSecureWebSocket = false;
// neonConfig.wsProxy = () => "127.0.0.1:5433";
// }
//
// export const queryClient = neon(DATABASE_URL);
export const runMigrate = async () => {
console.log('Running database migrations...');

await dbMigrate()
.then(() => {
console.log('Database migrations done');
})
.catch((err) => {
console.error('Database migrations failed', err);
});
};
9 changes: 9 additions & 0 deletions internal/db/src/migrate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { runMigrate } from './index';

runMigrate()
.then(() => {
console.log('Database migrations fully done');
})
.catch((err) => {
console.error('Database migrations failed', err);
});
File renamed without changes.
5 changes: 5 additions & 0 deletions internal/db/src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import type { InferSelectModel } from 'drizzle-orm';
import type * as schema from './schema';

export type Users = InferSelectModel<typeof schema.users>;
export type Tokens = InferSelectModel<typeof schema.tokens>;
7 changes: 7 additions & 0 deletions internal/db/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"$schema": "https://json.schemastore.org/tsconfig",
"exclude": ["dist"],
"compilerOptions": {
"outDir": "dist"
}
}
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@
"private": true,
"license": "AGPL-3.0",
"version": "0.0.0",
"workspaces": ["apps/*", "packages/*"],
"workspaces": ["apps/*", "packages/*", "internal/*"],
"author": "Maxence Maireaux",
"scripts": {
"prepare": "husky",
"build": "dotenv -e .env -- turbo build",
"dev": "dotenv -e .env -- turbo dev",
"dev": "dotenv -e .env -- pnpm run db:migrate && dotenv -e .env -- turbo dev",
"db:migrate": "dotenv -e .env -- turbo db:migrate --filter './internal/db'",
"fmt": "biome format . --write && biome check . --apply",
"bump-versions": "pnpm changeset version && pnpm install"
},
Expand Down
Loading

0 comments on commit 6c4234f

Please sign in to comment.