Skip to content

Cachier

new Cachier([opts], [readFormatter], [writeFormatter], [log])

The default persistence cache manager that uses a simple object mapping for Cachier.read/Cachier.write operations. All caching is maintained in-memory. Template, partial and context Cachier.read operations use the standard Fetch API in supported Node.js and browser runtimes to capture partial template content. Compiled template Cachier.read operations are handled via dynamic import/require (if used). Cachier.write operations are typically written to memory, but can also be configured to POST template, partials and/or context over HTTP/S.

Parameters

NameTypeDescription
[opts]TemplateOptsthe TemplateOpts
[readFormatter]functionThe function(string, readFormatOptions) that will return a formatted string for reading
data using the options.readFormatOptions from TemplateOpts as the formatting options. Typically reads are for HTML
minification and/or beautifying. NOTE: Use with caution as syntax errors may result depending on the formatter used and the
complexity of the data being formatted!
[writeFormatter]functionThe function(string, writeFormatOptions) that will return a formatted string for writting
data using the options.writeFormatOptions from TemplateOpts as the formatting options. Typically reads are for JS
minification and/or beautifying. NOTE: Use with caution as syntax errors may result depending on the formatter used and the
complexity of the data being formatted!
[log]ObjectThe log for handling logging output
[log.debug]functionA function that will accept debug level logging messages (i.e. debug('some message to log'))
[log.info]functionA function that will accept info level logging messages (i.e. info('some message to log'))
[log.warn]functionA function that will accept warning level logging messages (i.e. warn('some message to log'))
[log.error]functionA function that will accept error level logging messages (i.e. error('some message to log'))

cachier.registerHelper(func)

Registers a directive function that can be used within template interpolations

Parameters

NameTypeDescription
funcfunctionA named function that has no external scope dependencies/closures other than those exposed
via templates during rendering

cachier.unregister(name)

Unregisters a partial template from cache

Async: yes

Parameters

NameTypeDescription
nameStringThe template name that uniquely identifies the template content

cachier.registerPartial(name, contentOrParams, [extension=options.defaultExtension])String

Registers and stores a partial template in-memory. Use Cachier.register to write partials to cache (Cachier)

Async: yes

Parameters

NameTypeDefaultDescription
nameStringThe raw template name (i.e. not from Cachier.readWriteName)
contentOrParamsString | URLSearchParamsEither the partial template content string to register or the
URLSearchParams that will be passed during the content read
[extension=options.defaultExtension]Stringoptions.defaultExtensionOptional override for a file extension designation for the partial

Returns

  • String — The partial content

cachier.getRegistered(name, [params], [extension=options.defaultExtension])Object

Retrieves a template, partial or context that resides in-memory.

Async: yes

Parameters

NameTypeDefaultDescription
nameStringThe raw template name (i.e. not from Cachier.readWriteName)
[params]URLSearchParamsAny parameters designated during Cachier.registerPartial
[extension=options.defaultExtension]Stringoptions.defaultExtensionOptional override for a file extension designation
for the template, partial or context designated during Cachier.registerPartial

Returns

cachier.register([data], [read], [write])Object

Registers and caches the template, one or more partial templates and/or context JSON.

Async: yes

Parameters

NameTypeDescription
[data]Array.<Object>The template, partials and/or context to register.
data[].nameStringThe name that uniquely identifies the template, partial or context
[data[].content]StringThe raw content that will be registered. Omit when read === true to read content from cache.
[data[].params]URLSearchParamsThe URLSearchParams that will be passed during the content read
(ignored when content is specified).
[data[].extension]StringOptional override for a file extension designated for a template, partial or context.
[read]BooleanWhen true, an attempt will be made to also Cachier.read the template, partials and context that
do not have a content property set.
[write]BooleanWhen true, an attempt will be made to also Cachier.write the template, partials and context that
have a content property set.

Returns

  • Object — An object that contains the registration results:

  • data The object that contains the template, partial fragments and/or context that have been registered

    • name The name that uniquely identifies the template, partial or context
    • content The raw content of the template, partial or context
    • extension The template file extension designation
    • params The URLSearchParams passed during the initial content read
    • fromRead A flag that indicates that the data was set from a read operation

cachier.compile(name, [template], [params], [extension])function

Compiles a locally sandboxed async template rendering function and when applicable, stores the function in cache

Async: yes

Parameters

NameTypeDescription
nameStringThe template name that uniquely identifies the primary template content
[template]String | BooleanThe raw template content, true to read from cache before compilation.
Omit to load the template content from cache when the returned rendering function is called.
[params]URLSearchParamsAny URL search parmeters that will be passed when capturing the primary template and/or context when needed
[extension]StringThe file extension designation for the template

Returns

cachier.read(name, [forContent], [extension], [params])Object

Reads either template content or template code from internal cache. When options.partialsURL is set to an HTTP/S URL and the read is for partial content, a GET call to the standard Fetch API is made. The partial name will be appended to options.partialsURL (e.g. https://example.com/some/id.html where some/id.html is the the partial's Cachier.readWriteName and options.partialsURL is set to https://example.com). When options.partialsURL is omitted reading of template partial content will be limited to reading from memory. Compiled template source code is alwaysread from memory only.

Async: yes

Parameters

NameTypeDescription
nameStringThe template name that uniquely identifies the template content
[forContent]Booleantrue to read a template content, false to read the template source code
[extension]StringThe file extension designation (only used when forContent is truthy)
[params]URLSearchParamsThe URLSearchParams to pass for the read (only used when forContent is truthy)

Returns

  • Object — An object read from cache that contains either the template content or module.

Returned template content properties:

  • name The template name that uniquely identifies the template content
  • content The template content
  • extension The template file extension designation

Returned module properties:

  • name The template name that uniquely identifies the template content
  • func The module function generated from the code

cachier.write(name, data, [forContent], [extension], [params])function | undefined

Writes either template content or template code from internal cache. When options.partialsURL is set to an HTTP/S URL and the write is for partial content, a POST call to the standard Fetch API is made. The partial name will be appended to options.partialsURL (e.g. https://example.com/some/id.html where some/id.html is the the partial's Cachier.readWriteName and options.partialsURL is set to https://example.com). When options.partialsURL is omitted writting of template partial content will be limited to writes to memory. Compiled template source code is alwayswritten to memory only.

Async: yes

Parameters

NameTypeDescription
nameStringThe template name that uniquely identifies the template content
dataString | functionThe data to write. For content, data should be a string. Otherwise data should be a function or
a function string.
[forContent]Booleantrue to read a template content, false to read the template source code
[extension]StringThe file extension designation (only used when forContent is truthy)
[params]URLSearchParamsThe URLSearchParams to pass for the write (only used when forContent is truthy)

Returns

  • function | undefined — Optionally return the compiled/written module function

cachier.optionsTemplateOpts

Returns

  • TemplateOpts — The template compile options

cachier.metadataObject

Access: protected

Returns

  • Object — The compilation metadata that will be passed into Sandbox.compile

cachier.readFormatterfunction

Returns

  • function — The read formatting function that takes 1 or 2 arguments with the first being the content that will be formatted and the second being options.readFormatOptions

cachier.writeFormatterfunction

Returns

  • function — The write formatting function that takes 1 or 2 arguments with the first being the content that will be formatted and the second being options.writeFormatOptions

cachier.logObject

Returns

  • Object — The optional log used by the Cachier

cachier.statsObject

Returns a snapshot of cache activity and current cache size.

Returns

  • Object — Cache statistics.

cachier.resetStats()Object

Resets cumulative cache counters while retaining current entry and byte totals.

Returns

  • Object — The reset cache statistics.

cachier.clearMemory()

Clears in-memory template content and compiled renderers.

Async: yes

cachier.clear([all=false])

Clears the cache.

Async: yes

Parameters

NameTypeDefaultDescription
[all=false]BooleanfalseReserved for persistence implementations that can clear unassociated cache instances.

cachier.close()

Releases in-memory cache resources. Persistence implementations may extend this method to close additional resources.

Async: yes

cachier.modules(optional)Object

Async: yes

Parameters

NameTypeDescription
optionalTemplateOpts | functionEither the TemplateOpts or a function that takes a
single name argument and returns the option value

Returns

  • Object — The object that contains the modules used by the Cachier implementation

cachier.operationsObject | Array.<Object> | function | function | function | Array.<function()>

Returns

  • Object | Array.<Object> — [operations] One or more operation objects that will handle render-time reads/writes
  • function — [operations[].read] The reader is an async function responsible for reading partial template content/modules/etc during render-time when a partial template cannot be found within includes. When options.cacheRawTemplates is truthy an attempt will be made to add any missing/read partials into storage.data in order to prevent unnecessary template partial reads for repeated includes. Read functions should not reference any external scope other than the global object space. The following arguments will be passed:
  1. {String} name The name of the partial that will be read. The read function may be invoked without a name parameter when the intent is to capture all partials in a single read opteration that will be included.
  2. {String} path The path to the partial that will be read. The read function may be invoked without a path parameter when the intent is to capture all partials in a single read opteration that will be included.
  3. {String} ext The path file extension to the partial that will be read. The read function may be invoked without an ext parameter when the intent is to capture all partials in a single read opteration that will be included.
  4. {Boolean} forContent The flag indicating that the read is for content. Otherwise, the read is for rendering functions.
  5. {(TemplateOpts | Function(name:String)😗)} optional Either the TemplateOpts or a function that takes a single name argument and returns the option value.
  6. {URLSearchParams} [params] The URLSearchParams that should be used during the read
  7. {Object} storage The storage object that can contain metadata for read operations and should contain a data object that stores each of the read paratial template content/metadata.
  8. {Function} [formatter] The function that will format reads/writes during include discovery (if any). The formatting function takes 1 or 2 arguments with the first being the content that will be formatted and the second being options.readFormatOptions for reads and options.writeFormatOptions for writes. The returned result should be a valid string.
  9. {Boolean} [close] A flag indicating whether or not any resources used during the read should be closed/cleaned up after the read completes. Closure may be dependent upon the policy set on the options.
  10. {Object} [log] A logger that can contain functions for each of the following: error/warn/info/debug.

Read functions can return the partial template content and/or it can be set on the storage.data. Returning true will stop any further rendering from processing resulting in the rendering function returning a blank string.

  • function — [operations[].write] The write function that will be used for writting newly discovered template sources. Accepts the same arguments as operations[].read and all scoped functions will be available. Can return a rendering function that will prevent further iteration of any subsequent operations[].write invocations.
  • function — [operations[].finish] An async function that can perform cleanup tasks for a reader. Arguments passed are storage, optional and log as described for operations[].read.
  • Array.<function()> — [operations[].scopes] Zero or more functions that will be in scope when the read function is called. Scoped functions can assit with complex read/write operations that can benefit from separate supporting functions. For example, [myFunc(){}] could be referenced like async function myReader(){ myFunc(); ... }.

cachier.readWriteName(name, optional, [params], store, forContent, [extension], forContext)String

Converts template names into a full path name consumable by read/write oprtations. Each function from Cachier.readWriteNames will be executed in order using the same arguments as Cachier.readWriteName as well as an additional last agument being the return value from the previous function invocation.

Async: yes

Parameters

NameTypeDescription
nameStringThe name of the template, partial or context that will be converted into a name suitable for a read operation
optionalTemplateOpts | functionEither the TemplateOpts or a function that takes a single name
argument and returns the option value
[params]URLSearchParamsThe parameters that should be used in the converted name
storeObjectThe storage object that can contain metadata used by naming operations
forContentBooleanThe flag indicating if the converted name is being used to capture partials
[extension]StringThe file extension override for the converted name (omit to use the default extension set in the options)
forContextBooleanThe flag indicating if the converted name is being used to capture context

Returns

  • String — The full template name

cachier.readWriteNamesObject | Object | Object

Returns

  • Objectnamers One or more async functions responsible for formatting template names into a full path name consumable by read/write oprtations
  • Objectnamers.namer The default naming function
  • Objectnamers.namerSuper The naming function to use when a Cachier.operations function throws an error. The next reader called in the Cachier.operations list will use the name generated by this reader.

See also

Cachier.contentURL(name, opts)Object

Extracts the proper URL and option name used for a particular template, partial or context

Parameters

NameTypeDescription
nameStringThe template, partial or context name
optsTemplateOptsThe template options

Returns

  • Object — The extracted content that contains a url property and a optionName that describes the option used for the URL

Cachier.waiter(proms, [errMsg='One or more pomises failed'], [capture=true])Array | undefined

Waits for promises to finish and throws commulative errors into a single meaningful stack while continuing to process subsequent promises in the array. When an error is thrown and capture === true, it will also contain a results property that contains either each result from an awaited promise or an error thrown when waiting for the promise to complete.

Async: yes

Parameters

NameTypeDefaultDescription
promsArray.<Promise>The promises to wait for.
[errMsg='One or more pomises failed']String'One or more pomises failed'The message to use when any errors occur.
[capture=true]BooleantrueWhen true each promise results/errors will be captured and returned. Otherwise,
nothing will be captured

Returns

  • Array | undefined — When capture === true, the awaited promise results are retuend. When an error occurs, the value at the given index will contain the error instead. When capture !== true nothing is captured/returned.

Released under the MIT License.