Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use pglite to persist items (wip) #42

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified bun.lockb
100644 → 100755
Binary file not shown.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@electric-sql/pglite": "^0.1.5",
"dayjs": "^1.11.11",
"uuid": "^10.0.0"
},
Expand Down
55 changes: 37 additions & 18 deletions src/lib/components/StoragePlace.svelte
Original file line number Diff line number Diff line change
@@ -1,17 +1,26 @@
<script lang="ts">
import Item from '$lib/components/item/Item.svelte'
import { createItemStore } from '$lib/stores/item.svelte'
import { type ItemStore, createItemStore } from '$lib/stores/item.svelte'

// Props
const { storagePlaceName }: { storagePlaceName: string } = $props()

// State
const items = createItemStore()
let items = $state< ItemStore | null>()
let newItemName = $state('')
let isLoading = $state(true)

$effect(() => {
createItemStore().then((itemStore) => {
items = itemStore
isLoading = false
})
})

// Methods
function addItem() {
items.add(newItemName)
if (items)
items.add(newItemName)
newItemName = ''
}

Expand All @@ -26,21 +35,31 @@
class="rounded-sm border m-3 inline-block h-fit min-w-80 max-w-[420px] border-black p-1"
role="tree"
>
<h1 class="font-bold">{storagePlaceName} <span class="text-stone-400">({items.list.length})</span></h1>
<div role="group">
{#each items.list as item, i (item.id)}
<Item
bind:item={items.list[i]}
isSelected={items.selected === i}
onSelected={(amount = 0) => {
items.select(i + amount)
}}
onDelete={items.delete}
/>
{/each}
</div>
{#if items.list.length === 0}
<div class="text-stone-400">Nothing in the {storagePlaceName}.</div>
<h1 class="font-bold">{storagePlaceName}
{#if items}
<span class="text-stone-400">({items.list.length})</span>
{/if}
</h1>
{#if isLoading || !items}
<p>Loading</p>
{:else}
<div role="group">
{#each items.list as item, i (item.id)}
<Item
bind:item={items.list[i]}
isSelected={items.selected === i}
onSelected={(amount = 0) => {
if (items)
items.select(i + amount)
}}
onDelete={items.delete}
/>
{/each}
</div>

{#if items.list.length === 0}
<div class="text-stone-400">Nothing in the {storagePlaceName}.</div>
{/if}
{/if}

<input
Expand Down
63 changes: 63 additions & 0 deletions src/lib/db.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { PGlite } from '@electric-sql/pglite'

let db: PGlite
let dbInitialized = false

export async function initDb(): Promise<void> {
if (!dbInitialized) {
db = new PGlite('idb://food-inventory')
await db.waitReady
await createTables()
dbInitialized = true
}
}

async function createTables(): Promise<void> {
// await db.exec(`DROP TABLE IF EXISTS food_item`)
await db.exec(`
CREATE TABLE IF NOT EXISTS food_items (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
quantity INTEGER,
date_added DATE,
storage TEXT
);
`)
}

interface FoodItem {
id: string
name: string
quantity: number
date_added: string
storage: string
}

export async function addFoodItem(id: string, name: string, quantity: number, storage: string): Promise<void> {
await initDb()
const date_added = new Date().toISOString().split('T')[0]

await db.query<FoodItem>(
'INSERT INTO food_items (id, name, quantity, date_added, storage) VALUES ($1, $2, $3, $4, $5)',
[id, name, quantity, date_added, storage],
)
}

export async function getFoodItems(storage: string): Promise<FoodItem[]> {
await initDb()
const result = await db.query<FoodItem>('SELECT * FROM food_items WHERE storage = $1', [storage])
return result.rows
}

export async function updateFoodItem(id: string, name: string, quantity: number, dateAdded: string): Promise<void> {
await initDb()
await db.query(
'UPDATE food_items SET name = $1, quantity = $2, dateAdded = $3 WHERE id = $4',
[name, quantity, dateAdded, id],
)
}

export async function deleteFoodItem(id: string): Promise<void> {
await initDb()
await db.query('DELETE FROM food_items WHERE id = $1', [id])
}
90 changes: 54 additions & 36 deletions src/lib/stores/item.svelte.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,42 +3,60 @@ import dayjs from 'dayjs'
import { possibleItems } from '$lib/components/item/itemGenerator'
import { randomIntFromInterval } from '$lib/utils'
import type { StoredItem } from '$lib/types'
import { addFoodItem, deleteFoodItem, getFoodItems, updateFoodItem } from '$lib/db'

export function createItemStore() {
const list = $state<StoredItem[]>(getRandomItems())
export interface ItemStore { readonly list: StoredItem[], add: (name: string) => void, delete: (id: string) => void, readonly selected: number, select: (i: number) => void }

export async function createItemStore() {
const foodItems = await getFoodItems('fridge')
console.log(foodItems)

const storedFoodItems = foodItems.map(foodItem => ({ id: foodItem.id, name: foodItem.name, quantity: foodItem.quantity, dateAdded: foodItem.date_added, shelfLife: 5 }))
const list = $state<StoredItem[]>(storedFoodItems)
let selected = $state(-1)

return {
get list() {
return list
},
add(name: string) {
if (name === '')
add(input: string) {
if (input === '')
return

const itemList = name.split(' ')
const id = uuid()

const itemList = input.split(' ')
let itemName: string
let itemQuantity: number

if (itemList.length > 1 && itemList[0].match(/^\d+$/)) {
list.push({
id: uuid(),
dateAdded: dayjs().format('YYYY-MM-DD'),
name: name.slice(itemList[0].length).trim(),
quantity: Math.min(Number(itemList[0]), 99),
shelfLife: 5,
})
itemName = input.slice(itemList[0].length).trim()
itemQuantity = Math.min(Number(itemList[0]), 99)
}
else {
list.push({
id: uuid(),
dateAdded: dayjs().format('YYYY-MM-DD'),
name,
quantity: 1,
shelfLife: 5,
})
itemName = input
itemQuantity = 1
}

const newItem = {
id,
dateAdded: dayjs().format('YYYY-MM-DD'),
name: itemName,
quantity: itemQuantity,
shelfLife: 5,
}

list.push(newItem)
addFoodItem(id, itemName, itemQuantity, 'fridge')

selected = list.length
},
update(id: string, name: string, quantity: number, dateAdded: string) {
// currently not connected. not sure how to do it with bindable item?
updateFoodItem(id, name, quantity, dateAdded)
},
delete(id: string) {
deleteFoodItem(id)
const index = list.findIndex(item => item.id === id)

if (index !== -1) {
Expand All @@ -61,23 +79,23 @@ export function createItemStore() {
}
}

function getRandomItems(
itemList: StoredItem[] = possibleItems,
minItems = 3,
maxItems = 10,
) {
// Determine the number of items to select
const numItems = randomIntFromInterval(minItems, maxItems)
// function getRandomItems(
// itemList: StoredItem[] = possibleItems,
// minItems = 3,
// maxItems = 10,
// ) {
// // Determine the number of items to select
// const numItems = randomIntFromInterval(minItems, maxItems)

// Array to hold our selected items
const selectedItems = []
// // Array to hold our selected items
// const selectedItems = []

// Select random items
for (let i = 0; i < numItems && itemList.length > 0; i++) {
const randomIndex = Math.floor(Math.random() * itemList.length)
selectedItems.push(itemList[randomIndex])
itemList.splice(randomIndex, 1)
}
// // Select random items
// for (let i = 0; i < numItems && itemList.length > 0; i++) {
// const randomIndex = Math.floor(Math.random() * itemList.length)
// selectedItems.push(itemList[randomIndex])
// itemList.splice(randomIndex, 1)
// }

return selectedItems
}
// return selectedItems
// }
18 changes: 18 additions & 0 deletions vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ export default defineConfig({
sveltekit(),
svelteTesting(),
],
optimizeDeps: {
exclude: ['@electric-sql/pglite'],
},
test: {
environment: 'jsdom',
coverage: {
Expand All @@ -16,4 +19,19 @@ export default defineConfig({
reporters: ['html', 'default'],
include: ['src/**/*.{test,spec}.{js,ts}'],
},
// build: {
// commonjsOptions: {
// include: [/@electric-sql\/pglite/, /node_modules/],
// },
// },
// server: {
// fs: {
// allow: ['..'],
// },
// },
// resolve: {
// alias: {
// '@electric-sql/pglite': '@electric-sql/pglite/dist/index.js',
// },
// },
})