Skip to content

Commit

Permalink
refactor: Remove console logs and enhance metadata handling by adding…
Browse files Browse the repository at this point in the history
… title extraction in EntryPage, ForceDirectedGraph, and ForceFromEntry components
  • Loading branch information
bramses committed Nov 9, 2024
1 parent 1ddb7c1 commit 303931c
Show file tree
Hide file tree
Showing 5 changed files with 224 additions and 7 deletions.
46 changes: 46 additions & 0 deletions src/app/[locale]/(auth)/api/log/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { NextResponse } from 'next/server';

import { logger } from '@/libs/Logger';

import { GET } from '../getCBPath/route';

// import env variables

export const POST = async (request: Request) => {
const { page, limit, sortModel } = await request.json();
const { CLOUD_URL } = process.env;

const dbRes = await GET(request);
if (!dbRes) {
return NextResponse.json({}, { status: 500 });
}
const { DATABASE_URL, API_KEY } = await dbRes.json();

const resp = await fetch(`${CLOUD_URL}/log`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
page,
limit,
sortModel,
dbPath: DATABASE_URL,
apiKey: API_KEY,
}),
});
logger.info('resp:', resp);
const data = await resp.json();

try {
logger.info(`A new log has been created ${JSON.stringify(data)}`);

return NextResponse.json({
data,
});
} catch (error) {
logger.error(error, 'An error occurred while creating a log');

return NextResponse.json({}, { status: 500 });
}
};
12 changes: 9 additions & 3 deletions src/components/EntryPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -876,7 +876,6 @@ const EntryPage = () => {
);
neighbor.parent = parent;
}
console.log('pushing neighbor:', neighbor.id);
// if metadata.author includes imagedelivery.net, add it to the thumbnails array
if (JSON.parse(neighbor.metadata).author) {
if (
Expand All @@ -885,6 +884,9 @@ const EntryPage = () => {
neighbor.image = JSON.parse(neighbor.metadata).author;
}
}
if (JSON.parse(neighbor.metadata).title) {
neighbor.title = JSON.parse(neighbor.metadata).title;
}
neighbors.push(neighbor);
}
}
Expand Down Expand Up @@ -929,7 +931,9 @@ const EntryPage = () => {
penPal.image = JSON.parse(penPal.metadata).author;
}
}
console.log('pushing penPal:', penPal.id);
if (JSON.parse(penPal.metadata).title) {
penPal.title = JSON.parse(penPal.metadata).title;
}
penPals.push(penPal);
}
}
Expand Down Expand Up @@ -970,7 +974,6 @@ const EntryPage = () => {
);
internalLink.parent = parent;
}
console.log('pushing internalLink:', internalLink.id);
if (JSON.parse(internalLink.metadata).author) {
if (
JSON.parse(internalLink.metadata).author.includes(
Expand All @@ -980,6 +983,9 @@ const EntryPage = () => {
internalLink.image = JSON.parse(internalLink.metadata).author;
}
}
if (JSON.parse(internalLink.metadata).title) {
internalLink.title = JSON.parse(internalLink.metadata).title;
}
internalLinks.push(internalLink);
}
}
Expand Down
17 changes: 14 additions & 3 deletions src/components/ForceDirectedGraph.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,13 @@ const ForceDirectedGraph = ({ data }: any) => {
content: '',
id: '',
image: '',
title: '',
});
const [showModal, setShowModal] = useState(false);

const openModal = (content: any, id: any, image: any) => {
setModalContent({ content, id, image });
const openModal = (content: any, id: any, image: any, title: any) => {
console.log('title:', title);
setModalContent({ content, id, image, title });
setShowModal(true);
};

Expand Down Expand Up @@ -63,13 +65,15 @@ const ForceDirectedGraph = ({ data }: any) => {
group: 'neighbor',
similarity: n.similarity,
image: n.image,
title: n.title,
})),
// Add internal links as nodes with 'internalLink' group
...data.internalLinks.map((link: any, idx: any) => ({
id: `internalLink-${idx}`,
label: link.internalLink,
group: 'internalLink',
image: link.image,
title: link.title,
})),
...data.internalLinks.flatMap((link: any) =>
link.penPals.map((penPal: any) => ({
Expand All @@ -78,13 +82,15 @@ const ForceDirectedGraph = ({ data }: any) => {
group: 'penPal',
similarity: penPal.similarity,
image: penPal.image,
title: penPal.title,
})),
),
...data.comments.map((comment: any, idx: any) => ({
id: `comment-${idx}`,
label: comment.comment,
group: 'comment',
image: comment.image,
title: comment.title,
})),
...data.comments.flatMap((comment: any) =>
comment.penPals.map((penPal: any) => ({
Expand All @@ -93,6 +99,7 @@ const ForceDirectedGraph = ({ data }: any) => {
group: 'penPal',
similarity: penPal.similarity,
image: penPal.image,
title: penPal.title,
})),
),
// Add parents of neighbors and penpals
Expand Down Expand Up @@ -240,7 +247,7 @@ const ForceDirectedGraph = ({ data }: any) => {
if (d.group === 'internalLink') return 'brown'; // Internal links as brown nodes
return 'gray';
})
.on('click', (_, d) => openModal(d.label, d.id, d.image))
.on('click', (_, d) => openModal(d.label, d.id, d.image, d.title))
.call(drag(simulation) as any);

const labels = g
Expand Down Expand Up @@ -302,6 +309,10 @@ const ForceDirectedGraph = ({ data }: any) => {
<p>{modalContent.content}</p>
)}
<br />
<p className="text-sm text-gray-500">
{modalContent.title}
</p>
<br />
<Link href={`/dashboard/entry/${modalContent.id}`} className="mt-4">
View Entry
</Link>
Expand Down
9 changes: 9 additions & 0 deletions src/components/ForceFromEntry.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ const ForceFromEntry = ({
neighbor.image = JSON.parse(neighbor.metadata).author;
}
}
if (JSON.parse(neighbor.metadata).title) {
neighbor.title = JSON.parse(neighbor.metadata).title;
}
neighbors.push(neighbor);
}
}
Expand Down Expand Up @@ -87,6 +90,9 @@ const ForceFromEntry = ({
penPal.image = JSON.parse(penPal.metadata).author;
}
}
if (JSON.parse(penPal.metadata).title) {
penPal.title = JSON.parse(penPal.metadata).title;
}
penPals.push(penPal);
}
}
Expand Down Expand Up @@ -132,6 +138,9 @@ const ForceFromEntry = ({
internalLink.image = JSON.parse(internalLink.metadata).author;
}
}
if (JSON.parse(internalLink.metadata).title) {
internalLink.title = JSON.parse(internalLink.metadata).title;
}
internalLinks.push(internalLink);
}
}
Expand Down
147 changes: 146 additions & 1 deletion src/components/SimpleDashboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { fetchByID, fetchRandomEntry } from '@/helpers/functions';

import ForceFromEntry from './ForceFromEntry';
import SearchModalBeta from './SearchModalBeta';
import Link from 'next/link';

const SimpleDashboard = () => {
const router = useRouter();
Expand All @@ -21,6 +22,8 @@ const SimpleDashboard = () => {
});
const [isSearchModalBetaOpen, setSearchModalBetaOpen] = useState(false);
const [searchBetaModalQuery, setSearchBetaModalQuery] = useState('');
const [logEntries, setLogEntries] = useState<any[]>([]);
const [isSaving, setIsSaving] = useState(false);

// const [inboxEntries, setInboxEntries] = useState<any[]>([]);
const { user, isLoaded } = useUser();
Expand Down Expand Up @@ -148,6 +151,56 @@ const SimpleDashboard = () => {
fetchEntry();
}, []);

// get log entries
const fetchLogEntries = async () => {
try {
const response = await fetch('/api/log', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
page: 1,
limit: 10,
sortModel: [{ colId: 'createdAt', sort: 'desc' }],
}),
});
const data = await response.json();
console.log('Log entries:', data);
// if createdAt == updatedAt, say "added", else "updated"
const log = data.data.map((entry: any) => {
// skip entries with parent_id
let metadata;
try {
metadata = JSON.parse(entry.metadata);
} catch (err) {
console.error('Error parsing metadata:', err);
}
if (metadata.parent_id) {
return null;
}
if (entry.createdAt === entry.updatedAt) {
return {
...entry,
action: 'added',
};
}
return {
...entry,
action: 'updated',
};
}).filter((entry: any) => entry !== null);
console.log('Log:', log);
setLogEntries(log);
} catch (error) {
console.error('Error fetching log entries:', error);
}
};

useEffect(() => {
fetchLogEntries();
}, []);

const closeModal = () => setSearchModalBetaOpen(false);

return (
Expand Down Expand Up @@ -207,7 +260,6 @@ const SimpleDashboard = () => {
closeModalFn={() => closeModal()}
inputQuery={searchBetaModalQuery}
/>

{randomEntry && (
<>
<button
Expand All @@ -229,6 +281,99 @@ const SimpleDashboard = () => {
</button>
</>
)}

{/* ask the user what they are thinking about right now in a text box and add it as an entry -- like a journal */}
<h1 className="my-4 text-xl font-extrabold text-gray-900 md:text-xl lg:text-xl">
Journal
</h1>
<div className="mx-2 my-4">
<textarea
id="journal-message"
rows={4}
className="mt-4 block w-full rounded-lg border border-gray-300 bg-gray-50 p-2.5 text-sm text-gray-900 focus:border-blue-500 focus:ring-blue-500"
placeholder="What are you thinking about right now?"
/>
<button
type="button"
onClick={async () => {
const journalMessage = (
document.getElementById('journal-message') as HTMLInputElement
).value;
if (!journalMessage) {
return;
}
setIsSaving(true); // Set loading state
try {
// add the journal message as an entry
await fetch('/api/add', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
data: journalMessage,
metadata: {
author: randomEntry.metadata.author,
title: 'Journal',
},
}),
});
(document.getElementById('journal-message') as HTMLInputElement).value = ''; // Clear textarea
await fetchLogEntries(); // Reload log entries
} catch (error) {
console.error('Error saving journal entry:', error);
} finally {
setIsSaving(false); // Reset loading state
}
}}
disabled={isSaving} // Disable button while saving
className={`mt-2 w-full rounded-lg ${
isSaving ? 'bg-gray-400' : 'bg-blue-700'
} px-5 py-2.5 text-sm font-medium text-white ${
isSaving ? '' : 'hover:bg-blue-800'
} focus:outline-none focus:ring-4 focus:ring-blue-300 dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800`}
>
{isSaving ? 'Loading...' : 'Save'}
</button>
</div>

<h1 className="my-4 text-xl font-extrabold text-gray-900 md:text-xl lg:text-xl">
Recent Activity
</h1>
<div className="mx-2 my-4">
{logEntries.map((entry: any) => (
<div key={entry.id}>
<div
key={entry.id}
className="mx-2 mb-4 flex items-center justify-between"
>
<div className="grow">
<Link
href={{
pathname: `/dashboard/entry/${entry.id}`,
}}
className="block text-gray-900 no-underline"
>
<div className="relative">
<span className="font-normal">
{entry.data}
</span>
</div>
</Link>
<div className="text-sm text-gray-500">
{entry.action === 'added'
? <b>Added</b>
: entry.action === 'updated'
? <b>Updated</b>
: 'Deleted'}{' '}
{new Date(entry.updatedAt).toLocaleDateString()}
</div>
</div>
</div>
{/* <hr className="my-4" /> */}
</div>
))}
</div>
</div>
);
};
Expand Down

0 comments on commit 303931c

Please sign in to comment.