Skip to content

Commit

Permalink
feat: make all env optional (#94)
Browse files Browse the repository at this point in the history
* feat: make all env optional

* fix: fixing typecheck
  • Loading branch information
invisal committed Jun 11, 2024
1 parent 15e4c56 commit e236b30
Show file tree
Hide file tree
Showing 16 changed files with 46 additions and 26 deletions.
2 changes: 1 addition & 1 deletion studio/drizzle.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export default {
out: "./drizzle",
driver: "turso",
dbCredentials: {
url: env.DATABASE_URL,
url: env.DATABASE_URL ?? "",
authToken: env.DATABASE_AUTH_TOKEN,
},
} satisfies Config;
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { HttpStatus } from "@studio/constants/http-status";
import { db } from "@studio/db";
import { get_database } from "@studio/db";
import { database_role, database_user_role } from "@studio/db/schema-database";
import { user as userTable } from "@studio/db/schema-user";
import { ApiError } from "@studio/lib/api-error";
Expand All @@ -12,6 +12,7 @@ const handleAssignUser: DatabaseOperationHandler<
RequestDatabaseAssignUser
> = async ({ database: databaseInfo, body, user, permission }) => {
const { roleId, userId } = body;
const db = get_database();

// Validate if user input all fields
if (!userId || !roleId)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { HttpStatus } from "@studio/constants/http-status";
import { db } from "@studio/db";
import { get_database } from "@studio/db";
import { database_role, database_user_role } from "@studio/db/schema-database";
import { ApiError } from "@studio/lib/api-error";
import { RequestDatabaseDeleteUser } from "@studio/lib/api/api-database-request";
Expand All @@ -11,6 +11,7 @@ const handleDeleteUser: DatabaseOperationHandler<
RequestDatabaseDeleteUser
> = async ({ database: databaseInfo, body, user, permission }) => {
const { userId } = body;
const db = get_database();

// Validate if user input all fields
if (!userId)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { db } from "@studio/db";
import { get_database } from "@studio/db";
import { database_role } from "@studio/db/schema-database";
import { DatabaseOperationHandler } from "@studio/lib/with-database-ops";
import { eq } from "drizzle-orm";
import { NextResponse } from "next/server";

const handleRoleList: DatabaseOperationHandler = async ({ database }) => {
const db = get_database();

const roles = await db.query.database_role.findMany({
where: eq(database_role.databaseId, database.id),
});
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { db } from "@studio/db";
import { get_database } from "@studio/db";
import { user } from "@studio/db/schema";
import { database_role, database_user_role } from "@studio/db/schema-database";
import { DatabaseOperationHandler } from "@studio/lib/with-database-ops";
Expand All @@ -11,6 +11,7 @@ const handleUserList: DatabaseOperationHandler = async ({
}) => {
const assigned_user = alias(user, "assigned_user");

const db = get_database();
const users = await db
.select({
id: user.id,
Expand Down
4 changes: 3 additions & 1 deletion studio/src/app/api/database/[database_id]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ import withDatabaseOperation from "@studio/lib/with-database-ops";
import { NextResponse } from "next/server";
import { database } from "@studio/db/schema";
import { eq } from "drizzle-orm";
import { db } from "@studio/db";
import { encrypt } from "@studio/lib/encryption-edge";
import { env } from "@studio/env";
import { SavedConnectionItemConfig } from "@studio/app/connect/saved-connection-storage";
import { get_database } from "@studio/db";

export const runtime = "edge";

Expand Down Expand Up @@ -40,6 +40,7 @@ export const GET = withDatabaseOperation(async ({ database: databaseInfo }) => {
export const DELETE = withDatabaseOperation(
async ({ database: databaseInfo, user }) => {
const isOriginalOwner = databaseInfo.userId === user.id;
const db = get_database();

if (!isOriginalOwner) {
return NextResponse.json({ error: "Unauthorization" }, { status: 500 });
Expand All @@ -59,6 +60,7 @@ export const DELETE = withDatabaseOperation(
export const PUT = withDatabaseOperation(
async ({ database: databaseInfo, body, user }) => {
const parsed = databaseSchema.safeParse(body);
const db = get_database();

if (!parsed.success) {
return NextResponse.json(
Expand Down
3 changes: 2 additions & 1 deletion studio/src/app/api/database/route.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import zod from "zod";
import withUser from "@studio/lib/with-user";
import { db } from "@studio/db";
import { generateId } from "lucia";
import { database, database_role, database_user_role } from "@studio/db/schema";
import { NextResponse } from "next/server";
import { env } from "@studio/env";
import { encrypt } from "@studio/lib/encryption-edge";
import { SavedConnectionItem } from "@studio/app/connect/saved-connection-storage";
import { get_database } from "@studio/db";

export const runtime = "edge";

Expand Down Expand Up @@ -43,6 +43,7 @@ export const POST = withUser(async ({ user, req }) => {
const now = Date.now();

try {
const db = get_database();
await db.batch([
db.insert(database).values({
id: databaseId,
Expand Down
3 changes: 2 additions & 1 deletion studio/src/app/api/databases/route.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { SavedConnectionItem } from "@studio/app/connect/saved-connection-storage";
import { db } from "@studio/db";
import { get_database } from "@studio/db";
import {
database,
database_user_role,
Expand All @@ -12,6 +12,7 @@ import { NextResponse } from "next/server";
export const runtime = "edge";

export const GET = withUser(async ({ user }) => {
const db = get_database();
const dbs = await db
.select()
.from(database_user_role)
Expand Down
3 changes: 2 additions & 1 deletion studio/src/app/api/upload/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ import withUser from "@studio/lib/with-user";
import { NextResponse } from "next/server";
import { ok, err } from "@justmiracle/result";
import { R2 } from "@studio/lib/r2";
import { db } from "@studio/db";
import { user as userTable, user_file } from "@studio/db/schema";
import { eq, sql } from "drizzle-orm";
import { generateId } from "lucia";
import { ApiError } from "@studio/lib/api-error";
import { HttpStatus } from "@studio/constants/http-status";
import { env } from "@studio/env";
import { filetypeinfo } from "magic-bytes.js";
import { get_database } from "@studio/db";

export const runtime = "edge";

Expand All @@ -34,6 +34,7 @@ export const POST = withUser(async ({ req, user }) => {
});
}

const db = get_database();
const formData = await req.formData().then(ok).catch(err);

if (formData.error) {
Expand Down
3 changes: 2 additions & 1 deletion studio/src/app/client/r/page.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import "@libsqlstudio/gui/css";

import type { SavedConnectionLabel } from "@studio/app/connect/saved-connection-storage";
import { db } from "@studio/db";
import { get_database } from "@studio/db";
import { database } from "@studio/db/schema";
import { getSessionFromCookie } from "@studio/lib/auth";
import { and, eq, isNotNull } from "drizzle-orm";
Expand All @@ -22,6 +22,7 @@ export default async function SessionPage({
return <div>Something wrong</div>;
}

const db = get_database();
const databaseId = searchParams?.p;
const databaseInfo = await db.query.database.findFirst({
where: and(eq(database.id, databaseId), isNotNull(database.id)),
Expand Down
3 changes: 2 additions & 1 deletion studio/src/controllers/auth.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { db } from "@studio/db";
import { get_database } from "@studio/db";
import { user, user_oauth } from "@studio/db/schema";
import { Provider, lucia } from "@studio/lib/auth";
import { generateId } from "lucia";
Expand All @@ -13,6 +13,7 @@ interface UserAuth {
export const save = async (data: UserAuth, provider: Provider) => {
const { id, name, email } = data;
const headerStore = headers();
const db = get_database();

const existingUser = await db.query.user_oauth.findFirst({
where: (field, op) =>
Expand Down
18 changes: 13 additions & 5 deletions studio/src/db/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,17 @@ import * as schema from "./schema";
import { createClient } from "@libsql/client/web";
import { env } from "@studio/env";

export const connection = createClient({
url: env.DATABASE_URL,
authToken: env.DATABASE_AUTH_TOKEN,
});
export function get_connection() {
if (env.DATABASE_URL) {
return createClient({
url: env.DATABASE_URL,
authToken: env.DATABASE_AUTH_TOKEN,
});
}

export const db = drizzle(connection, { schema });
throw new Error("Database is not setup");
}

export function get_database() {
return drizzle(get_connection(), { schema });
}
7 changes: 3 additions & 4 deletions studio/src/db/migrate.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import "dotenv/config";

import { migrate } from "drizzle-orm/libsql/migrator";
import { db, connection } from ".";
import { get_database } from ".";

(async function () {
const db = get_database();

// This will run migrations on the database, skipping the ones already applied
await migrate(db, { migrationsFolder: "./drizzle" });

// Don't forget to close the connection, otherwise the script will hang
connection.close();
})()
.catch(console.error)
.finally(() => {
Expand Down
6 changes: 3 additions & 3 deletions studio/src/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ export const appVersion = pkg.version;

export const env = createEnv({
server: {
BASE_URL: z.string().min(1),
DATABASE_URL: z.string().min(1),
DATABASE_AUTH_TOKEN: z.string().min(1),
BASE_URL: z.string().min(1).optional(),
DATABASE_URL: z.string().min(1).optional(),
DATABASE_AUTH_TOKEN: z.string().min(1).optional(),

GITHUB_CLIENT_ID: z.string().optional(),
GITHUB_CLIENT_SECRET: z.string().optional(),
Expand Down
4 changes: 2 additions & 2 deletions studio/src/lib/auth.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Lucia } from "lucia";
import { GitHub, Google } from "arctic";
import { LibSQLAdapter } from "@lucia-auth/adapter-sqlite";
import { connection } from "@studio/db";
import { get_connection } from "@studio/db";
import { env } from "@studio/env";
import { cache } from "react";
import { cookies, headers } from "next/headers";
Expand Down Expand Up @@ -29,7 +29,7 @@ export const google = new Google(
`${env.BASE_URL}/login/google/callback`
);

const adapter = new LibSQLAdapter(connection, {
const adapter = new LibSQLAdapter(get_connection(), {
user: "user",
session: "user_session",
});
Expand Down
3 changes: 2 additions & 1 deletion studio/src/lib/with-database-ops.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ import {
import { User } from "lucia";
import withUser from "./with-user";
import { NextResponse } from "next/server";
import { db } from "@studio/db";
import { and, eq } from "drizzle-orm";
import { headers } from "next/headers";
import { get_database } from "@studio/db";

export interface DatabasePermission {
isOwner: boolean;
Expand All @@ -36,6 +36,7 @@ export default function withDatabaseOperation<T = unknown>(
return withUser<{ params: { database_id: string } }>(
async ({ user, req, params }) => {
const databaseId = params.params.database_id;
const db = get_database();

if (!databaseId) {
return NextResponse.json(
Expand Down

0 comments on commit e236b30

Please sign in to comment.