Skip to content

Commit

Permalink
Add milestones to backend
Browse files Browse the repository at this point in the history
- add/update Milestone, MilestoneText, MilestoneImage models
- add admin endpoints to create / update / delete milestones

Make endpoint naming more consistent

- use plurals for all collections of entities
- use PUT instead of PATCH since these endpoints take the entire entity, not just selected fields to update

Refactor

- use factory pattern for app and routers to make it easier to modify app settings in tests
- extract common router code into utils
- extend and refactor backend tests
  • Loading branch information
lkeegan committed Sep 26, 2024
1 parent bbea732 commit 1744f2a
Show file tree
Hide file tree
Showing 17 changed files with 891 additions and 494 deletions.
18 changes: 11 additions & 7 deletions frontend/src/lib/admin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export async function refreshMilestoneGroups() {
export async function newMilestoneGroup() {
console.log('newMilestoneGroup...');
try {
const res = await fetch(`${import.meta.env.VITE_MONDEY_API_URL}/admin/milestone-group/`, {
const res = await fetch(`${import.meta.env.VITE_MONDEY_API_URL}/admin/milestone-groups/`, {
method: 'POST',
credentials: 'include',
headers: {
Expand All @@ -50,12 +50,12 @@ export async function newMilestoneGroup() {
return null;
}

export async function patchMilestoneGroup(milestoneGroup) {
console.log('patchMilestoneGroup...');
export async function updateMilestoneGroup(milestoneGroup) {
console.log('updateMilestoneGroup...');
console.log(milestoneGroup);
try {
const res = await fetch(`${import.meta.env.VITE_MONDEY_API_URL}/admin/milestone-group`, {
method: 'PATCH',
const res = await fetch(`${import.meta.env.VITE_MONDEY_API_URL}/admin/milestone-groups`, {
method: 'PUT',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
Expand Down Expand Up @@ -83,9 +83,9 @@ export async function uploadMilestoneGroupImage(milestoneGroupId: number, file)
const formData = new FormData();
formData.append('file', file);
const res = await fetch(
`${import.meta.env.VITE_MONDEY_API_URL}/admin/upload-milestone-group-image/${milestoneGroupId}`,
`${import.meta.env.VITE_MONDEY_API_URL}/admin/milestone-group-images/${milestoneGroupId}`,
{
method: 'POST',
method: 'PUT',
credentials: 'include',
body: formData
}
Expand Down Expand Up @@ -121,3 +121,7 @@ export async function deleteMilestoneGroup(milestoneGroupId: number | null) {
console.error(e);
}
}

export function milestoneGroupImageUrl(id: number) {
return `${import.meta.env.VITE_MONDEY_API_URL}/static/mg${id}.jpg`;
}
17 changes: 9 additions & 8 deletions frontend/src/lib/components/Admin/EditMilestoneGroupModal.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,11 @@
Modal
} from 'flowbite-svelte';
import { lang_id, languages } from '$lib/stores/adminStore';
import { patchMilestoneGroup, uploadMilestoneGroupImage } from '$lib/admin';
import {
updateMilestoneGroup,
uploadMilestoneGroupImage,
milestoneGroupImageUrl
} from '$lib/admin';
export let open: boolean = false;
export let milestoneGroup: object | null = null;
Expand All @@ -19,7 +23,7 @@
let image: string | ArrayBuffer | null | undefined = null;
$: if (milestoneGroup !== null) {
image = `${import.meta.env.VITE_MONDEY_API_URL}/static/milestone_group_${milestoneGroup.id}.jpg`;
image = milestoneGroupImageUrl(milestoneGroup.id);
}
$: if (files) {
Expand All @@ -30,20 +34,17 @@
};
}
async function reloadImg(url) {
console.log(`Reloading ${url}`);
async function reloadImg(url: string) {
await fetch(url, { cache: 'reload', mode: 'no-cors' });
document.body.querySelectorAll(`img[src='${url}']`).forEach((img) => (img.src = url));
}
export async function saveChanges() {
try {
await patchMilestoneGroup(milestoneGroup);
await updateMilestoneGroup(milestoneGroup);
if (files) {
await uploadMilestoneGroupImage(milestoneGroup.id, files[0]);
reloadImg(
`${import.meta.env.VITE_MONDEY_API_URL}/static/milestone_group_${milestoneGroup.id}.jpg`
);
await reloadImg(milestoneGroupImageUrl(milestoneGroup.id));
}
} catch (e) {
console.error(e);
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/lib/components/Admin/Languages.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
async function newLanguage() {
try {
const res = await fetch(`${import.meta.env.VITE_MONDEY_API_URL}/admin/language`, {
const res = await fetch(`${import.meta.env.VITE_MONDEY_API_URL}/admin/languages`, {
method: 'POST',
credentials: 'include',
headers: {
Expand All @@ -48,7 +48,7 @@
async function deleteLanguage(id: string) {
try {
const res = await fetch(`${import.meta.env.VITE_MONDEY_API_URL}/admin/language/${id}`, {
const res = await fetch(`${import.meta.env.VITE_MONDEY_API_URL}/admin/languages/${id}`, {
method: 'DELETE',
credentials: 'include',
headers: {
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/lib/components/Admin/MilestoneGroups.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
import EditMilestoneGroupModal from '$lib/components/Admin/EditMilestoneGroupModal.svelte';
import DeleteMilestoneGroupModal from '$lib/components/Admin/DeleteMilestoneGroupModal.svelte';
import { lang_id, milestoneGroups } from '$lib/stores/adminStore';
import { refreshMilestoneGroups, newMilestoneGroup } from '$lib/admin';
import { refreshMilestoneGroups, newMilestoneGroup, milestoneGroupImageUrl } from '$lib/admin';
import { onMount } from 'svelte';
let currentGroup: object | null = null;
Expand Down Expand Up @@ -77,7 +77,7 @@
</TableBodyCell>
<TableBodyCell>
<img
src={`${import.meta.env.VITE_MONDEY_API_URL}/static/milestone_group_${milestoneGroup.id}.jpg`}
src={milestoneGroupImageUrl(milestoneGroup.id)}
width="64"
height="64"
alt={title}
Expand Down
108 changes: 0 additions & 108 deletions frontend/src/lib/components/Admin/NewMilestoneGroupModal.svelte

This file was deleted.

4 changes: 2 additions & 2 deletions frontend/src/lib/stores/adminStore.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { writable } from 'svelte/store';
import { writable, type Writable } from 'svelte/store';

export const isLoggedIn = writable(false);

export const milestoneGroups = writable([]);

export const languages = writable({});
export const languages: Writable<Record<string, string>> = writable({});

export const lang_id = writable('1');
39 changes: 21 additions & 18 deletions mondey_backend/src/mondey_backend/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,24 +25,26 @@ async def lifespan(app: FastAPI):
yield


# ensure static files directory exists
pathlib.Path(app_settings.STATIC_FILES_PATH).mkdir(parents=True, exist_ok=True)
app = FastAPI(lifespan=lifespan, title="MONDEY API", root_path="/api")
app.include_router(milestones.router)
app.include_router(admin.router)
app.include_router(users.router)
app.include_router(auth.router)
app.mount(
"/static", StaticFiles(directory=app_settings.STATIC_FILES_PATH), name="static"
)
if app_settings.ENABLE_CORS:
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:5173"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
def create_app() -> FastAPI:
# ensure static files directory exists
pathlib.Path(app_settings.STATIC_FILES_PATH).mkdir(parents=True, exist_ok=True)
app = FastAPI(lifespan=lifespan, title="MONDEY API", root_path="/api")
app.include_router(milestones.create_router())
app.include_router(admin.create_router())
app.include_router(users.create_router())
app.include_router(auth.create_router())
app.mount(
"/static", StaticFiles(directory=app_settings.STATIC_FILES_PATH), name="static"
)
if app_settings.ENABLE_CORS:
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:5173"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
return app


def main():
Expand All @@ -55,12 +57,13 @@ def main():
for key, value in app_settings:
logger.info(f"{key}: {value if key != 'SECRET' else '****************'}")
uvicorn.run(
"mondey_backend.main:app",
"mondey_backend.main:create_app",
host=app_settings.HOST,
port=app_settings.PORT,
reload=app_settings.RELOAD,
log_level=app_settings.LOG_LEVEL,
forwarded_allow_ips="*",
factory=True,
)


Expand Down
Loading

0 comments on commit 1744f2a

Please sign in to comment.