summaryrefslogtreecommitdiffstats
path: root/src/utils/helpers/projects.ts
blob: 3736242e02a8454d7d0a710435e1e2289db0c106 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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);
};