/
markdown-reporter.ts
85 lines (79 loc) · 2.43 KB
/
markdown-reporter.ts
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
85
import path from 'node:path';
import type { ManifestOutput, ManifestDocumentEntry } from './types';
export type ToMarkdownContentOptions = {
baseDir: string;
outputDir: string;
ignoreFragments?: boolean;
};
function createLinkPath(fileName: string, baseDir: string, outputDir: string) {
const displayPath = path.isAbsolute(fileName) ? path.relative(baseDir, fileName) : fileName;
const linkPath = path.isAbsolute(fileName) ? path.relative(outputDir, fileName) : fileName;
return { displayPath, linkPath };
}
function createSection(
sectionName: string,
operationDocs: ManifestDocumentEntry[],
baseDir: string,
outputDir: string,
) {
const h2 = '## ' + sectionName[0].toUpperCase() + sectionName.slice(1);
return (
h2 +
'\n' +
operationDocs
.map(doc => {
const { displayPath, linkPath } = createLinkPath(doc.fileName, baseDir, outputDir);
return `
### ${doc.type !== 'fragment' ? doc.operationName || 'anonymous' : doc.fragmentName}
\`\`\`graphql
${doc.body.trim()}
\`\`\`
From [${displayPath}:${doc.documentStart.line + 1}:${doc.documentStart.character + 1}](${linkPath}#L${
doc.documentStart.line + 1
}-L${doc.documentEnd.line + 1})
`;
})
.join('\n')
);
}
export class MarkdownReporter {
toMarkdownConntent(
manifest: ManifestOutput,
{ ignoreFragments = true, baseDir, outputDir }: ToMarkdownContentOptions,
) {
if (!manifest.documents.length) return null;
const outs = ['# Extracted GraphQL Operations'];
const groupedDocs = {
queries: [],
mutations: [],
subscriptions: [],
fragments: [],
} as { [key: string]: ManifestDocumentEntry[] };
manifest.documents.forEach(doc => {
switch (doc.type) {
case 'query':
groupedDocs.queries.push(doc);
break;
case 'mutation':
groupedDocs.mutations.push(doc);
break;
case 'subscription':
groupedDocs.subscriptions.push(doc);
break;
case 'fragment':
if (!ignoreFragments) groupedDocs.fragments.push(doc);
break;
default:
break;
}
});
Object.entries(groupedDocs).forEach(([name, docs]) => {
if (docs.length) {
outs.push(createSection(name, docs, baseDir, outputDir));
}
});
outs.push('---');
outs.push('Extracted by [ts-graphql-plugin](https://github.com/Quramy/ts-graphql-plugin)');
return outs.join('\n');
}
}