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
| Name | Type | Description |
|---|---|---|
| [opts] | TemplateOpts | the TemplateOpts |
| [readFormatter] | function | The function(string, readFormatOptions) that will return a formatted string for readingdata using the options.readFormatOptions from TemplateOpts as the formatting options. Typically reads are for HTMLminification 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] | function | The function(string, writeFormatOptions) that will return a formatted string for writtingdata using the options.writeFormatOptions from TemplateOpts as the formatting options. Typically reads are for JSminification 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] | Object | The log for handling logging output |
| [log.debug] | function | A function that will accept debug level logging messages (i.e. debug('some message to log')) |
| [log.info] | function | A function that will accept info level logging messages (i.e. info('some message to log')) |
| [log.warn] | function | A function that will accept warning level logging messages (i.e. warn('some message to log')) |
| [log.error] | function | A 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
| Name | Type | Description |
|---|---|---|
| func | function | A named function that has no external scope dependencies/closures other than those exposedvia templates during rendering |
cachier.unregister(name)
Unregisters a partial template from cache
Async: yes
Parameters
| Name | Type | Description |
|---|---|---|
| name | String | The 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
| Name | Type | Default | Description |
|---|---|---|---|
| name | String | The raw template name (i.e. not from Cachier.readWriteName) | |
| contentOrParams | String | URLSearchParams | Either the partial template content string to register or theURLSearchParams that will be passed during the content read | |
| [extension=options.defaultExtension] | String | options.defaultExtension | Optional 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
| Name | Type | Default | Description |
|---|---|---|---|
| name | String | The raw template name (i.e. not from Cachier.readWriteName) | |
| [params] | URLSearchParams | Any parameters designated during Cachier.registerPartial | |
| [extension=options.defaultExtension] | String | options.defaultExtension | Optional override for a file extension designation for the template, partial or context designated during Cachier.registerPartial |
Returns
Object— A copy of the generated data from Cachier.registerPartial
cachier.register([data], [read], [write]) ⇒ Object
Registers and caches the template, one or more partial templates and/or context JSON.
Async: yes
Parameters
| Name | Type | Description |
|---|---|---|
| [data] | Array.<Object> | The template, partials and/or context to register. |
| data[].name | String | The name that uniquely identifies the template, partial or context |
| [data[].content] | String | The raw content that will be registered. Omit when read === true to read content from cache. |
| [data[].params] | URLSearchParams | The URLSearchParams that will be passed during the content read(ignored when content is specified). |
| [data[].extension] | String | Optional override for a file extension designated for a template, partial or context. |
| [read] | Boolean | When true, an attempt will be made to also Cachier.read the template, partials and context thatdo not have a content property set. |
| [write] | Boolean | When true, an attempt will be made to also Cachier.write the template, partials and context thathave a content property set. |
Returns
Object— An object that contains the registration results:dataThe object that contains the template, partial fragments and/or context that have been registerednameThe name that uniquely identifies the template, partial or contextcontentThe raw content of the template, partial or contextextensionThe template file extension designationparamsThe URLSearchParams passed during the initial content readfromReadA 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
| Name | Type | Description |
|---|---|---|
| name | String | The template name that uniquely identifies the primary template content |
| [template] | String | Boolean | The 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] | URLSearchParams | Any URL search parmeters that will be passed when capturing the primary template and/or context when needed |
| [extension] | String | The file extension designation for the template |
Returns
function— The return function from Sandbox.compile
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
| Name | Type | Description |
|---|---|---|
| name | String | The template name that uniquely identifies the template content |
| [forContent] | Boolean | true to read a template content, false to read the template source code |
| [extension] | String | The file extension designation (only used when forContent is truthy) |
| [params] | URLSearchParams | The 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:
nameThe template name that uniquely identifies the template contentcontentThe template contentextensionThe template file extension designation
Returned module properties:
nameThe template name that uniquely identifies the template contentfuncThe 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
| Name | Type | Description |
|---|---|---|
| name | String | The template name that uniquely identifies the template content |
| data | String | function | The data to write. For content, data should be a string. Otherwise data should be a function ora function string. |
| [forContent] | Boolean | true to read a template content, false to read the template source code |
| [extension] | String | The file extension designation (only used when forContent is truthy) |
| [params] | URLSearchParams | The URLSearchParams to pass for the write (only used when forContent is truthy) |
Returns
function|undefined— Optionally return the compiled/written module function
cachier.options ⇒ TemplateOpts
Returns
TemplateOpts— The template compile options
cachier.metadata ⇒ Object
Access: protected
Returns
Object— The compilation metadata that will be passed into Sandbox.compile
cachier.readFormatter ⇒ function
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 beingoptions.readFormatOptions
cachier.writeFormatter ⇒ function
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 beingoptions.writeFormatOptions
cachier.log ⇒ Object
Returns
Object— The optional log used by the Cachier
cachier.stats ⇒ Object
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
| Name | Type | Default | Description |
|---|---|---|---|
| [all=false] | Boolean | false | Reserved 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
| Name | Type | Description |
|---|---|---|
| optional | TemplateOpts | function | Either 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.operations ⇒ Object | Array.<Object> | function | function | function | Array.<function()>
Returns
Object|Array.<Object>— [operations] One or more operation objects that will handle render-time reads/writesfunction— [operations[].read] The reader is anasync functionresponsible for reading partial template content/modules/etc during render-time when a partial template cannot be found withinincludes. Whenoptions.cacheRawTemplatesis truthy an attempt will be made to add any missing/read partials intostorage.datain 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:
- {String}
nameThe 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. - {String}
pathThe 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. - {String}
extThe 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. - {Boolean}
forContentThe flag indicating that the read is for content. Otherwise, the read is for rendering functions. - {(TemplateOpts | Function(name:String)😗)}
optionalEither the TemplateOpts or a function that takes a single name argument and returns the option value. - {URLSearchParams}
[params]The URLSearchParams that should be used during the read - {Object}
storageThe 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. - {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 beingoptions.readFormatOptionsfor reads andoptions.writeFormatOptionsfor writes. The returned result should be a valid string. - {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. - {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 asoperations[].readand all scoped functions will be available. Can return a rendering function that will prevent further iteration of any subsequentoperations[].writeinvocations.function— [operations[].finish] Anasync functionthat can perform cleanup tasks for a reader. Arguments passed arestorage,optionalandlogas described foroperations[].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 likeasync 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
| Name | Type | Description |
|---|---|---|
| name | String | The name of the template, partial or context that will be converted into a name suitable for a read operation |
| optional | TemplateOpts | function | Either the TemplateOpts or a function that takes a single name argument and returns the option value |
| [params] | URLSearchParams | The parameters that should be used in the converted name |
| store | Object | The storage object that can contain metadata used by naming operations |
| forContent | Boolean | The flag indicating if the converted name is being used to capture partials |
| [extension] | String | The file extension override for the converted name (omit to use the default extension set in the options) |
| forContext | Boolean | The flag indicating if the converted name is being used to capture context |
Returns
String— The full template name
cachier.readWriteNames ⇒ Object | Object | Object
Returns
Object—namersOne or more async functions responsible for formatting template names into a full path name consumable byread/writeoprtationsObject—namers.namerThe default naming functionObject—namers.namerSuperThe 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.readWriteName for parameter details
Cachier.contentURL(name, opts) ⇒ Object
Extracts the proper URL and option name used for a particular template, partial or context
Parameters
| Name | Type | Description |
|---|---|---|
| name | String | The template, partial or context name |
| opts | TemplateOpts | The template options |
Returns
Object— The extracted content that contains aurlproperty and aoptionNamethat 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
| Name | Type | Default | Description |
|---|---|---|---|
| proms | Array.<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] | Boolean | true | When true each promise results/errors will be captured and returned. Otherwise,nothing will be captured |
Returns
Array|undefined— Whencapture === true, the awaited promise results are retuend. When an error occurs, the value at the given index will contain the error instead. Whencapture !== truenothing is captured/returned.