Skip to content

Instantly share code, notes, and snippets.

@osk
Last active April 25, 2017 14:21
Show Gist options
  • Save osk/1a469b0f25865d33692b059f15d3eeb3 to your computer and use it in GitHub Desktop.
Save osk/1a469b0f25865d33692b059f15d3eeb3 to your computer and use it in GitHub Desktop.
Patches prismic.io module for better dev experience
import prismic from 'prismic.io';
/**
* Patches the `prismic.io` module to provide null checks on data that might
* be there or not. You can then safely call the API without running into nulls,
* but you still have to provide some fallback data, e.g.
*
* ```
* const html = data.getStructuredText('key').asHtml() || 'defaultValue';
* const bool = data.getBoolean('nonExistantKey') || false;
* ```
*
* @param {object} obj Object prototype to patch,
* e.g. `prismic.Document.prototype`
* @param {string} method Method name to patch, e.g. `getStructuredText`
* @param {Object} DefaultConstructor Constructor to instantiate if no result
* from API, defaults to null
*/
function patch(obj, method, DefaultConstructor = null) {
const proto = Object.getPrototypeOf(obj);
const original = proto[method];
proto[method] = function nullCheckPatched(...args) {
let result = null;
try {
result = original.apply(this, args);
} catch (e) {
// empty
}
if (result === null) {
if (DefaultConstructor instanceof Object) {
return new DefaultConstructor();
}
return null;
}
return result;
};
}
// Can't use the objects from prismic for links
function NullLink() {
this.asHtml = function asHtml() { return ''; };
this.url = function url() { return ''; };
this.asText = function asText() { return ''; };
}
patch(prismic.Document.prototype, 'getStructuredText', prismic.Fragments.StructuredText);
patch(prismic.Document.prototype, 'getImage', prismic.Fragments.ImageView);
patch(prismic.Document.prototype, 'getBoolean');
patch(prismic.Document.prototype, 'getLink', NullLink);
// and all the calls you want to patch
export default prismic;
@osk
Copy link
Author

osk commented Apr 25, 2017

This patches the prismic.io module to make handling null sane, ain't nobody got time for null checking all the time!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment