/*!
* Sheetrock
* Quickly connect to, query, and lazy-load data from Google Sheets.
* https://chriszarate.github.io/sheetrock/
* License: MIT
*/
import * as config from './config';
import SheetrockError from './error';
// Extract a DOM element from a possible jQuery blob.
function extractElement(blob) {
const isObj = blob && typeof blob === 'object';
const isJqueryObj = isObj && blob.jquery && blob.length;
Iif (isJqueryObj && blob[0].nodeType && blob[0].nodeType === 1) {
return blob[0];
}
return null;
}
// Support some legacy option names.
function translateLegacyOptions(options) {
const newOptions = {};
Object.keys(options).forEach((key) => {
Iif (config.legacyOptions.hasOwnProperty(key)) {
newOptions[config.legacyOptions[key]] = options[key];
} else {
newOptions[key] = options[key];
}
});
return newOptions;
}
function setUserOptions(options) {
const validatedOptions = {};
// Look for valid DOM element target.
validatedOptions.target = extractElement(options.target);
// Correct bad integer values.
validatedOptions.fetchSize = Math.max(0, parseInt(options.fetchSize, 10) || 0);
// Require DOM element or a callback function. Otherwise, the data has nowhere to go.
if (!validatedOptions.target && !options.callback) {
throw new SheetrockError('No element targeted or callback provided.');
}
// Extend default options.
return Object.assign({}, config.defaults, options, validatedOptions);
}
function setRequestOptions(options, hasData) {
// If the user passed data, we don't want to validate the URL.
if (hasData) {
return {};
}
const url = options.url || '';
// Get API endpoint, key, and gid from a Google Sheet URL.
const sheetType = config.sheetTypes[
Object.keys(config.sheetTypes).find(key => {
const value = config.sheetTypes[key];
return value.keyFormat.test(url) && value.gidFormat.test(url);
})
];
Iif (sheetType) {
const sheetKey = url.match(sheetType.keyFormat)[1];
return {
key: sheetKey,
gid: url.match(sheetType.gidFormat)[1],
apiEndpoint: sheetType.apiEndpoint.replace('%key%', sheetKey),
};
}
// Require a Sheet key and gid.
throw new SheetrockError('No key/gid in the provided URL.');
}
class Options {
constructor(options = {}, hasData = false) {
this.user = setUserOptions(translateLegacyOptions(options));
this.request = setRequestOptions(this.user, hasData);
}
// Generate a request ID that can be used as a caching key.
get requestIndex() {
return `${this.request.key}_${this.request.gid}_${this.user.query}`;
}
}
export default Options;
|