summaryrefslogtreecommitdiffstats
path: root/src/utils
diff options
context:
space:
mode:
authorArmand Philippot <git@armandphilippot.com>2022-01-20 11:57:16 +0100
committerArmand Philippot <git@armandphilippot.com>2022-01-20 11:57:16 +0100
commitf5ba1046b13acd239c472e361f345902937662fb (patch)
treed2468fa51f3d2f9dda61eb9cdf6594ad8e618352 /src/utils
parent08855874397399459b281f6f0506fa5e91cdfdc0 (diff)
chore: add a page for projects
Diffstat (limited to 'src/utils')
-rw-r--r--src/utils/helpers/projects.ts72
1 files changed, 72 insertions, 0 deletions
diff --git a/src/utils/helpers/projects.ts b/src/utils/helpers/projects.ts
new file mode 100644
index 0000000..3736242
--- /dev/null
+++ b/src/utils/helpers/projects.ts
@@ -0,0 +1,72 @@
+import { Project, ProjectMeta } from '@ts/types/app';
+import { readdirSync } from 'fs';
+import path from 'path';
+
+/**
+ * Retrieve the projects data from filenames.
+ * @param {string[]} filenames - An array of filenames.
+ * @returns {Promise<Project[]>} An array of projects.
+ */
+const getProjectsWithMeta = async (filenames: string[]): Promise<Project[]> => {
+ return Promise.all(
+ filenames.map(async (filename) => {
+ const id = filename.replace(/\.mdx$/, '');
+
+ try {
+ const {
+ image,
+ intro,
+ meta,
+ }: { image: string; intro: string; meta: ProjectMeta } = await import(
+ `../../content/projects/${filename}`
+ );
+
+ const projectMeta: ProjectMeta = meta
+ ? meta
+ : {
+ title: '',
+ publishedOn: '',
+ updatedOn: '',
+ license: '',
+ };
+ const projectIntro = intro ? intro : '';
+ const projectCover = image ? image : '';
+
+ return {
+ id,
+ cover: projectCover,
+ intro: projectIntro,
+ meta: projectMeta,
+ slug: id,
+ };
+ } catch (err) {
+ console.error(err);
+ throw err;
+ }
+ })
+ );
+};
+
+/**
+ * Method to sort an array of projects by publication date.
+ * @param {Project} a - A single project.
+ * @param {Project} b - A single project.
+ * @returns The result used by Array.sort() method: 1 || -1 || 0.
+ */
+const sortProjectByPublicationDate = (a: Project, b: Project) => {
+ if (a.meta.publishedOn < b.meta.publishedOn) return 1;
+ if (a.meta.publishedOn > b.meta.publishedOn) return -1;
+ return 0;
+};
+
+/**
+ * Retrieve all projects in content folder sorted by publication date.
+ * @returns {Promise<Project[]>} An array of projects.
+ */
+export const getSortedProjects = async (): Promise<Project[]> => {
+ const projectsDirectory = path.join(process.cwd(), 'src/content/projects');
+ const filenames = readdirSync(projectsDirectory);
+ const projects = await getProjectsWithMeta(filenames);
+
+ return [...projects].sort(sortProjectByPublicationDate);
+};