Skip to content
Merged
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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/venv
/frontend/package-lock.json
15 changes: 15 additions & 0 deletions backend/crud.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from unicodedata import name
from unittest import skip
from sqlalchemy.orm import Session

import models, schemas

def get_grocery_list(db: Session, skip: int = 0, limit: int = 50):
return db.query(models.Food).offset(skip).limit(limit).all()

def add_to_grocery_list(db: Session, food: schemas.FoodCreate ):
db_food = models.Food(name = food.name)
db.add(db_food)
db.commit()
db.refresh(db_food)
return db_food
20 changes: 20 additions & 0 deletions backend/database.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

# ------ Create a database URL for SQLAlchemy
# SQLALCHEMY_DATABASE_URL = "postgresql://localhost:5432"
# SQLALCHEMY_DATABASE_URL = "postgresql://postgres:password@localhost:5432/food"
SQLALCHEMY_DATABASE_URL = "postgresql://postgres:password@localhost:5432/postgres"
# SQLALCHEMY_DATABASE_URL = "postgresql://postgres:postgrespassword@host.docker.internal:5432/postgres"


# ------ Create the SQLAlchemy engine
engine = create_engine(
SQLALCHEMY_DATABASE_URL
)
# ------ Create a SessionLocal (the class for a database session)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# ------ Create a base Class (used to create the database models/classes/ORM models)
Base = declarative_base()
56 changes: 43 additions & 13 deletions backend/main.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,18 @@
from fastapi import FastAPI
from fastapi import FastAPI, Depends, HTTPException
from pydantic import BaseModel
from sqlalchemy.orm import Session

from fastapi.middleware.cors import CORSMiddleware
import requests

# from . import crud, models, schemas
# from .database import SessionLocal, engine
import crud, models, schemas
from database import SessionLocal, engine

# Initialize tables; generally, Alembic is a tool meant for initializing DBs and migrations.
# But, for now we can use this
models.Base.metadata.create_all(bind=engine)

app = FastAPI()

Expand All @@ -19,30 +28,51 @@
allow_headers=["*"],
)

class Food(BaseModel):
# Dependancy
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()

class Food2(BaseModel):
id:str
name:str

grocery_list = [
{"name":"oranges"},
{"name":"bread"}
]

# grocery_list = [
# {"name":"oranges"},
# {"name":"bread"}
# ]

## Endpoints
@app.get("/")
async def welcome():
return "Who's Hungry!"

@app.get("/groceries")
async def get_groceries_list():

@app.get("/groceries", response_model = list[schemas.Food])
def get_groceries_list(skip: int = 0, limit: int = 50, db: Session = Depends(get_db)):
grocery_list = crud.get_grocery_list(db, skip, limit=limit)
return grocery_list

@app.post('/add')
async def add_item(item:Food):
grocery_list.append(item)
return "Added " + item.name
@app.post('/add', response_model = schemas.Food)
def add_to_grocery_list(food:schemas.FoodCreate, db: Session = Depends(get_db)):
return crud.add_to_grocery_list(db=db, food=food)


# @app.get("/groceries")
# async def get_groceries_list():
# return grocery_list

# @app.post('/add')
# async def add_item(item:Food):
# grocery_list.append(item)
# return "Added " + item.name

@app.get('/recipes')
async def find_recipes(item:Food):
async def find_recipes(item:Food2): #schemas.Food
result = []
response = find_by_ingredients(item.name)

Expand Down
10 changes: 10 additions & 0 deletions backend/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from sqlalchemy import Boolean, Column, ForeignKey, Integer, String
from sqlalchemy.orm import relationship

from database import Base

class Food(Base):
__tablename__ = "food"

id = Column(Integer, index=True, primary_key=True)
name = Column(String, index=True)
15 changes: 15 additions & 0 deletions backend/schemas.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Create the Pydantic models(schemas)
from typing import List, Union
from pydantic import BaseModel

class FoodBase(BaseModel):
name: str
class Config: # Use Pydantic's orm_mode
orm_mode = True

class FoodCreate(FoodBase):
pass

class Food(FoodBase):
id: int
pass
17 changes: 16 additions & 1 deletion frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 5 additions & 2 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"awesome-typescript-loader": "^5.2.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"react-scripts": "^5.0.1",
"source-map-loader": "^4.0.0",
"typescript": "^4.7.4",
"web-vitals": "^2.1.4"
Expand Down Expand Up @@ -42,5 +42,8 @@
"last 1 safari version"
]
},
"proxy":"http://localhost:8000"
"proxy": "http://localhost:8000",
"devDependencies": {
"@types/uuid": "^8.3.4"
}
}
16 changes: 14 additions & 2 deletions frontend/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import React from 'react';
import List from './components/List';
import Recipe from './components/Recipe';
import { isTemplateExpression } from 'typescript';
import {v4 as uuid} from 'uuid';

export default function App() {

Expand All @@ -22,14 +23,23 @@ export default function App() {
function onClose(){
setAddModalIsOpen(false);
console.log('canceled');

// const myuuid = uuid();
// console.log('Your UUID is:' + myuuid);
// console.log(typeof myuuid);

}
function onAdd(foodName: string){
fetch('http://localhost:3000/add',{
method:'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({"name":foodName}),
body: JSON.stringify({
"id":uuid(),
"name":foodName
}),
// body: JSON.stringify({"name":foodName}),
})
.then(data => {
console.log('Success', data)
Expand All @@ -41,12 +51,14 @@ export default function App() {
}

async function fetchFoodList() {
console.log("about to fetch some food...");
const response = await fetch('http://localhost:3000/groceries', {
method:'GET',
headers: {
'accept': 'application/json',
}
});
console.log("got some food...", response);
const newList: FoodObj[] = await response.json();
console.log('newList', newList);
const newFoodList: FoodList = {
Expand Down Expand Up @@ -90,7 +102,7 @@ export default function App() {

React.useEffect(() => {
fetchFoodList();
}, [addModalIsOpen]);
}, [foodList]);

return (
<div className="App">
Expand Down