@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
309 lines (268 loc) • 12.3 kB
JavaScript
import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
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 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 { sprintf } from "sprintf-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("vue-common/", [// error
"error/SubmissionError.js", // mixins
"mixins/CreateMixin.js", "mixins/ListMixin.js", "mixins/NotificationMixin.js", "mixins/ShowMixin.js", "mixins/UpdateMixin.js", // services
"services/api.js", "services/foo.js", // modules
"store/modules/crud.js", "store/modules/notifications.js", // utils
"utils/dates.js", "utils/fetch.js", "utils/hydra.js", // validators
"validators/date.js"]);
handlebars.registerHelper("compare", hbh_comparison.compare);
handlebars.registerHelper("ifEven", hbh_comparison.ifEven);
handlebars.registerHelper("ifOdd", hbh_comparison.ifOdd);
handlebars.registerHelper("isArray", hbh_array.isArray);
handlebars.registerHelper("inArray", hbh_array.inArray);
handlebars.registerHelper("forEach", hbh_array.forEach);
handlebars.registerHelper("lowercase", hbh_string.lowercase);
_this.registerSwitchHelper();
return _this;
}
_createClass(_default, [{
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: "getContextForResource",
value: function getContextForResource(resource, params) {
var lc = resource.title.toLowerCase();
var titleUcFirst = resource.title.charAt(0).toUpperCase() + resource.title.slice(1);
var fields = this.parseFields(resource);
var formFields = this.buildFields(resource.writableFields);
var dateTypes = ["time", "date", "dateTime"];
var formContainsDate = formFields.some(function (e) {
return dateTypes.includes(e.type);
});
var parameters = [];
params.forEach(function (p) {
var param = fields.find(function (field) {
return field.name === p.variable;
});
if (!param) {
p.name = p.variable;
parameters.push(p);
} else {
param.multiple = p.multiple;
parameters.push(param);
}
});
var paramsHaveRefs = parameters.some(function (e) {
return e.type === "text" && e.reference;
});
var labels = this.commonLabelTexts();
return {
title: resource.title,
name: resource.name,
lc: lc,
uc: resource.title.toUpperCase(),
fields: fields,
dateTypes: dateTypes,
paramsHaveRefs: paramsHaveRefs,
parameters: parameters,
formFields: formFields,
formContainsDate: formContainsDate,
hydraPrefix: this.hydraPrefix,
titleUcFirst: titleUcFirst,
labels: labels
};
}
}, {
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);
});
} // eslint-disable-next-line no-unused-vars
}, {
key: "generateFiles",
value: function generateFiles(api, resource, dir, params) {
var _this3 = this;
// Create directories
// These directories may already exist
["".concat(dir, "/config"), "".concat(dir, "/error"), "".concat(dir, "/mixins"), "".concat(dir, "/router"), "".concat(dir, "/services"), "".concat(dir, "/store/modules"), "".concat(dir, "/utils"), "".concat(dir, "/validators")].forEach(function (dir) {
return _this3.createDir(dir, false);
}); // error
this.createFile("error/SubmissionError.js", "".concat(dir, "/error/SubmissionError.js"), {}, false); // mixins
["mixins/Create%s.js", "mixins/List%s.js", "mixins/Notification%s.js", "mixins/Show%s.js", "mixins/Update%s.js"].forEach(function (pattern) {
return _this3.createFile(sprintf("".concat(pattern), "Mixin"), sprintf("".concat(dir, "/").concat(pattern), "Mixin"), {}, false);
}); // stores
["crud.js", "notifications.js"].forEach(function (file) {
return _this3.createFile("store/modules/".concat(file), "".concat(dir, "/store/modules/").concat(file), {
hydraPrefix: _this3.hydraPrefix
}, false);
}); // services
this.createFile("services/api.js", "".concat(dir, "/services/api.js"), {}, false);
this.createFileFromPattern("services/%s.js", dir, resource.title.toLowerCase(), {
name: resource.name
}); // validators
this.createFile("validators/date.js", "".concat(dir, "/validators/date.js"), {
hydraPrefix: this.hydraPrefix
}, false); // utils
["dates.js", "fetch.js", "hydra.js"].forEach(function (file) {
return _this3.createFile("utils/".concat(file), "".concat(dir, "/utils/").concat(file), {}, false);
});
this.createEntrypoint(api.entrypoint, "".concat(dir, "/config/entrypoint.js"));
}
}, {
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.endsWith("[exists]")) {
return; // removed for the moment, it can help to add null option to select
}
if (p.variable.startsWith("order[")) {
return; // removed for the moment, it can help to sorting data
}
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: "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",
edit: "Edit",
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:"
};
}
}, {
key: "parseFields",
value: function parseFields(resource) {
var fields = [].concat(_toConsumableArray(resource.writableFields), _toConsumableArray(resource.readableFields)).reduce(function (list, field) {
if (list[field.name]) {
return list;
}
var isReferences = field.reference && field.maxCardinality !== 1;
var isEmbeddeds = field.embedded && field.maxCardinality !== 1;
return _objectSpread(_objectSpread({}, list), {}, _defineProperty({}, field.name, _objectSpread(_objectSpread({}, field), {}, {
readonly: false,
isReferences: isReferences,
isEmbeddeds: isEmbeddeds,
isRelations: isEmbeddeds || isReferences
})));
}, {});
return Object.values(fields);
}
}]);
return _default;
}(BaseGenerator);
export { _default as default };