aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils/helpers/server/projects.ts
blob: 3f822fee48aecc4afcbb3f3953623dc9e0de1a75 (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
73
74
75
76
77
78
79
80
81
82
83
84
import { readdir } from 'fs/promises';
import { join } from 'path';
import type { StaticImageData } from 'next/image';
import type { MDXProjectMeta, Project, ProjectPreview } from '../../../types';
import { ROUTES } from '../../constants';

/**
 * Retrieve all the projects filename.
 *
 * @returns {Promise<string[]>} An array of filenames.
 */
export const getProjectFilenames = async (): Promise<string[]> => {
  const projectsDir = join(process.cwd(), 'src/content/projects');
  const filenames = await readdir(projectsDir);

  return filenames.map((filename) => filename.replace(/\.mdx$/, ''));
};

/**
 * Retrieve the data of a project by filename.
 *
 * @param {string} filename - The project filename.
 * @returns {Promise<ProjectPreview>} A ProjectPreview object.
 */
export const getProjectData = async (filename: string): Promise<Project> => {
  try {
    const {
      meta,
    }: {
      meta: MDXProjectMeta;
    } = await import(`../../../content/projects/${filename}.mdx`);

    const { intro, title, ...projectMeta } = meta;
    const cover: StaticImageData = (
      await import(`../../../../public/projects/${filename}.jpg`)
    ).default;

    return {
      id: filename,
      intro,
      meta: {
        ...projectMeta,
        // Dynamic import source does not work so I use it only to get sizes
        cover: {
          alt: `${title} image`,
          height: cover.height,
          src: `/projects/${filename}.jpg`,
          width: cover.width,
          title,
        },
      },
      slug: `${ROUTES.PROJECTS}/${filename}`,
      title,
    };
  } catch (err) {
    console.error(err);
    throw err;
  }
};

/**
 * Method to sort an array of projects by publication date.
 *
 * @param {ProjectPreview} a - A single project.
 * @param {ProjectPreview} b - A single project.
 * @returns {number} The result used by Array.sort() method: 1 || -1 || 0.
 */
const byPublicationDate = (a: ProjectPreview, b: ProjectPreview) => {
  if (a.meta.dates.publication < b.meta.dates.publication) return 1;
  if (a.meta.dates.publication > b.meta.dates.publication) return -1;
  return 0;
};

/**
 * Retrieve all projects in content folder sorted by publication date.
 *
 * @returns {Promise<ProjectPreview[]>} An array of projects.
 */
export const getAllProjects = async (): Promise<ProjectPreview[]> => {
  const filenames = await getProjectFilenames();
  const projects = await Promise.all(filenames.map(getProjectData));

  return [...projects].sort(byPublicationDate);
};