Skip to content

Commit

Permalink
Refactor: Changed owens function to read off database
Browse files Browse the repository at this point in the history
  • Loading branch information
AntGa committed Oct 1, 2024
1 parent b806e22 commit 7298a2e
Show file tree
Hide file tree
Showing 8 changed files with 181 additions and 81 deletions.
19 changes: 18 additions & 1 deletion prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -49,5 +49,22 @@ model Project {
model Tag {
id Int @id @default(autoincrement()) // Auto-generated unique tag ID
name String @unique
projects Project[] @relation("ProjectToTag") // Many-to-many relation with Project
projects Project[] @relation("ProjectToTag")
}

// schema.prisma

model TeamDescription {
id Int @id @default(autoincrement()) // Unique identifier for each team description
name String @unique // Name of the team (must be unique)
description String? // Description of the team (optional)
tags TeamTag[] @relation("TeamDescriptionTags") // Many-to-many relationship with TeamTag
createdAt DateTime @default(now()) // Timestamp when the record was created
updatedAt DateTime @updatedAt // Timestamp when the record was last updated
}

model TeamTag {
id Int @id @default(autoincrement()) // Unique identifier for each tag
name String @unique // Name of the tag (must be unique)
teamDescriptions TeamDescription[] @relation("TeamDescriptionTags") // Relation back to TeamDescription
}
2 changes: 2 additions & 0 deletions src/pages/api/refresh-login.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Client } from "@notionhq/client";
import { updateMembers } from "../../scripts/updateMembers.ts";
import { updateProjects } from "../../scripts/updateProjects.ts";
import { updateTeamsDescriptions } from "../../scripts/updateTeamDescription.ts";
import { updateHomepageDescriptions } from "../../scripts/updateHomepageDescriptions.ts";
import type { APIRoute } from 'astro';
import type { passwordRow } from "../../types/passwordRow.ts";
Expand Down Expand Up @@ -60,6 +61,7 @@ export const POST: APIRoute = async ({ request }) => {
await updateMembers();
await updateProjects();
await updateHomepageDescriptions();
await updateTeamsDescriptions();
return new Response(JSON.stringify({ success: true }), { status: 200 });
} catch (err) {
console.error("Error during refresh data:", err);
Expand Down
17 changes: 5 additions & 12 deletions src/pages/members.astro
Original file line number Diff line number Diff line change
@@ -1,35 +1,28 @@
---
import { sortMembersByTeam } from "../scripts/sortTeams.ts";
import path from "path"
import "../styles/global.css";
import "../styles/members.css";
import {fetchMembers} from "../scripts/serveMembers"
import Layout from "../layouts/layout.astro";
import TeamDisplayLeft from "../components/TeamDisplayLeft.astro";
import TeamDisplayRight from "../components/TeamDisplayRight.astro";
import ProjectTeam from "../components/ProjectTeam.tsx";
import { getTeamsDescriptions } from "../scripts/getTeamDescription";
let members = await fetchMembers(); // Call the new function
import type {TeamDescriptions} from "../types/teamDescriptions"
import {serveTeamDescriptions} from "../scripts/serveTeamDescriptions"
import type { memberData } from "../types/memberData";
type TeamDescriptions = {
name: string;
description?: string;
tags?: string;
}
type Team = {
teamName: string;
members: memberData[];
description: string | undefined;
}
let members = await fetchMembers();
let { teamsDict, projects } =
sortMembersByTeam(members);
let teamDescription: TeamDescriptions[] = await getTeamsDescriptions();
let teamDescription: TeamDescriptions[] = await serveTeamDescriptions()
function mapTeamWithDesc(teams: {[teamName: string]: memberData[]}, teamDescription: TeamDescriptions[]) {
return Object.keys(teams)
Expand Down
40 changes: 0 additions & 40 deletions src/scripts/getTeamDescription.ts

This file was deleted.

43 changes: 43 additions & 0 deletions src/scripts/serveTeamDescriptions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { PrismaClient } from '@prisma/client';

// Initialize Prisma Client
const prisma = new PrismaClient();

type TeamDescriptions = {
name: string;
description?: string;
tags?: string[]; // Array of tag names
};

/**
* Fetches team descriptions with their tags from the database.
* @returns {Promise<TeamDescriptions[]>} An array of team descriptions with tags.
*/
export async function serveTeamDescriptions(): Promise<TeamDescriptions[]> {
let teamDescriptions: TeamDescriptions[] = []; // Explicitly type the result variable

try {
// Fetch team descriptions with their related tags
const descriptions = await prisma.teamDescription.findMany({
include: {
tags: true, // Fetch related tags
},
});

// Map the results to the TeamDescriptions type
teamDescriptions = descriptions.map((team) => ({
name: team.name,
description: team.description || undefined,
tags: team.tags.map((tag) => tag.name) || undefined, // Convert tag objects to an array of tag names
}));

} catch (err) {
console.error("Error fetching team descriptions:", err);
teamDescriptions = []; // Fallback to an empty array in case of error
} finally {
// Close Prisma Client connection
await prisma.$disconnect();
}

return teamDescriptions;
}
72 changes: 72 additions & 0 deletions src/scripts/updateTeamDescription.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { Client } from "@notionhq/client";
import { PrismaClient } from '@prisma/client'; // Import PrismaClient
import type { teamRow } from "../types/teamRow";

type TeamDescriptions = {
name: string;
description?: string;
tags?: string[];
};

export async function updateTeamsDescriptions(): Promise<void> {
const NOTION_TOKEN = process.env.NOTION_TOKEN || import.meta.env.NOTION_TOKEN;
const NOTION_TEAMS_ID = process.env.NOTION_TEAMS_ID || import.meta.env.NOTION_TEAMS_ID;
if (!NOTION_TOKEN || !NOTION_TEAMS_ID) throw new Error("Missing secret(s)");

const notion = new Client({ auth: NOTION_TOKEN });
const prisma = new PrismaClient();

const query = await notion.databases.query({
database_id: NOTION_TEAMS_ID,
sorts: [{
property: 'Name',
direction: 'ascending'
}]
});

const teampages = query.results as teamRow[];

const teams: TeamDescriptions[] = teampages.map((row) => {
return {
name: row.properties.Name.title[0] ? row.properties.Name.title[0].plain_text : "",
description: row.properties.Description.rich_text[0] ? row.properties.Description.rich_text[0].plain_text : "",
tags: row.properties.Tags.multi_select?.map(tag => tag.name) || [], // Use optional chaining and provide default
};
});

// Store teams in the Prisma database
for (const team of teams) {
// Ensure tags is an array to avoid 'undefined' error
const tagConnections = await Promise.all(
(team.tags || []).map(async (tagName) => { // Use a fallback to an empty array if tags is undefined
const tag = await prisma.teamTag.upsert({
where: { name: tagName },
create: { name: tagName },
update: {},
});
return { id: tag.id }; // Return the tag id for connecting
})
);

// Upsert the team description
await prisma.teamDescription.upsert({
where: { name: team.name },
create: {
name: team.name,
description: team.description,
tags: {
connect: tagConnections, // Connect the tags
},
},
update: {
description: team.description,
tags: {
set: tagConnections, // Update the tags
},
},
});
}

console.log("Team descriptions uploaded to Prisma database.");
await prisma.$disconnect();
}
5 changes: 5 additions & 0 deletions src/types/teamDescriptions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export type TeamDescriptions = {
name: string;
description?: string;
tags?: string[];
}
64 changes: 36 additions & 28 deletions src/types/teamRow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,33 +3,41 @@ import type { rich_text } from "./richText";
import type { cover } from "./cover";

export type teamRow = {
object: string,
id: string,
created_time: string,
last_edited_time: string,
created_by: { object: string, id: string },
last_edited_by: { object: string, id: string },
cover: cover,
icon: null,
object: string;
id: string;
created_time: string;
last_edited_time: string;
created_by: { object: string; id: string };
last_edited_by: { object: string; id: string };
cover: cover;
icon: null;
parent: {
type: string,
database_id: string
},
archived: boolean,
in_trash: boolean,
type: string;
database_id: string;
};
archived: boolean;
in_trash: boolean;
properties: {
Name: { id: string, type: string, title: rich_text[] }
Tags: { id: string, type: string, select:
{
id: string,
name: string,
color: string
}},
Description: { id: string, type: string, rich_text: rich_text[] },
},
url: string,
public_url: string,
title: Array<RichTextItemResponse>,
description: Array<RichTextItemResponse>,
is_inline: boolean,
};
Name: { id: string; type: string; title: rich_text[] };
Tags: {
id: string;
type: "multi_select" | "select"; // Allow either multi_select or select
multi_select?: { // Define multi_select structure
id: string;
name: string;
color: string;
}[];
select?: { // Define select structure
id: string;
name: string;
color: string;
} | null; // Allow select to be null
};
Description: { id: string; type: string; rich_text: rich_text[] };
};
url: string;
public_url: string;
title: Array<RichTextItemResponse>;
description: Array<RichTextItemResponse>;
is_inline: boolean;
};

0 comments on commit 7298a2e

Please sign in to comment.