Jotzy/frontend/src/api/notes.tsx

90 lines
2.6 KiB
TypeScript
Raw Normal View History

2025-11-23 09:08:01 +00:00
import axios from "axios";
import { encryptString, decryptString } from "./encryption";
import { useAuthStore } from "../stores/authStore";
import { Tag } from "./tags";
axios.defaults.withCredentials = true;
const API_URL = (import.meta as any).env.PROD
? "/api"
: "http://localhost:8000/api";
2025-11-23 09:08:01 +00:00
export interface Note {
id: number;
title: string;
folder_id?: number;
content: string;
created_at: string;
updated_at: string;
tags: Tag[];
2025-11-23 09:08:01 +00:00
}
export interface NoteCreate {
title: string;
content: string;
folder_id: number | null;
}
2025-11-23 15:14:48 +00:00
const createNote = async (note: NoteCreate) => {
const encryptionKey = useAuthStore.getState().encryptionKey;
if (!encryptionKey) throw new Error("Not authenticated");
var noteContent = await encryptString(note.content, encryptionKey);
var noteTitle = await encryptString(note.title, encryptionKey);
2025-11-24 19:48:46 +00:00
var encryptedNote = {
title: noteTitle,
content: noteContent,
folder_id: note.folder_id,
};
console.log(encryptedNote);
return axios.post(`${API_URL}/notes/`, encryptedNote);
2025-11-24 19:48:46 +00:00
};
const fetchNotes = async () => {
const encryptionKey = useAuthStore.getState().encryptionKey;
if (!encryptionKey) throw new Error("Not authenticated");
const { data } = await axios.get(`${API_URL}/notes/`);
2025-11-24 19:48:46 +00:00
console.log(data);
const decryptedNotes = await Promise.all(
data.map(async (note: Note) => ({
...note,
title: await decryptString(note.title, encryptionKey),
content: await decryptString(note.content, encryptionKey),
tags: await Promise.all(
note.tags.map(async (tag) => ({
...tag,
name: await decryptString(tag.name, encryptionKey),
})),
),
2025-11-24 19:48:46 +00:00
})),
);
return decryptedNotes;
2025-11-23 15:14:48 +00:00
};
const updateNote = async (id: number, note: Partial<Note>) => {
const encryptionKey = useAuthStore.getState().encryptionKey;
if (!encryptionKey) throw new Error("Not authenticated");
var encryptedNote: Partial<Note> = {};
if (note.content) {
encryptedNote.content = await encryptString(note.content, encryptionKey);
}
if (note.title) {
encryptedNote.title = await encryptString(note.title, encryptionKey);
}
if (note.folder_id) {
encryptedNote.folder_id = note.folder_id;
}
return axios.patch(`${API_URL}/notes/${id}`, encryptedNote);
};
2025-11-23 09:08:01 +00:00
export const notesApi = {
2025-11-24 19:48:46 +00:00
list: () => fetchNotes(),
2025-11-23 09:08:01 +00:00
get: (id: number) => axios.get(`${API_URL}/notes/${id}`),
2025-11-23 15:14:48 +00:00
create: (note: NoteCreate) => createNote(note),
update: (id: number, note: Partial<Note>) => updateNote(id, note),
2025-11-23 09:08:01 +00:00
delete: (id: number) => axios.delete(`${API_URL}/notes/${id}`),
};