Is this a proper way to type a table and column?
I want to make certain crud action reusable in my codebase. Is this the proper way to type a SQLite table and column?
Load activeItem function
import { type InferSelectModel } from 'drizzle-orm';
import type { SQLiteColumn, SQLiteTable} from 'drizzle-orm/sqlite-core';
export async function loadActiveItems<T extends SQLiteTable>(
table: T,
orderBy: keyof InferSelectModel<T> = 'name'
) {
const activeColumn = table._.columns['active'];
const orderByColumn = table._.columns[orderBy];
return db.select().from(table).where(eq(activeColumn, true)).orderBy(orderByColumn);
}
import { type InferSelectModel } from 'drizzle-orm';
import type { SQLiteColumn, SQLiteTable} from 'drizzle-orm/sqlite-core';
export async function loadActiveItems<T extends SQLiteTable>(
table: T,
orderBy: keyof InferSelectModel<T> = 'name'
) {
const activeColumn = table._.columns['active'];
const orderByColumn = table._.columns[orderBy];
return db.select().from(table).where(eq(activeColumn, true)).orderBy(orderByColumn);
}
1 Reply
Delete item function
export async function deleteItem<T extends SQLiteTable>(
request: Request,
table: T,
entityName: string
) {
const formData = await request.formData();
const id = Number(formData.get('id'));
if (!id) {
return fail(400, { success: false, message: 'Invalid request' });
}
const idColumn = table._.columns['id'];
const activeColumn = table._.columns['active'];
try {
const [existing] = await db
.select()
.from(table)
.where(and(eq(idColumn, id), eq(activeColumn, true)));
if (!existing) {
return fail(404, { success: false, message: `${entityName} not found` });
}
await db
.update(table)
.set({ active: sql`false` } as Partial<T['$inferInsert']>)
.where(eq(idColumn, id));
return { success: true, message: `${entityName} deleted successfully` };
} catch (error) {
console.error(error);
return fail(500, { success: false, message: `Unable to delete ${entityName}` });
}
}
export async function deleteItem<T extends SQLiteTable>(
request: Request,
table: T,
entityName: string
) {
const formData = await request.formData();
const id = Number(formData.get('id'));
if (!id) {
return fail(400, { success: false, message: 'Invalid request' });
}
const idColumn = table._.columns['id'];
const activeColumn = table._.columns['active'];
try {
const [existing] = await db
.select()
.from(table)
.where(and(eq(idColumn, id), eq(activeColumn, true)));
if (!existing) {
return fail(404, { success: false, message: `${entityName} not found` });
}
await db
.update(table)
.set({ active: sql`false` } as Partial<T['$inferInsert']>)
.where(eq(idColumn, id));
return { success: true, message: `${entityName} deleted successfully` };
} catch (error) {
console.error(error);
return fail(500, { success: false, message: `Unable to delete ${entityName}` });
}
}