Files
smartfm/ts/index.ts
T

46 lines
1.2 KiB
TypeScript
Raw Normal View History

2019-09-04 14:13:42 +02:00
import grayMatter from 'gray-matter';
2016-11-13 23:11:49 +01:00
export type TFrontMatter = 'yaml' | 'json';
2016-11-13 23:11:49 +01:00
export interface ISmartfmContructorOptions {
fmType: TFrontMatter;
2016-11-13 23:11:49 +01:00
}
/**
* class smartfm handles frontmatter
*/
export class Smartfm {
fmType: TFrontMatter;
2017-03-11 22:34:28 +01:00
constructor(optionsArg: ISmartfmContructorOptions) {
this.fmType = optionsArg.fmType;
2017-03-11 22:34:28 +01:00
}
/**
* add frontmatter to a string
*/
stringify(bodyString: string, frontmatterData: Record<string, unknown>): string {
return grayMatter.stringify(bodyString, frontmatterData);
2017-03-11 22:34:28 +01:00
}
/**
* parse a string that has frontmatter attached, YAML notation
*/
parse(stringToParse: string): grayMatter.GrayMatterFile<string> {
return grayMatter(stringToParse);
2017-03-11 22:34:28 +01:00
}
2019-09-04 15:45:18 +02:00
/**
* parse from comments
2019-09-04 15:45:18 +02:00
*/
parseFromComments(commentStart: string, stringToParse: string): grayMatter.GrayMatterFile<string> {
const diffFunc = (diffMe: string, diffBy: string): string => diffMe.split(diffBy).join('');
2019-09-04 15:45:18 +02:00
let lines = stringToParse.split('\n');
lines = lines.map((line) => {
2019-09-04 15:45:18 +02:00
return diffFunc(line, commentStart);
});
const cleanedString = lines.join('\n');
return this.parse(cleanedString);
}
2016-11-13 23:11:49 +01:00
}