Merge branch 'worktree-agent-a7e6e4b2' into Develop
# Conflicts: # .planning/REQUIREMENTS.md # .planning/ROADMAP.md # .planning/STATE.md # drizzle/meta/_journal.json # src/db/schema.ts # src/db/seed.ts # src/shared/schemas.ts # src/shared/types.ts
This commit is contained in:
79
src/server/services/global-item.service.ts
Normal file
79
src/server/services/global-item.service.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
import { count, eq, like, or, sql } from "drizzle-orm";
|
||||
import { db as prodDb } from "../../db/index.ts";
|
||||
import { globalItems, itemGlobalLinks } from "../../db/schema.ts";
|
||||
|
||||
type Db = typeof prodDb;
|
||||
|
||||
/**
|
||||
* Search global items by brand or model. SQLite LIKE is case-insensitive for ASCII.
|
||||
* Escapes % and _ wildcard characters in user input.
|
||||
*/
|
||||
export function searchGlobalItems(db: Db = prodDb, query?: string) {
|
||||
if (!query) {
|
||||
return db.select().from(globalItems).all();
|
||||
}
|
||||
|
||||
// Escape SQL LIKE wildcards
|
||||
const escaped = query.replace(/%/g, "\\%").replace(/_/g, "\\_");
|
||||
const pattern = `%${escaped}%`;
|
||||
|
||||
return db
|
||||
.select()
|
||||
.from(globalItems)
|
||||
.where(
|
||||
or(
|
||||
like(globalItems.brand, pattern),
|
||||
like(globalItems.model, pattern),
|
||||
),
|
||||
)
|
||||
.all();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a single global item by ID with the count of user items linked to it.
|
||||
*/
|
||||
export function getGlobalItemWithOwnerCount(db: Db = prodDb, id: number) {
|
||||
const item = db
|
||||
.select()
|
||||
.from(globalItems)
|
||||
.where(eq(globalItems.id, id))
|
||||
.get();
|
||||
|
||||
if (!item) return null;
|
||||
|
||||
const result = db
|
||||
.select({ ownerCount: count() })
|
||||
.from(itemGlobalLinks)
|
||||
.where(eq(itemGlobalLinks.globalItemId, id))
|
||||
.get();
|
||||
|
||||
return { ...item, ownerCount: result?.ownerCount ?? 0 };
|
||||
}
|
||||
|
||||
/**
|
||||
* Link a user's item to a global item. Throws on duplicate (unique constraint on itemId).
|
||||
*/
|
||||
export function linkItemToGlobal(
|
||||
db: Db = prodDb,
|
||||
itemId: number,
|
||||
globalItemId: number,
|
||||
) {
|
||||
return db
|
||||
.insert(itemGlobalLinks)
|
||||
.values({ itemId, globalItemId })
|
||||
.returning()
|
||||
.get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the link between a user's item and any global item.
|
||||
*/
|
||||
export function unlinkItemFromGlobal(db: Db = prodDb, itemId: number) {
|
||||
const result = db
|
||||
.delete(itemGlobalLinks)
|
||||
.where(eq(itemGlobalLinks.itemId, itemId))
|
||||
.returning()
|
||||
.all();
|
||||
|
||||
return result.length;
|
||||
}
|
||||
Reference in New Issue
Block a user