/ packages / string-templates / src / helpers / external.ts
external.ts
 1  // @ts-ignore we don't have types for it
 2  import helpers from "@budibase/handlebars-helpers"
 3  
 4  import { date, difference, duration, durationFromNow } from "./date"
 5  import {
 6    HelperFunctionBuiltin,
 7    EXTERNAL_FUNCTION_COLLECTIONS,
 8  } from "./constants"
 9  import Handlebars from "handlebars"
10  
11  const ADDED_HELPERS = {
12    date,
13    duration,
14    difference,
15    durationFromNow,
16  }
17  
18  export const externalCollections = EXTERNAL_FUNCTION_COLLECTIONS
19  export const addedHelpers = ADDED_HELPERS
20  
21  export function registerAll(handlebars: typeof Handlebars) {
22    for (let [name, helper] of Object.entries(ADDED_HELPERS)) {
23      handlebars.registerHelper(name, helper)
24    }
25    let externalNames = []
26    for (let collection of EXTERNAL_FUNCTION_COLLECTIONS) {
27      // collect information about helper
28      let hbsHelperInfo = helpers[collection]()
29      for (let entry of Object.entries(hbsHelperInfo)) {
30        const name = entry[0]
31        // skip built-in functions and ones seen already
32        if (
33          HelperFunctionBuiltin.indexOf(name) !== -1 ||
34          externalNames.indexOf(name) !== -1
35        ) {
36          continue
37        }
38        externalNames.push(name)
39      }
40      // attach it to our handlebars instance
41      helpers[collection]({
42        handlebars,
43      })
44    }
45    // add date external functionality
46    externalHelperNames = externalNames.concat(Object.keys(ADDED_HELPERS))
47  }
48  
49  export function unregisterAll(handlebars: typeof Handlebars) {
50    for (let name of Object.keys(ADDED_HELPERS)) {
51      handlebars.unregisterHelper(name)
52    }
53    for (let name of externalHelperNames) {
54      handlebars.unregisterHelper(name)
55    }
56    externalHelperNames = []
57  }
58  
59  export let externalHelperNames: any[] = []