All files / apps/huella-legal/layers/articles/server/mappers citation.ts

100% Statements 19/19
100% Branches 9/9
100% Functions 7/7
100% Lines 19/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                            4x 4x   4x 11x 55x     11x     4x 12x   4x 12x 12x   12x     4x 15x   15x     4x         12x 15x               12x          
import { JOURNAL_LOCALE, LONG_DATE } from "../../../../i18n/dateFormats";
import type { ArticleSummary } from "../../shared/types/ArticleSummary";
import type { Citation } from "../../shared/types/Citation";
import type { Journal } from "../../shared/types/Journal";
 
interface Source {
    authors: string[];
    title: string;
    number?: string;
    date?: Date;
    journal: Journal;
    permalink: string;
}
 
const DATE = new Intl.DateTimeFormat(JOURNAL_LOCALE, LONG_DATE);
const LIST = new Intl.ListFormat(JOURNAL_LOCALE, { type: "conjunction" });
 
const apaDate = (date: Date): string => {
    const { year, day, month } = Object.fromEntries(
        DATE.formatToParts(date).map(({ type, value }) => [type, value]),
    );
 
    return `${year}, ${day} de ${month}`;
};
 
const apa7 = ({ authors, title, date, journal, permalink }: Source): string =>
    `${LIST.format(authors)} (${date ? apaDate(date) : "s. f."}). ${title}. ${journal.name}. ${permalink}`;
 
const journalStyle = ({ authors, title, number, date, journal, permalink }: Source): string => {
    const numbered = number ? `, n.º ${number}` : "";
    const published = date ? `, ${DATE.format(date)}` : "";
 
    return `${authors.join("; ").toLocaleUpperCase(JOURNAL_LOCALE)}, «${title}», ${journal.name}${numbered}${published}. ISSN ${journal.issn}. Disponible en: ${permalink}`;
};
 
const invertName = (name: string): string => {
    const [given = "", ...surnames] = name.trim().split(/\s+/);
 
    return `${surnames.join(" ")}, ${given.charAt(0)}.`;
};
 
export const toCitations = (
    { authors, title, number, publishedAt }: ArticleSummary,
    journal: Journal,
    permalink: string,
): Citation[] => {
    const source: Source = {
        authors: authors.map(({ name }) => invertName(name)),
        title,
        number,
        date: publishedAt ? new Date(publishedAt) : undefined,
        journal,
        permalink,
    };
 
    return [
        { style: "APA 7", text: apa7(source) },
        { style: journal.name, text: journalStyle(source) },
    ];
};