nuxt-flagsmith
Version:
Nuxt.js module to use Flagsmith toggle feature services
93 lines (84 loc) • 2.96 kB
JavaScript
;
const consola = require('consola');
const colorette = require('colorette');
const axios = require('axios');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
const consola__default = /*#__PURE__*/_interopDefaultLegacy(consola);
const axios__default = /*#__PURE__*/_interopDefaultLegacy(axios);
var name = "nuxt-flagsmith";
var version = "1.0.1";
const printTitle = (badgeMessages) => {
badgeMessages.push(colorette.white(colorette.bold("Feature Flags")));
};
const printFeatureFlag = (feature, badgeMessages) => {
let nameFeature = colorette.red(colorette.bold(`${feature.name} \u2717 (Disabled): `)) + colorette.red(feature.description);
if (feature.enabled) {
nameFeature = colorette.green(colorette.italic(colorette.bold(`${feature.name} \u2713 (Enabled): `) + colorette.green(feature.description)));
}
badgeMessages.push(`${colorette.white(colorette.bold("-"))} ${nameFeature}`);
};
const printChalk = (feature, options) => {
if (!feature) {
return;
}
const badgeMessages = options.cli.badgeMessages;
printTitle(badgeMessages);
feature.forEach((f) => printFeatureFlag(f, badgeMessages));
badgeMessages.push("");
};
const logger$1 = consola__default["default"].withTag("nuxt:flagsmith");
const fetchData = async (host, environmentId) => {
try {
const { data } = await axios__default["default"].get(`${host}/api/v1/flags/`, {
headers: {
"X-Environment-Key": environmentId
}
});
return data;
} catch (e) {
logger$1.error(`Cannot fetch data from host ${host}`);
}
};
const fetchData$1 = (host, environmentId) => {
if (!host || !environmentId) {
return void 0;
}
return fetchData(host, environmentId).then((res) => res.map((item) => ({
id: item.feature.id,
name: item.feature.name,
enabled: item.enabled
}))).catch(() => void 0);
};
const { resolve, join } = require("path");
const logger = consola__default["default"].withTag("nuxt:flagsmith");
const CONFIG_KEY = "flagsmith";
const nuxtModule = async function(moduleOptions) {
const options = {
...this.options["flagsmith-module"],
...this.options[CONFIG_KEY],
...moduleOptions
};
const defaultHost = "https://api.flagsmith.com";
if (!options.host) {
options.host = defaultHost;
}
if (!options.environmentId) {
logger.warn("environmentId option is not set");
}
const { host, environmentId } = options;
const featureFlags = await fetchData$1(host, environmentId);
printChalk(featureFlags, this.nuxt.options);
this.addTemplate({
src: resolve(__dirname, "../templates/FlagsmithFlags.js"),
fileName: join("FlagsmithFlags.js")
});
this.addPlugin({
src: resolve(__dirname, "../templates/plugin.ts"),
fileName: join("flagsmith.js"),
options: {
data: JSON.stringify(featureFlags)
}
});
};
nuxtModule.meta = { name, version };
module.exports = nuxtModule;