Publican.lib utility functions

576 words, 3-minute read

The util library provides utility functions you can use in your Publican configuration file or elsewhere. You can import the functions you need from publican.lib:

publican.config.js excerpt

// Publican configuration
import { env, apiFetch } from 'publican.lib';

console.log( env('NODE_ENV') );

or from publican.lib/util:

publican.config.js excerpt

// Publican configuration
import { env, apiFetch } from 'publican.lib/util';

console.log( env('NODE_ENV') );

Or you can import all functions:

publican.config.js excerpt

// Publican configuration
import * as libUtil from 'publican.lib/util';

console.log( libUtil.env('NODE_ENV') );

env(name [, default]) #

Fetches an environment variable, converts to a numeric value where possible, and reverts to a default when necessary:

// isDev true when NODE_ENV is explicitly set to "development"
const isDev = (env('NODE_ENV', 'production') === 'development');

apiFetch(object) #

Make an HTTP request, format the response, and cache when required. The object parameter properties:

The function returns an object with the following properties:

Example that caches a response for 10 minutes:

const res = await apiFetch({
  uri: 'https://api.site.com/call',
  authKey: 'mytoken',
  cacheDir: './_cache/'
});

if (res.ok) console.log(res.body);

normalize(str) #

Normalizes a string to lowercase characters with hyphens in place of spaces:

normalize(' Publican Library 1 ');
// returns "publican-library-1"

strHash(str) #

Hashes a string to an MD5 hex value.

strHash('Publican Library');

apiFetch() uses a hash of the HTTP URI, headers, and body as a filename when caching response data.

cspScript(code [, type]) #

When passed client-side JavaScript code in a string and an optional type attribute, cspScript() returns an object with the properties:

publican.config.js excerpt

const tacs.myScript = cspScript('alert("Hello!")');

You can use this in a template:

htmlhead.html example

<!-- Content Security Policy -->
<meta http-equiv="Content-Security-Policy" content="
default-src 'self';
script-src 'self' 'sha256-${ tacs.myScript.hash }';
">

<!-- add inline <script> -->
${ tacs.myScript.code }

sortBy(prop) #

A function to sort an array using property values, e.g.

const obj = [
  { name: "Craig" },
  { name: "Bob" },
  { name: "Anne" },
].sort( sortBy('name') );
// in order: Anne, Bob, Craig

fileInfo(path) #

When passed a file path, it returns an object with the following properties:

Returns an object with file information:

const
  file = './somefile.txt',
  info = fileInfo(file);

if (info.exists) {

  console.log(file);

  if (info.isFile) {
    console.log('is a file');
  }
  else if (info.isDir) {
    console.log('is a directory');
  }

}