UNPKG

2.5 kBJavaScriptView Raw
1// packages
2const { load } = require('archieml');
3const { google: googleApisInstance } = require('googleapis');
4
5function readParagraphElement(element) {
6 // pull out the text
7 const textRun = element.textRun;
8
9 // sometimes it's not there, skip this all if so
10 if (textRun) {
11 // sometimes the content isn't there, and if so, make it an empty string
12 const content = textRun.content || '';
13
14 // step through optional text styles to check for an associated URL
15 if (!textRun.textStyle) return content;
16 if (!textRun.textStyle.link) return content;
17 if (!textRun.textStyle.link.url) return content;
18
19 // if we got this far there's a URL key, grab it...
20 const url = textRun.textStyle.link.url;
21
22 // ...but sometimes that's empty too
23 if (url) {
24 return `<a href="${url}">${content}</a>`;
25 } else {
26 return content;
27 }
28 } else {
29 return '';
30 }
31}
32
33function readElements(document) {
34 // prepare the text holder
35 let text = '';
36
37 // check if the body key and content key exists, and give up if not
38 if (!document.body) return text;
39 if (!document.body.content) return text;
40
41 // loop through each content element in the body
42 document.body.content.forEach(element => {
43 if (element.paragraph) {
44 // get the paragraph within the element
45 const paragraph = element.paragraph;
46
47 // this is a list
48 const needsBullet = paragraph.bullet != null;
49
50 if (paragraph.elements) {
51 // all values in the element
52 const values = paragraph.elements;
53
54 values.forEach((value, idx) => {
55 // we only need to add a bullet to the first value, so we check
56 const isFirstValue = idx === 0;
57
58 // prepend an asterisk if this is a list item
59 const prefix = needsBullet && isFirstValue ? '* ' : '';
60
61 // concat the text
62 text += `${prefix}${readParagraphElement(value)}`;
63 });
64 }
65 }
66 });
67
68 return text;
69}
70
71async function docToArchieML({
72 auth,
73 client,
74 documentId,
75 google = googleApisInstance,
76}) {
77 // create docs client if not provided
78 if (!client) {
79 client = google.docs({
80 version: 'v1',
81 auth,
82 });
83 }
84
85 // pull the data out of the doc
86 const { data } = await client.documents.get({
87 documentId,
88 });
89
90 // convert the doc's content to text ArchieML will understand
91 const text = readElements(data);
92
93 // pass text to ArchieML and return results
94 return load(text);
95}
96
97module.exports = { docToArchieML };