@api-platform/client-generator
Version:
Generate apps built with Next, Nuxt, Quasar, React, React Native, Vue or Vuetify for any API documented using Hydra or OpenAPI
376 lines (330 loc) • 20.7 kB
JavaScript
import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import _typeof from "@babel/runtime/helpers/typeof";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _classCallCheck from "@babel/runtime/helpers/classCallCheck";
import _createClass from "@babel/runtime/helpers/createClass";
import _inherits from "@babel/runtime/helpers/inherits";
import _possibleConstructorReturn from "@babel/runtime/helpers/possibleConstructorReturn";
import _getPrototypeOf from "@babel/runtime/helpers/getPrototypeOf";
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
import chalk from "chalk";
import handlebars from "handlebars";
import hbh_comparison from "handlebars-helpers/lib/comparison.js";
import hbh_array from "handlebars-helpers/lib/array.js";
import hbh_string from "handlebars-helpers/lib/string.js";
import BaseGenerator from "./BaseGenerator.js";
var _default = /*#__PURE__*/function (_BaseGenerator) {
_inherits(_default, _BaseGenerator);
var _super = _createSuper(_default);
function _default(params) {
var _this;
_classCallCheck(this, _default);
_this = _super.call(this, params);
_this.registerTemplates("quasar/", [// modules
"store/modules/foo/index.js", "store/modules/foo/create/actions.js", "store/modules/foo/create/getters.js", "store/modules/foo/create/index.js", "store/modules/foo/create/mutation_types.js", "store/modules/foo/create/mutations.js", "store/modules/foo/create/state.js", "store/modules/foo/delete/actions.js", "store/modules/foo/delete/getters.js", "store/modules/foo/delete/index.js", "store/modules/foo/delete/mutation_types.js", "store/modules/foo/delete/mutations.js", "store/modules/foo/delete/state.js", "store/modules/foo/list/actions.js", "store/modules/foo/list/getters.js", "store/modules/foo/list/index.js", "store/modules/foo/list/mutation_types.js", "store/modules/foo/list/mutations.js", "store/modules/foo/list/state.js", "store/modules/foo/show/actions.js", "store/modules/foo/show/getters.js", "store/modules/foo/show/index.js", "store/modules/foo/show/mutation_types.js", "store/modules/foo/show/mutations.js", "store/modules/foo/show/state.js", "store/modules/foo/update/actions.js", "store/modules/foo/update/getters.js", "store/modules/foo/update/index.js", "store/modules/foo/update/mutation_types.js", "store/modules/foo/update/mutations.js", "store/modules/foo/update/state.js", // common for modules
"common/store/mutation_types.js", "common/store/create/actions.js", "common/store/create/getters.js", "common/store/create/mutation_types.js", "common/store/create/mutations.js", "common/store/create/state.js", "common/store/delete/actions.js", "common/store/delete/getters.js", "common/store/delete/mutation_types.js", "common/store/delete/mutations.js", "common/store/delete/state.js", "common/store/list/actions.js", "common/store/list/getters.js", "common/store/list/mutation_types.js", "common/store/list/mutations.js", "common/store/list/state.js", "common/store/show/actions.js", "common/store/show/getters.js", "common/store/show/mutation_types.js", "common/store/show/mutations.js", "common/store/show/state.js", "common/store/update/actions.js", "common/store/update/getters.js", "common/store/update/mutation_types.js", "common/store/update/mutations.js", "common/store/update/state.js", // components
"components/foo/Create.vue", "components/foo/Filter.vue", "components/foo/Form.vue", "components/foo/List.vue", "components/foo/Update.vue", "components/foo/Show.vue", //common components
"common/components/index.js", "common/components/ActionCell.vue", "common/components/Breadcrumb.vue", "common/components/ConfirmDelete.vue", "common/components/DataFilter.vue", "common/components/InputDate.vue", "common/components/Loading.vue", "common/components/Toolbar.vue", // components mixins
"common/mixins/CreateMixin.js", "common/mixins/ListMixin.js", "common/mixins/ShowMixin.js", "common/mixins/UpdateMixin.js", // routes
"router/foo.js", // error
"error/SubmissionError.js", // utils
"utils/fetch.js", "utils/dates.js", "utils/notify.js", "utils/vuexer.js", // i18n
"i18n/index.js"]);
handlebars.registerHelper("compare", hbh_comparison.compare);
handlebars.registerHelper("ifEven", hbh_comparison.ifEven);
handlebars.registerHelper("ifOdd", hbh_comparison.ifOdd);
handlebars.registerHelper("inArray", hbh_array.inArray);
handlebars.registerHelper("forEach", hbh_array.forEach);
handlebars.registerHelper("lowercase", hbh_string.lowercase);
handlebars.registerHelper("capitalize", hbh_string.capitalize);
_this.registerSwitchHelper();
return _this;
}
_createClass(_default, [{
key: "help",
value: function help(resource) {
var titleLc = resource.title.toLowerCase();
console.log('Code for the "%s" resource type has been generated!', resource.title);
console.log("Paste the following definitions in your application configuration:");
console.log(chalk.green("\n//Add to quasar.conf\n// 1. in 'framework.components'\n 'QTable',\n 'QTh',\n 'QTr',\n 'QTd',\n 'QBreadcrumbs',\n 'QBreadcrumbsEl',\n 'QSpace',\n 'QInput',\n 'QForm',\n 'QSelect',\n 'QMarkupTable',\n 'QDate',\n 'QTime',\n 'QCheckbox',\n 'QPopupProxy',\n 'QSpinner',\n 'QInnerLoading',\n 'QCard',\n 'QCardSection',\n 'QCardActions',\n 'QExpansionItem',\n 'QDialog',\n 'QAvatar',\n\n// 2. in 'framework.config', customize later\nnotify: {\n position: 'top',\n multiLine: true,\n timeout: 0,\n},\n\n// 3. in 'framework.directives\n 'ClosePopup'\n\n// 4. in 'framework.plugins\n 'Notify'\n\n//import routes\nimport ".concat(titleLc, "Routes from '../router/").concat(titleLc, "';\n\n// Add routes to VueRouter\nconst router = new VueRouter({\n // ...\n routes: [\n ...").concat(titleLc, "Routes,\n ]\n});\n\n// Add the modules in the store\nimport ").concat(titleLc, " from '../store/modules/").concat(titleLc, "/';\n\nexport const store = new Vuex.Store({\n // ...\n modules: {\n ").concat(titleLc, "\n }\n});\n")));
}
}, {
key: "registerSwitchHelper",
value: function registerSwitchHelper() {
/*
https://github.com/wycats/handlebars.js/issues/927#issuecomment-318640459
{{#switch state}}
{{#case "page1" "page2"}}page 1 or 2{{/case}}
{{#case "page3"}}page3{{/case}}
{{#case "page4"}}page4{{/case}}
{{#case "page5"}}
{{#switch s}}
{{#case "3"}}s = 3{{/case}}
{{#case "2"}}s = 2{{/case}}
{{#case "1"}}s = 1{{/case}}
{{#default}}unknown{{/default}}
{{/switch}}
{{/case}}
{{#default}}page0{{/default}}
{{/switch}}
*/
handlebars.__switch_stack__ = [];
handlebars.registerHelper("switch", function (value, options) {
handlebars.__switch_stack__.push({
switch_match: false,
switch_value: value
});
var html = options.fn(this);
handlebars.__switch_stack__.pop();
return html;
});
handlebars.registerHelper("case", function (value, options) {
var args = Array.from(arguments);
options = args.pop();
var caseValues = args;
var stack = handlebars.__switch_stack__[handlebars.__switch_stack__.length - 1];
if (stack.switch_match || caseValues.indexOf(stack.switch_value) === -1) {
return "";
} else {
stack.switch_match = true;
return options.fn(this);
}
});
handlebars.registerHelper("default", function (options) {
var stack = handlebars.__switch_stack__[handlebars.__switch_stack__.length - 1];
if (!stack.switch_match) {
return options.fn(this);
}
});
}
}, {
key: "generate",
value: function generate(api, resource, dir) {
var _this2 = this;
return resource.getParameters().then(function (params) {
params = params.map(function (param) {
return _objectSpread(_objectSpread({}, param), _this2.getHtmlInputTypeFromField(param));
});
params = _this2.cleanupParams(params);
_this2.generateFiles(api, resource, dir, params);
})["catch"](function (e) {
return console.log(chalk.red(e));
});
}
}, {
key: "cleanupParams",
value: function cleanupParams(params) {
var stats = {};
var result = [];
params.forEach(function (p) {
var key = p.variable.endsWith("[]") ? p.variable.slice(0, -2) : p.variable;
if (!stats[key]) {
stats[key] = 0;
}
stats[key] += 1;
});
params.forEach(function (p) {
if (p.variable.startsWith("exists[")) {
result.push(p);
return; // removed for the moment, it can help to add null option to select
}
if (p.variable.startsWith("order[")) {
result.push(p);
return;
}
if (!stats[p.variable] && p.variable.endsWith("[]")) {
if (stats[p.variable.slice(0, -2)] === 1) {
result.push(p);
}
} else {
if (stats[p.variable] === 2) {
p.multiple = true;
}
result.push(p);
}
});
return result;
}
}, {
key: "printObject",
value: function printObject(obj) {
var cache = [];
console.log(JSON.stringify(obj, function (key, value) {
if (_typeof(value) === "object" && value !== null) {
if (cache.includes(value)) {
// Duplicate reference found, discard key
return;
} // Store value in our collection
cache.push(value);
}
return value;
}));
cache = null;
}
}, {
key: "generateFiles",
value: function generateFiles(api, resource, dir, params) {
var _this3 = this;
var lc = resource.title.toLowerCase();
var titleUcFirst = resource.title.charAt(0).toUpperCase() + resource.title.slice(1);
var formFields = this.buildFields(resource.writableFields);
var dateTypes = ["time", "date", "dateTime"];
var formContainsDate = formFields.some(function (e) {
return dateTypes.includes(e.type);
});
var fields = this.buildFields(resource.readableFields);
var listContainsDate = fields.some(function (e) {
return dateTypes.includes(e.type);
});
var parameters = [];
params.forEach(function (p) {
var paramIndex = fields.findIndex(function (field) {
return field.name === p.variable;
});
if (paramIndex === -1) {
if (p.variable.startsWith("order[")) {
var v = p.variable.slice(6, -1);
var found = fields.findIndex(function (field) {
return field.name === v;
});
if (found !== -1) {
fields[found].sortable = true;
}
return;
}
if (p.variable.startsWith("exists[")) {
var exists = p.variable.slice(7, -1);
var foundExistsFieldIndex = fields.findIndex(function (field) {
return field.name === exists;
});
if (foundExistsFieldIndex !== -1) {
var param = fields[foundExistsFieldIndex];
param.variable = p.variable;
param.filterType = "exists";
parameters.push(param);
} else {
p.name = exists;
p.filterType = "exists";
parameters.push(p);
}
return;
}
if (!p.name) {
p = _objectSpread(_objectSpread({}, p), {}, {
name: p.variable
});
}
if (!p.sortable) {
parameters.push(p);
}
} else {
var _param = fields[paramIndex];
_param.multiple = p.multiple;
parameters.push(_param);
}
});
var paramsHaveRefs = parameters.some(function (e) {
return e.type === "text" && e.reference;
});
var labels = this.commonLabelTexts();
var hashEntry = this.hashCode(api.entrypoint);
var context = {
title: resource.title,
name: resource.name,
lc: lc,
uc: resource.title.toUpperCase(),
fields: fields,
dateTypes: dateTypes,
listContainsDate: listContainsDate,
paramsHaveRefs: paramsHaveRefs,
parameters: parameters,
formFields: formFields,
formContainsDate: formContainsDate,
hydraPrefix: this.hydraPrefix,
titleUcFirst: titleUcFirst,
labels: labels,
hashEntry: hashEntry
}; // Create directories
// These directories may already exist
["".concat(dir, "/config"), "".concat(dir, "/error"), "".concat(dir, "/router"), "".concat(dir, "/utils"), "".concat(dir, "/i18n"), "".concat(dir, "/i18n/en-us"), "".concat(dir, "/common"), "".concat(dir, "/common/components"), "".concat(dir, "/common/mixins"), "".concat(dir, "/common/store"), "".concat(dir, "/common/store/create"), "".concat(dir, "/common/store/delete"), "".concat(dir, "/common/store/list"), "".concat(dir, "/common/store/show"), "".concat(dir, "/common/store/update")].forEach(function (dir) {
return _this3.createDir(dir, false);
});
["".concat(dir, "/store/modules/").concat(lc), "".concat(dir, "/store/modules/").concat(lc, "/create"), "".concat(dir, "/store/modules/").concat(lc, "/delete"), "".concat(dir, "/store/modules/").concat(lc, "/list"), "".concat(dir, "/store/modules/").concat(lc, "/show"), "".concat(dir, "/store/modules/").concat(lc, "/update"), "".concat(dir, "/components/").concat(lc)].forEach(function (dir) {
return _this3.createDir(dir);
});
["common/components/index.js", "common/components/ActionCell.vue", "common/components/Breadcrumb.vue", "common/components/ConfirmDelete.vue", "common/components/DataFilter.vue", "common/components/InputDate.vue", "common/components/Loading.vue", "common/components/Toolbar.vue", "common/mixins/CreateMixin.js", "common/mixins/ListMixin.js", "common/mixins/ShowMixin.js", "common/mixins/UpdateMixin.js", "common/store/mutation_types.js", "common/store/create/actions.js", "common/store/create/getters.js", "common/store/create/mutation_types.js", "common/store/create/mutations.js", "common/store/create/state.js", "common/store/delete/actions.js", "common/store/delete/getters.js", "common/store/delete/mutation_types.js", "common/store/delete/mutations.js", "common/store/delete/state.js", "common/store/list/actions.js", "common/store/list/getters.js", "common/store/list/mutation_types.js", "common/store/list/mutations.js", "common/store/list/state.js", "common/store/show/actions.js", "common/store/show/getters.js", "common/store/show/mutation_types.js", "common/store/show/mutations.js", "common/store/show/state.js", "common/store/update/actions.js", "common/store/update/getters.js", "common/store/update/mutation_types.js", "common/store/update/mutations.js", "common/store/update/state.js", "utils/dates.js", "utils/notify.js", "utils/vuexer.js"].forEach(function (common) {
return _this3.createFile(common, "".concat(dir, "/").concat(common), context, false);
});
[// modules
"store/modules/%s/index.js", "store/modules/%s/create/actions.js", "store/modules/%s/create/getters.js", "store/modules/%s/create/index.js", "store/modules/%s/create/mutation_types.js", "store/modules/%s/create/mutations.js", "store/modules/%s/create/state.js", "store/modules/%s/delete/actions.js", "store/modules/%s/delete/getters.js", "store/modules/%s/delete/index.js", "store/modules/%s/delete/mutation_types.js", "store/modules/%s/delete/mutations.js", "store/modules/%s/delete/state.js", "store/modules/%s/list/actions.js", "store/modules/%s/list/getters.js", "store/modules/%s/list/index.js", "store/modules/%s/list/mutation_types.js", "store/modules/%s/list/mutations.js", "store/modules/%s/list/state.js", "store/modules/%s/show/actions.js", "store/modules/%s/show/getters.js", "store/modules/%s/show/index.js", "store/modules/%s/show/mutation_types.js", "store/modules/%s/show/mutations.js", "store/modules/%s/show/state.js", "store/modules/%s/update/actions.js", "store/modules/%s/update/getters.js", "store/modules/%s/update/index.js", "store/modules/%s/update/mutation_types.js", "store/modules/%s/update/mutations.js", "store/modules/%s/update/state.js", // components
"components/%s/Create.vue", "components/%s/Filter.vue", "components/%s/Form.vue", "components/%s/List.vue", "components/%s/Update.vue", "components/%s/Show.vue", // routes
"router/%s.js"].forEach(function (pattern) {
if (pattern === "components/%s/Filter.vue" && !context.parameters.length) {
return;
}
_this3.createFileFromPattern(pattern, dir, lc, context);
}); // error
this.createFile("error/SubmissionError.js", "".concat(dir, "/error/SubmissionError.js"), context, false);
this.createEntrypoint(api.entrypoint, "".concat(dir, "/config/").concat(hashEntry, "_entrypoint.js"));
this.createFile("utils/fetch.js", "".concat(dir, "/utils/fetch.js"), {
hydraPrefix: this.hydraPrefix
}, false);
this.createFile("i18n/index.js", "".concat(dir, "/i18n/en-us/index.js"), {
labels: Object.values(labels)
}, false);
var contextLabels = {
labels: this.contextLabelTexts(formFields, fields)
};
this.createFile("i18n/index.js", "".concat(dir, "/i18n/en-us/").concat(lc, ".js"), contextLabels, false);
}
}, {
key: "hashCode",
value: function hashCode(s) {
return Math.abs(Array.from(s).reduce(function (s, c) {
return Math.imul(31, s) + c.charCodeAt(0) | 0;
}, 0));
}
}, {
key: "contextLabelTexts",
value: function contextLabelTexts(formFields, fields) {
var texts = [];
formFields.forEach(function (x) {
return texts.push(x.name);
}); // forms
fields.forEach(function (x) {
return texts.push(x.name);
}); // for show, too
return _toConsumableArray(new Set(texts));
}
}, {
key: "commonLabelTexts",
value: function commonLabelTexts() {
return {
submit: "Submit",
reset: "Reset",
"delete": "Delete",
confirmDelete: "Are you sure you want to delete this item?",
noresults: "No results",
close: "Close",
cancel: "Cancel",
updated: "Updated",
field: "Field",
value: "Value",
filters: "Filters",
filter: "Filter",
unavail: "Data unavailable",
loading: "Loading...",
deleted: "Deleted",
numValidation: "Please, insert a value bigger than zero!",
stringValidation: "Please type something",
required: "Field is required",
recPerPage: "Records per page:"
}; // handlebars.registerPartial("myPartial", "{{name}}");
}
}]);
return _default;
}(BaseGenerator);
export { _default as default };