feat: init drizzle implementation for backend (express) and frontend (vite-react)
This commit is contained in:
parent
fc3a21263a
commit
aca6a4da98
17 changed files with 1608 additions and 35 deletions
|
|
@ -1,6 +1,17 @@
|
|||
import { drizzle } from "drizzle-orm/postgres-js";
|
||||
import postgres from "postgres";
|
||||
import dotenv from "dotenv";
|
||||
dotenv.config({ path: ".env" });
|
||||
|
||||
const client = postgres(process.env.DATABASE_URL!);
|
||||
let db_url = process.env.DATABASE_URL!;
|
||||
try {
|
||||
db_url = decodeURI(db_url);
|
||||
} catch (e) {
|
||||
console.warn("Failed to decode DATABASE_URL, using as is.");
|
||||
}
|
||||
|
||||
console.log("Connecting to database URL:", db_url);
|
||||
|
||||
const client = postgres(db_url!);
|
||||
|
||||
export const db = drizzle(client);
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import { count, desc } from "drizzle-orm";
|
||||
import { db } from "../database";
|
||||
import { InsertProduct, products } from "../schema/products";
|
||||
|
||||
|
|
@ -5,6 +6,28 @@ export async function createProduct(data: InsertProduct) {
|
|||
await db.insert(products).values(data);
|
||||
}
|
||||
|
||||
export async function getProducts() {
|
||||
return db.select().from(products);
|
||||
export async function getProducts(page: number = 1, limit: number = 10) {
|
||||
const offset = (page - 1) * limit;
|
||||
|
||||
const totalCountResult = await db.select({ count: count() }).from(products);
|
||||
const totalCount = totalCountResult[0].count;
|
||||
|
||||
const productsList = await db
|
||||
.select()
|
||||
.from(products)
|
||||
.orderBy(desc(products.createdAt))
|
||||
.limit(limit)
|
||||
.offset(offset);
|
||||
|
||||
return {
|
||||
data: productsList,
|
||||
pagination: {
|
||||
page,
|
||||
limit,
|
||||
totalCount,
|
||||
totalPages: Math.ceil(totalCount / limit),
|
||||
hasNextPage: page < Math.ceil(totalCount / limit),
|
||||
hasPreviousPage: page > 1,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,20 @@
|
|||
import { db } from "../database";
|
||||
import { InsertUser, user } from "../schema/users";
|
||||
import { InsertUser, users } from "../schema/users";
|
||||
import { eq } from "drizzle-orm";
|
||||
|
||||
export async function createUser(data: InsertUser) {
|
||||
await db.insert(user).values(data);
|
||||
return await db.insert(users).values(data);
|
||||
}
|
||||
|
||||
export async function getUsers() {
|
||||
return await db.select().from(users);
|
||||
}
|
||||
export async function getUserById(id: string) {
|
||||
const result = await db
|
||||
.select()
|
||||
.from(users)
|
||||
.where(eq(users.id, id))
|
||||
.limit(1);
|
||||
|
||||
return result[0] || null;
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue