grud-structorizer
-Small synchronous JS SDK for building GRUD schemas
+Async JS SDK for building GRUD schemas
Documentation
See docs for API documentation
Options
@@ -71,42 +71,42 @@ Options
cookies allows to pass a cookie header as object for requests
// expressjs session cookie via cookies
-const option = { "cookies": { "connect.sid": { "value":"s%3Al...PWgk;" } } }
+const option = { cookies: { "connect.sid": { value: "s%3Al...PWgk;" } } };
headers allows to pass headers for requests
// expressjs session cookie via headers
-const option = { "headers": { "Cookie": "connect.sid=s%3Al...PWgk;" } }
+const option = { headers: { Cookie: "connect.sid=s%3Al...PWgk;" } };
// OAuth 2.0 bearer token
-const option = { "headers": { "Authorization": "Bearer eyJhbG...ciOiJSUz" } }
+const option = { headers: { Authorization: "Bearer eyJhbG...ciOiJSUz" } };
Example
-const grudStructorizer = require('grud-structorizer');
+import grudStructorizer from "grud-structorizer";
-const options = { };
+const options = {};
const structorizer = grudStructorizer("http://localhost:8181", options);
+const { TableBuilder, ColumnBuilder, ConstraintBuilder } = structorizer;
-const TableBuilder = structorizer.TableBuilder;
-const ColumnBuilder = structorizer.ColumnBuilder;
-const ConstraintBuilder = structorizer.ConstraintBuilder;
+const tableBuilder = new TableBuilder("newTable", "generic").displayName("de", "Neue Tabelle", "en", "New table");
+const newTable = await tableBuilder.create();
-const newTable = new TableBuilder("newTable", "generic")
- .displayName("de", "Neue Tabelle", "en", "New table")
- .create();
-
-newTable.createColumns([
- new ColumnBuilder("rowIdentifier", "shorttext")
- .displayName("de", "Name")
- .identifier()
-]);
-
-newTable.createRowByObj({rowIdentifier: "Test"});
+await newTable.createColumns([new ColumnBuilder("rowIdentifier", "shorttext").displayName("de", "Name").identifier()]);
+await newTable.createRowByObj({ rowIdentifier: "Test" });
+Development
+Making Changes
+
+- Edit source files in
src/ directory
+- Run build (
npm run build) to ensure types and docs are up to date to your changes:
+- Publish changes via git in a new PR
+
+Migration Guide from v2.x to v3.0.0
+See migration guide for details.
Changelog
-See CHANGELOG.md
+See CHANGELOG.md
License
Copyright 2016-present Campudus GmbH.
diff --git a/docs/index.js.html b/docs/index.js.html
index 6dc98d4..44ac9e7 100644
--- a/docs/index.js.html
+++ b/docs/index.js.html
@@ -29,7 +29,7 @@
@@ -45,12 +45,9 @@ index.js
- "use strict";
+ import _ from "lodash";
-const _ = require("lodash");
-
-const AsyncApi = require("./AsyncApi");
-const SyncApi = require("./SyncApi");
+import Api from "./Api.js";
function argumentsToMultiLanguageObj(argsObj) {
const args = _.toArray(argsObj);
@@ -93,8 +90,7 @@ index.js
/**
* @typedef {object} GRUDStructorizer
- * @property api {SyncApi}
- * @property asyncApi {AsyncApi}
+ * @property api {Api}
* @property Table {Table}
* @property Tables {Tables}
* @property TableBuilder {TableBuilder}
@@ -103,19 +99,16 @@ index.js
*/
/**
- *
* @param baseUrl {string}
* @param options {object}
* @returns {GRUDStructorizer}
*/
function grudStructorizer(baseUrl, options) {
-
- const syncApi = new SyncApi(baseUrl, options);
- const asyncApi = new AsyncApi(baseUrl, options);
+ const api = new Api(baseUrl, options);
const StaticHelpers = {
- getLanguages: () => {
- return syncApi.doCall("GET", "/system/settings/langtags").value;
+ async getLanguages() {
+ return (await api.doCall("GET", "/system/settings/langtags")).value;
},
checkKindForLanguageConversion: (kind) => {
@@ -133,11 +126,7 @@ index.js
}
};
- /**
- *
- */
class Tables {
-
/**
*
*/
@@ -148,10 +137,10 @@ index.js
/**
* Fetches all tables
*
- * @returns {Tables}
+ * @returns {Promise<Tables>}
*/
- fetch() {
- Object.assign(this, syncApi.doCall("GET", "/tables"));
+ async fetch() {
+ Object.assign(this, await api.doCall("GET", "/tables"));
return this;
}
@@ -159,7 +148,7 @@ index.js
* Searches for a specific table. Fetch tables first
*
* @param tableName {string}
- * @returns {Table}
+ * @returns {Table | undefined}
*/
find(tableName) {
const table = _.find(this.tables, { name: tableName });
@@ -176,10 +165,6 @@ index.js
* @property name {string}
* @property kind {string}
*/
-
- /**
- *
- */
class Table {
/**
*
@@ -203,11 +188,11 @@ index.js
/**
* Fetches meta and columns for this Table object.
*
- * @param includeRows retrieves rows (default: false) {boolean}
- * @returns {Table}
+ * @param includeRows {boolean} retrieves rows (default: false)
+ * @returns {Promise<Table>}
*/
- fetch(includeRows = false) {
- Object.assign(this, syncApi.fetchTable(this.tableId, includeRows));
+ async fetch(includeRows = false) {
+ Object.assign(this, await api.fetchTable(this.tableId, includeRows));
return this;
}
@@ -223,14 +208,11 @@ index.js
if (!this.columns || !this.rows) {
throw new Error("Fetch table and rows first");
}
- return _.map(
- this.rows,
- (row) => {
- const obj = _.zipObject(_.map(this.columns, "name"), row.values);
- obj.rowId = row.id;
- return obj;
- }
- );
+ return _.map(this.rows, (row) => {
+ const obj = _.zipObject(_.map(this.columns, "name"), row.values);
+ obj.rowId = row.id;
+ return obj;
+ });
}
/**
@@ -283,9 +265,9 @@ index.js
/**
*
* @param columnBuilderArray {Array.<ConstraintBuilder>}
- * @returns {Array.<Column>}
+ * @returns {Promise<Array.<Column>>}
*/
- createColumns(columnBuilderArray) {
+ async createColumns(columnBuilderArray) {
if (typeof this.tableId === "undefined") {
throw new Error("table " + this.name + " should be created first");
}
@@ -299,12 +281,18 @@ index.js
columnObjArray.forEach(function (columnObject) {
self.columns.forEach(function (column) {
if (column.name === columnObject.name) {
- throw new Error("column " + columnObject.name + " can't be created because its name " + columnObject.name + " is already used");
+ throw new Error(
+ "column " +
+ columnObject.name +
+ " can't be created because its name " +
+ columnObject.name +
+ " is already used"
+ );
}
});
});
- const newColumns = syncApi.createColumns(this.tableId, columnObjArray);
+ const newColumns = await api.createColumns(this.tableId, columnObjArray);
newColumns.forEach(function (newColumn) {
self.columns.push(newColumn);
@@ -317,14 +305,14 @@ index.js
*
* @param nameOrId {string|number}
*/
- deleteColumn(nameOrId) {
+ async deleteColumn(nameOrId) {
const column = this.findColumn(nameOrId);
if (!column) {
throw new Error("No column with this name or ID found '" + nameOrId + "'");
}
- const response = syncApi.doCall("DELETE", "/tables/" + this.tableId + "/columns/" + column.id);
+ const response = await api.doCall("DELETE", "/tables/" + this.tableId + "/columns/" + column.id);
if (response) {
_.remove(this.columns, function (c) {
@@ -336,9 +324,9 @@ index.js
/**
*
* @param columnBuilder {ColumnBuilder}
- * @return {number} column id
+ * @return {Promise<number>} column id
*/
- createColumn(columnBuilder) {
+ async createColumn(columnBuilder) {
if (typeof this.tableId === "undefined") {
throw new Error("table " + this.name + " should be created first");
}
@@ -347,11 +335,17 @@ index.js
this.columns.forEach(function (column) {
if (column.name === columnObject.name) {
- throw new Error("column " + columnObject.name + " can't be created because its name " + columnObject.name + " is already used");
+ throw new Error(
+ "column " +
+ columnObject.name +
+ " can't be created because its name " +
+ columnObject.name +
+ " is already used"
+ );
}
});
- const newColumn = syncApi.createColumn(this.tableId, columnBuilder.build());
+ const newColumn = await api.createColumn(this.tableId, columnBuilder.build());
this.columns.push(newColumn);
@@ -389,32 +383,31 @@ index.js
/**
*
* @param columnNameToValueObject {object}
- * @returns {number} row id
+ * @returns {Promise<number>} row id
*/
- createRowByObj(columnNameToValueObject) {
-
+ async createRowByObj(columnNameToValueObject) {
const { columnIds, values } = this.getValuesFromCreateRowByObj(columnNameToValueObject);
- return this.createRows([values], columnIds)[0];
+ return (await this.createRows([values], columnIds))[0];
}
/**
*
- * @returns {number} row id
+ * @returns {Promise<number>} row id
*/
- createRow() {
+ async createRow() {
// convert arguments to array and
// hand it over to createRows with just one row
- return this.createRows([_.toArray(arguments)])[0];
+ return (await this.createRows([_.toArray(arguments)]))[0];
}
/**
*
* @param rows {Array.<Array.<any>>}
* @param columns {Array.<number>}
- * @returns {Array.<number>} array of row ids
+ * @returns {Promise<Array.<number>>} array of row ids
*/
- createRows(rows, columns) {
+ async createRows(rows, columns) {
if (typeof this.tableId === "undefined") {
throw new Error("table should be created first");
}
@@ -431,11 +424,11 @@ index.js
// generate IDs based on rowValues length
const columnIds = columns || _.range(1, firstRowValues.length + 1);
- return syncApi.createRows(this.tableId, columnIds, rows);
+ return await api.createRows(this.tableId, columnIds, rows);
}
- changeColumn(columnId, changeObj) {
- return syncApi.doCall("POST", "/tables/" + this.tableId + "/columns/" + columnId, changeObj);
+ async changeColumn(columnId, changeObj) {
+ return api.doCall("POST", "/tables/" + this.tableId + "/columns/" + columnId, changeObj);
}
getColumn(columnName) {
@@ -444,22 +437,25 @@ index.js
throw new Error(`Column name '${columnName}' does not exist`);
}
return column;
- };
+ }
/**
* Convenient method to change a single language column to multi language
*
* @param columnName {string}
- * @param pickLanguage language in which raw values should be inserted (default: "first language of
- * '/system/settings/langtags'") {string}
+ * @param pickLanguage {string} language in which raw values should be inserted (default: "first language of '/system/settings/langtags'")
+ * @returns {Promise<void>}
*/
- convertColumnToMultilanguage(columnName, pickLanguage) {
- this.fetch();
+ async convertColumnToMultilanguage(columnName, pickLanguage) {
+ await this.fetch();
const column = this.getColumn(columnName);
- const { ordering, kind, identifier, displayName, description, multilanguage, maxLength, minLength } = _.find(this.columns, { name: columnName });
+ const { ordering, kind, identifier, displayName, description, multilanguage, maxLength, minLength } = _.find(
+ this.columns,
+ { name: columnName }
+ );
- const languages = StaticHelpers.getLanguages();
+ const languages = await StaticHelpers.getLanguages();
const defaultLanguage = _.head(languages);
StaticHelpers.checkLanguageForLanguageConversion(languages, pickLanguage || defaultLanguage);
@@ -471,20 +467,27 @@ index.js
const columnIndex = _.findIndex(this.columns, { name: columnName });
- this.changeColumn(column.id, { name: columnName + "_convert_language" });
- this.fetch(true);
-
- const newColumnId = this.createColumn(
- new ColumnBuilder(columnName, kind).displayName(displayName).identifier(identifier).description(description).ordering(ordering).maxLength(maxLength).minLength(minLength).multilanguage(true),
+ await this.changeColumn(column.id, { name: columnName + "_convert_language" });
+ await this.fetch(true);
+
+ const newColumnId = await this.createColumn(
+ new ColumnBuilder(columnName, kind)
+ .displayName(displayName)
+ .identifier(identifier)
+ .description(description)
+ .ordering(ordering)
+ .maxLength(maxLength)
+ .minLength(minLength)
+ .multilanguage(true)
);
- _.forEach(this.rows, row => {
+ for (const row of this.rows) {
const { id: rowId, values } = row;
const value = values[columnIndex];
const url = "/tables/" + this.tableId + "/columns/" + newColumnId + "/rows/" + rowId;
if (!value) {
- return;
+ continue;
}
const mapValueIntoLanguage = (value, lang) => {
@@ -497,31 +500,34 @@ index.js
const newValue = mapValueIntoLanguage(value, pickLanguage || defaultLanguage);
- syncApi.doCall("PATCH", url, newValue);
+ await api.doCall("PATCH", url, newValue);
- syncApi.doCall("POST", `${url}/annotations`, {
+ await api.doCall("POST", `${url}/annotations`, {
langtags: languages,
type: "flag",
value: "needs_translation"
});
- });
+ }
- syncApi.doCall("DELETE", "/tables/" + this.tableId + "/columns/" + column.id);
- };
+ await api.doCall("DELETE", "/tables/" + this.tableId + "/columns/" + column.id);
+ }
/**
* Convenient method to change a multi language column to single language
* @param columnName {string}
- * @param pickLanguage language from which values are taken as new values (default: first language of
- * '/system/settings/langtags') {string}
+ * @param pickLanguage {string} language from which values are taken as new values (default: first language of '/system/settings/langtags')
+ * @returns {Promise<void>}
*/
- convertColumnToSinglelanguage(columnName, pickLanguage) {
- this.fetch();
+ async convertColumnToSinglelanguage(columnName, pickLanguage) {
+ await this.fetch();
const column = this.getColumn(columnName);
- const { ordering, kind, identifier, displayName, description, multilanguage, maxLength, minLength } = _.find(this.columns, { name: columnName });
+ const { ordering, kind, identifier, displayName, description, multilanguage, maxLength, minLength } = _.find(
+ this.columns,
+ { name: columnName }
+ );
- const languages = StaticHelpers.getLanguages();
+ const languages = await StaticHelpers.getLanguages();
const defaultLanguage = _.head(languages);
StaticHelpers.checkLanguageForLanguageConversion(languages, pickLanguage || defaultLanguage);
@@ -533,48 +539,50 @@ index.js
const columnIndex = _.findIndex(this.columns, { name: columnName });
- this.changeColumn(column.id, { name: columnName + "_convert_language" });
- this.fetch(true);
-
- const newColumnId = this.createColumn(
- new ColumnBuilder(columnName, kind).displayName(displayName).identifier(identifier).description(description).ordering(ordering).maxLength(maxLength).minLength(minLength).multilanguage(false),
+ await this.changeColumn(column.id, { name: columnName + "_convert_language" });
+ await this.fetch(true);
+
+ const newColumnId = await this.createColumn(
+ new ColumnBuilder(columnName, kind)
+ .displayName(displayName)
+ .identifier(identifier)
+ .description(description)
+ .ordering(ordering)
+ .maxLength(maxLength)
+ .minLength(minLength)
+ .multilanguage(false)
);
- _.forEach(this.rows, row => {
+ for (const row of this.rows) {
const { id: rowId, values, annotations } = row;
const newValue = _.get(values[columnIndex], pickLanguage || defaultLanguage);
const url = "/tables/" + this.tableId + "/columns/" + newColumnId + "/rows/" + rowId;
if (!newValue) {
- return;
+ continue;
}
- syncApi.doCall("PATCH", url, { value: newValue });
+ await api.doCall("PATCH", url, { value: newValue });
if (_.includes(annotations, columnIndex)) {
// there schould be not more than one translation flag per cell
- const langAnnotation = _.head(_.filter(annotations[columnIndex], { "value": "needs_translation" }));
+ const langAnnotation = _.head(_.filter(annotations[columnIndex], { value: "needs_translation" }));
if (langAnnotation) {
- syncApi.doCall("DELETE", `${url}/annotations/${langAnnotation.uuid}`);
+ await api.doCall("DELETE", `${url}/annotations/${langAnnotation.uuid}`);
}
}
- });
+ }
- syncApi.doCall("DELETE", "/tables/" + this.tableId + "/columns/" + column.id);
+ await api.doCall("DELETE", "/tables/" + this.tableId + "/columns/" + column.id);
}
}
-
- /**
- *
- */
class TableBuilder {
-
/**
*
* @param name {string}
- * @param type {("generic"|"settings")}
+ * @param type {("generic"|"settings"|"taxonomy")}
*/
constructor(name, type) {
const ALLOWED_TYPES = ["generic", "settings", "taxonomy"];
@@ -625,18 +633,15 @@ index.js
/**
*
- * @returns {Table}
+ * @returns {Promise<Table>}
*/
- create() {
- const tableId = syncApi.createTable(this.name, this._hidden, this._displayName, this.type, this._groupId).id;
+ async create() {
+ const tableId = (await api.createTable(this.name, this._hidden, this._displayName, this.type, this._groupId)).id;
return new Table(tableId, this.name);
}
}
- /**
- *
- */
class ColumnBuilder {
/**
*
@@ -645,8 +650,8 @@ index.js
*/
constructor(name, kind) {
this.column = {
- "name": name,
- "kind": kind
+ name: name,
+ kind: kind
};
}
@@ -741,7 +746,7 @@ index.js
* @returns {ColumnBuilder}
*/
identifier(identifier) {
- this.column.identifier = (typeof identifier === "boolean" ? identifier : true);
+ this.column.identifier = typeof identifier === "boolean" ? identifier : true;
return this;
}
@@ -751,7 +756,7 @@ index.js
* @returns {ColumnBuilder}
*/
separator(separator) {
- this.column.separator = (typeof separator === "boolean" ? separator : true);
+ this.column.separator = typeof separator === "boolean" ? separator : true;
return this;
}
@@ -761,7 +766,7 @@ index.js
* @returns {ColumnBuilder}
*/
hidden(hidden) {
- this.column.hidden = (typeof hidden === "boolean" ? hidden : true);
+ this.column.hidden = typeof hidden === "boolean" ? hidden : true;
return this;
}
@@ -979,7 +984,9 @@ index.js
build() {
if (typeof this.column.name !== "string" || typeof this.column.kind !== "string") {
- throw new Error("at least 'name' (" + this.column.name + ") and 'kind' (" + this.column.kind + ") must be defined");
+ throw new Error(
+ "at least 'name' (" + this.column.name + ") and 'kind' (" + this.column.kind + ") must be defined"
+ );
}
return this.column;
@@ -1080,8 +1087,7 @@ index.js
}
return {
- api: syncApi,
- asyncApi: asyncApi,
+ api: api,
Table: Table,
Tables: Tables,
@@ -1092,7 +1098,7 @@ index.js
};
}
-module.exports = grudStructorizer;
+export default grudStructorizer;
diff --git a/eslint.config.js b/eslint.config.js
new file mode 100644
index 0000000..b3262c5
--- /dev/null
+++ b/eslint.config.js
@@ -0,0 +1,58 @@
+import js from "@eslint/js";
+import prettier from "eslint-config-prettier";
+import promise from "eslint-plugin-promise";
+
+export default [
+ {
+ ignores: ["lib/*", "docs/*", "*.spec.js*", "*.d.ts"]
+ },
+ js.configs.recommended,
+ promise.configs["flat/recommended"],
+ prettier,
+ {
+ languageOptions: {
+ ecmaVersion: 2024,
+ sourceType: "module",
+ globals: {
+ // Browser globals
+ document: "readonly",
+ navigator: "readonly",
+ window: "readonly",
+ console: "readonly",
+ URLSearchParams: "readonly",
+ fetch: "readonly"
+ }
+ },
+ rules: {
+ camelcase: ["warn", { properties: "never" }],
+ eqeqeq: ["error", "allow-null"],
+ "no-constant-condition": ["error", { checkLoops: false }],
+ "no-inner-declarations": ["error", "functions"],
+ "no-labels": ["error", { allowLoop: false, allowSwitch: false }],
+ "no-return-assign": ["error", "except-parens"],
+ "no-unneeded-ternary": ["error", { defaultAssignment: false }],
+ "no-unused-vars": ["warn", { vars: "all", args: "none" }],
+ "one-var": ["error", { initialized: "never" }],
+ "new-cap": ["error", { newIsCap: true, capIsNew: false }],
+ "wrap-iife": ["error", "any", { functionPrototypeMethods: true }],
+ yoda: ["error", "never"]
+ }
+ },
+ {
+ files: ["**/*.spec.js"],
+ languageOptions: {
+ globals: {
+ describe: "readonly",
+ it: "readonly",
+ expect: "readonly",
+ beforeEach: "readonly",
+ afterEach: "readonly",
+ beforeAll: "readonly",
+ afterAll: "readonly"
+ }
+ },
+ rules: {
+ "no-unused-vars": "off"
+ }
+ }
+];
diff --git a/lib/Api.js b/lib/Api.js
deleted file mode 100644
index 1813710..0000000
--- a/lib/Api.js
+++ /dev/null
@@ -1,45 +0,0 @@
-"use strict";
-
-function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
-function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
-function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
-function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
-function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
-function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
-function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
-function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
-function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
-var _ = require("lodash");
-
-/**
- * @typedef {object} ApiOptions
- * @property cookies {object}
- */
-var Api = /*#__PURE__*/function () {
- /**
- *
- * @param baseUrl {string}
- * @param options {ApiOptions}
- */
- function Api(baseUrl, options) {
- _classCallCheck(this, Api);
- if (this.constructor === Api) {
- throw new Error("Abstract class 'Api' cannot be instantiated!");
- }
- this.baseUrl = baseUrl;
- this.cookies = _.get(options, ["cookies"], {});
- this.headers = _.get(options, ["headers"], {});
- }
- return _createClass(Api, [{
- key: "_getRequestHeaders",
- value: function _getRequestHeaders() {
- return _objectSpread({
- "Cookie": _.map(this.cookies, function (_ref, name) {
- var value = _ref.value;
- return name + "=" + value || "undefined";
- }).join("; ")
- }, this.headers);
- }
- }]);
-}();
-module.exports = Api;
\ No newline at end of file
diff --git a/lib/AsyncApi.js b/lib/AsyncApi.js
deleted file mode 100644
index de2faf5..0000000
--- a/lib/AsyncApi.js
+++ /dev/null
@@ -1,79 +0,0 @@
-"use strict";
-
-function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
-function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
-function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); }
-function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; }
-function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
-function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
-function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
-function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
-function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
-function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
-function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
-function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
-function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
-function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
-function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
-function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
-var fetch = require("node-fetch");
-var Api = require("./Api");
-
-/**
- *
- */
-var AsyncApi = /*#__PURE__*/function (_Api) {
- /**
- *
- * @param baseUrl {string}
- * @param options {ApiOptions}
- */
- // eslint-disable-next-line no-useless-constructor
- function AsyncApi(baseUrl, options) {
- _classCallCheck(this, AsyncApi);
- return _callSuper(this, AsyncApi, [baseUrl, options]);
- }
-
- /**
- *
- * @param method {string}
- * @param url {string}
- * @param [json] {object}
- * @param [nonce] {string}
- */
- _inherits(AsyncApi, _Api);
- return _createClass(AsyncApi, [{
- key: "doCall",
- value: (function () {
- var _doCall = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(method, url, json, nonce) {
- var fullUrl, options, response;
- return _regeneratorRuntime().wrap(function _callee$(_context) {
- while (1) switch (_context.prev = _context.next) {
- case 0:
- fullUrl = nonce ? this.baseUrl + url + "?" + new URLSearchParams({
- nonce: nonce
- }) : this.baseUrl + url;
- options = {
- method: method,
- headers: this._getRequestHeaders(),
- body: json ? JSON.stringify(json) : undefined
- };
- _context.next = 4;
- return fetch(fullUrl, options);
- case 4:
- response = _context.sent;
- return _context.abrupt("return", response.json());
- case 6:
- case "end":
- return _context.stop();
- }
- }, _callee, this);
- }));
- function doCall(_x, _x2, _x3, _x4) {
- return _doCall.apply(this, arguments);
- }
- return doCall;
- }())
- }]);
-}(Api);
-module.exports = AsyncApi;
\ No newline at end of file
diff --git a/lib/SyncApi.js b/lib/SyncApi.js
deleted file mode 100644
index d115a43..0000000
--- a/lib/SyncApi.js
+++ /dev/null
@@ -1,191 +0,0 @@
-"use strict";
-
-function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
-function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
-function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
-function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
-function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
-function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
-function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
-function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
-function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
-function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
-function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
-function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
-function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
-var request = require("sync-request");
-var Api = require("./Api");
-
-/**
- *
- */
-var SyncApi = /*#__PURE__*/function (_Api) {
- /**
- *
- * @param baseUrl {string}
- * @param options {ApiOptions}
- */
- // eslint-disable-next-line no-useless-constructor
- function SyncApi(baseUrl, options) {
- _classCallCheck(this, SyncApi);
- return _callSuper(this, SyncApi, [baseUrl, options]);
- }
-
- /**
- *
- * @param method {string}
- * @param url {string}
- * @param [json] {object}
- * @param [nonce] {string}
- */
- _inherits(SyncApi, _Api);
- return _createClass(SyncApi, [{
- key: "doCall",
- value: function doCall(method, url, json, nonce) {
- var fullUrl = this.baseUrl + url;
- var options = {
- headers: this._getRequestHeaders(),
- json: json,
- qs: {
- nonce: nonce
- }
- };
- var response = request(method, fullUrl, options).getBody("utf-8");
- return JSON.parse(response);
- }
-
- /**
- *
- * @param nonce {string}
- */
- }, {
- key: "resetSchema",
- value: function resetSchema(nonce) {
- return this.doCall("POST", "/system/reset", undefined, nonce);
- }
-
- /**
- *
- * @param tableId {number}
- * @param [includeRows=false] {boolean}
- */
- }, {
- key: "fetchTable",
- value: function fetchTable(tableId) {
- var includeRows = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
- if (typeof tableId !== "number") {
- throw new Error("parameter 'tableId' should be a number");
- }
- var table = this.doCall("GET", "/tables/" + tableId);
- delete table["id"];
- delete table["status"];
- var columns = this.doCall("GET", "/tables/" + tableId + "/columns");
- delete columns["status"];
- Object.assign(table, columns);
- if (includeRows) {
- var rows = this.doCall("GET", "/tables/" + tableId + "/rows");
- delete rows["page"];
- delete rows["status"];
- Object.assign(table, rows);
- }
- return table;
- }
-
- /**
- *
- * @param name {string}
- * @param hidden {boolean}
- * @param displayName {object} multi-language object
- * @param type {string}
- * @param group {number}
- * @returns {object}
- */
- }, {
- key: "createTable",
- value: function createTable(name, hidden, displayName, type, group) {
- var json = {
- "name": name,
- "hidden": typeof hidden === "boolean" ? hidden : false
- };
- if (displayName && _typeof(displayName) === "object") {
- json["displayName"] = displayName;
- }
- if (type && typeof type === "string") {
- json["type"] = type;
- }
- if (group && typeof group === "number") {
- json["group"] = group;
- }
- return this.doCall("POST", "/tables", json);
- }
-
- /**
- *
- * @param tableId
- * @param columnObjArray
- */
- }, {
- key: "createColumns",
- value: function createColumns(tableId, columnObjArray) {
- var json = {
- "columns": columnObjArray
- };
- return this.doCall("POST", "/tables/" + tableId + "/columns", json).columns;
- }
-
- /**
- *
- * @param tableId
- * @param columnObject
- */
- }, {
- key: "createColumn",
- value: function createColumn(tableId, columnObject) {
- var json = {
- "columns": [columnObject]
- };
- return this.doCall("POST", "/tables/" + tableId + "/columns", json).columns[0];
- }
-
- /**
- *
- * @param tableId
- * @param columnIds
- * @param values
- * @returns {*}
- */
- }, {
- key: "createRow",
- value: function createRow(tableId, columnIds, values) {
- return this.createRows(tableId, columnIds, [values])[0];
- }
-
- /**
- *
- * @param tableId
- * @param columnIds
- * @param rows
- */
- }, {
- key: "createRows",
- value: function createRows(tableId, columnIds, rows) {
- var json = {
- "columns": columnIds.map(function (columnId) {
- return {
- "id": columnId
- };
- }),
- "rows": rows.map(function (rowValues) {
- return {
- "values": rowValues
- };
- })
- };
- var result = this.doCall("POST", "/tables/" + tableId + "/rows", json);
- return result.rows.map(function (row) {
- return row.id;
- });
- }
- }]);
-}(Api);
-module.exports = SyncApi;
\ No newline at end of file
diff --git a/lib/index.js b/lib/index.js
deleted file mode 100644
index 85a2a66..0000000
--- a/lib/index.js
+++ /dev/null
@@ -1,1101 +0,0 @@
-"use strict";
-
-function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
-function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
-function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
-function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
-function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
-function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
-function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
-var _ = require("lodash");
-var AsyncApi = require("./AsyncApi");
-var SyncApi = require("./SyncApi");
-function argumentsToMultiLanguageObj(argsObj) {
- var args = _.toArray(argsObj);
- var langtagRegex = /[a-z]{2,3}[-_][A-Z]{2,3}|[a-z]{2,3}/;
- var obj = {};
- if (args.length === 1 && _.isPlainObject(args[0])) {
- var valid = _.every(_.keys(args[0]), function (key) {
- return langtagRegex.test(key);
- });
- if (valid) {
- obj = args[0];
- } else {
- throw new Error("arguments must be either key/value list (e.g. de-DE, Tabelle, en-GB, table) or a plain object");
- }
- } else if (_.isArray(args) && args.length % 2 === 0) {
- var object = {};
- for (var i = 0; i < args.length; i += 2) {
- var langtag = args[i];
- var value = args[i + 1];
- if (langtag !== undefined && langtagRegex.test(langtag) && value !== undefined) {
- object[langtag] = value;
- } else {
- throw new Error("Arguments are wrong. undefined or wrong langtag. (" + JSON.stringify(args) + ")");
- }
- }
- obj = object;
- } else {
- console.log("invalid args", args, _.isArray(args), _.isPlainObject(args), _.toArray(args));
- throw new Error("arguments must be either key/value list (e.g. de-DE, Tabelle, en-GB, table) or a plain object");
- }
- return obj;
-}
-
-/**
- * @typedef {object} GRUDStructorizer
- * @property api {SyncApi}
- * @property asyncApi {AsyncApi}
- * @property Table {Table}
- * @property Tables {Tables}
- * @property TableBuilder {TableBuilder}
- * @property ColumnBuilder {ColumnBuilder}
- * @property ConstraintBuilder {ConstraintBuilder}
- */
-
-/**
- *
- * @param baseUrl {string}
- * @param options {object}
- * @returns {GRUDStructorizer}
- */
-function grudStructorizer(baseUrl, options) {
- var syncApi = new SyncApi(baseUrl, options);
- var asyncApi = new AsyncApi(baseUrl, options);
- var StaticHelpers = {
- getLanguages: function getLanguages() {
- return syncApi.doCall("GET", "/system/settings/langtags").value;
- },
- checkKindForLanguageConversion: function checkKindForLanguageConversion(kind) {
- var ALLOWED_TYPES = ["shorttext", "text"];
- if (!_.includes(ALLOWED_TYPES, kind)) {
- throw new Error("Column must be of kind '".concat(_.join(ALLOWED_TYPES, "' or '"), "'"));
- }
- },
- checkLanguageForLanguageConversion: function checkLanguageForLanguageConversion(languages, targetLanguage) {
- if (!_.includes(languages, targetLanguage)) {
- throw new Error("Language '".concat(targetLanguage, "' not in '/system/settings/langtags'"));
- }
- }
- };
-
- /**
- *
- */
- var Tables = /*#__PURE__*/function () {
- /**
- *
- */
- function Tables() {
- _classCallCheck(this, Tables);
- this.tables = [];
- }
-
- /**
- * Fetches all tables
- *
- * @returns {Tables}
- */
- return _createClass(Tables, [{
- key: "fetch",
- value: function fetch() {
- Object.assign(this, syncApi.doCall("GET", "/tables"));
- return this;
- }
-
- /**
- * Searches for a specific table. Fetch tables first
- *
- * @param tableName {string}
- * @returns {Table}
- */
- }, {
- key: "find",
- value: function find(tableName) {
- var table = _.find(this.tables, {
- name: tableName
- });
- if (table) {
- return new Table(table.id, table.name);
- }
- }
- }]);
- }();
- /**
- * @typedef {object} Column
- * @property id {number}
- * @property name {string}
- * @property kind {string}
- */
- /**
- *
- */
- var Table = /*#__PURE__*/function () {
- /**
- *
- * @param tableId {number}
- * @param tableName {string}
- */
- function Table(tableId, tableName) {
- _classCallCheck(this, Table);
- if (typeof tableId !== "number") {
- throw new Error("parameter 'tableId' should be a number");
- }
- if (typeof tableName !== "string") {
- throw new Error("parameter 'tableName' should be a string");
- }
- this.tableId = tableId;
- this.name = tableName;
- this.columns = [];
- }
-
- /**
- * Fetches meta and columns for this Table object.
- *
- * @param includeRows retrieves rows (default: false) {boolean}
- * @returns {Table}
- */
- return _createClass(Table, [{
- key: "fetch",
- value: function fetch() {
- var includeRows = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
- Object.assign(this, syncApi.fetchTable(this.tableId, includeRows));
- return this;
- }
-
- /**
- * Returns an array of row objects zipped with column names for this Table.
- *
- * The `rowId` property represents the row ID (PK) of the database,
- * so this value can be reused for updates/deletions/etc.
- *
- * @returns {Array.