qb-field
Version:
A lightweight abstraction layer for Quick Base
461 lines • 14.5 kB
JavaScript
/*!
* Package Name: qb-field
* Package Description: A lightweight abstraction layer for Quick Base
* Version: 5.0.23
* Build Timestamp: 2023-11-15T14:40:42.279Z
* Package Homepage: https://github.com/tflanagan/node-qb-field
* Git Location: git@github.com:tflanagan/node-qb-field.git
* Authored By: Tristian Flanagan <contact@tristianflanagan.com> (https://github.com/tflanagan)
* License: Apache-2.0
*
* Copyright 2019 Tristian Flanagan
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.QBField = void 0;
/* Dependencies */
const deepmerge_1 = __importDefault(require("deepmerge"));
const rfc4122_1 = __importDefault(require("rfc4122"));
const quickbase_1 = require("quickbase");
/* Globals */
const VERSION = require('../package.json').version;
const IS_BROWSER = typeof (window) !== 'undefined';
const rfc4122 = new rfc4122_1.default();
const BASE_USAGE = {
actions: {
count: 0
},
appHomePages: {
count: 0
},
dashboards: {
count: 0
},
defaultReports: {
count: 0
},
exactForms: {
count: 0
},
fields: {
count: 0
},
forms: {
count: 0
},
notifications: {
count: 0
},
personalReports: {
count: 0
},
relationships: {
count: 0
},
reminders: {
count: 0
},
reports: {
count: 0
},
roles: {
count: 0
},
tableImports: {
count: 0
},
tableRules: {
count: 0
},
webhooks: {
count: 0
}
};
/* Main Class */
class QBField {
constructor(options) {
this.CLASS_NAME = 'QBField';
this._tableId = '';
this._fid = -1;
this._data = {};
this._usage = (0, deepmerge_1.default)({}, BASE_USAGE);
this.id = rfc4122.v4();
const _a = options || {}, { quickbase } = _a, classOptions = __rest(_a, ["quickbase"]);
if (quickbase_1.QuickBase.IsQuickBase(quickbase)) {
this._qb = quickbase;
}
else {
this._qb = new quickbase_1.QuickBase(deepmerge_1.default.all([
QBField.defaults.quickbase,
quickbase || {}
]));
}
const settings = (0, deepmerge_1.default)(QBField.defaults, classOptions);
this.setTableId(settings.tableId)
.setFid(settings.fid);
return this;
}
/**
* This method clears the QBField instance of any trace of the existing field, but preserves defined connection settings.
*/
clear() {
this._fid = -1;
this._data = {};
this._usage = (0, deepmerge_1.default)({}, BASE_USAGE);
return this;
}
/**
* This method deletes the field from QuickBase, then calls `.clear()`.
*/
delete({ requestOptions } = {}) {
return __awaiter(this, void 0, void 0, function* () {
const fid = this.get('id');
const fin = (deletedFieldIds) => {
this.clear();
return {
deletedFieldIds,
errors: []
};
};
if (!fid) {
return fin([fid]);
}
try {
const { headers, data } = yield this._qb.deleteFields({
tableId: this.getTableId(),
fieldIds: [fid],
returnAxios: true,
requestOptions
});
if (data.errors && data.errors.length > 0) {
throw new quickbase_1.QuickBaseError(1000, 'Unable to delete field', data.errors[0], headers['qb-api-ray']);
}
this.clear();
return data;
}
catch (err) {
if (err.description === `Field: ${fid} was not found.`) {
return fin([fid]);
}
throw err;
}
});
}
get(attribute) {
if (attribute === 'tableId') {
return this.getTableId();
}
else if (attribute === 'fid' || attribute === 'id') {
return this.getFid();
}
else if (attribute === 'usage') {
return this.getUsage();
}
if (attribute === 'type') {
attribute = 'fieldType';
}
return this._data[attribute];
}
/**
* Get the set QBField Field ID
*/
getFid() {
return this._fid;
}
/**
* Get the set QBField Table ID
*/
getTableId() {
return this._tableId;
}
getTempToken({ requestOptions } = {}) {
return __awaiter(this, void 0, void 0, function* () {
yield this._qb.getTempTokenDBID({
dbid: this.getTableId(),
requestOptions
});
});
}
/**
* Get the Quick Base Field usage
*
* `.loadUsage()` must be called first
*/
getUsage() {
return this._usage;
}
/**
* Load the Quick Base Field attributes and permissions
*/
load({ requestOptions } = {}) {
return __awaiter(this, void 0, void 0, function* () {
const results = yield this._qb.getField({
tableId: this.getTableId(),
fieldId: this.getFid(),
requestOptions
});
Object.entries(results).forEach(([attribute, value]) => {
this.set(attribute, value);
});
return this._data;
});
}
/**
* Load the Quick Base Field usage
*/
loadUsage({ requestOptions } = {}) {
return __awaiter(this, void 0, void 0, function* () {
const results = yield this._qb.getFieldUsage({
tableId: this.getTableId(),
fieldId: this.getFid(),
requestOptions
});
this.set('usage', results[0].usage);
return this.getUsage();
});
}
/**
* If a field id is not defined, this will execute the createField option. After a successful
* createField, or if a field id was previously defined, this will execute an updateField.
*
* If `attributesToSave` is defined, then only configured attributes in this array will be saved.
*
* If this executes a createField, the newly assigned Field ID is automatically stored internally.
*
* After a successful save, all new attributes are available for use.
*
* @param attributesToSave Array of attributes to save
*/
save({ attributesToSave, requestOptions } = {}) {
return __awaiter(this, void 0, void 0, function* () {
const data = {
tableId: this.getTableId(),
label: this.get('label'),
requestOptions
};
const saveable = [
'fieldHelp',
'permissions',
'label',
'noWrap',
'bold',
'appearsByDefault',
'findEnabled'
];
if (this.getFid() > 0) {
saveable.push('required', 'unique');
}
else {
saveable.push('fieldType', 'mode', 'audited');
}
// TODO
// Need to filter out properties based on field type
// Field schema is not "round-trip", the returned schema
// has attributes in the properties object that are not
// accepted when saved. For now, only save the properties
// object when requested.
if (attributesToSave === null || attributesToSave === void 0 ? void 0 : attributesToSave.indexOf('properties')) {
saveable.push('properties');
}
saveable.filter((attribute) => {
return !attributesToSave || attributesToSave.indexOf(attribute) !== -1;
}).forEach((attribute) => {
data[attribute] = this.get(attribute);
});
let results;
if (this.getFid() > 0) {
data.fieldId = this.getFid();
results = yield this._qb.updateField(data);
}
else {
results = yield this._qb.createField(data);
}
Object.entries(results).forEach(([attribute, val]) => {
this.set(attribute, val);
});
return this._data;
});
}
set(attribute, value) {
if (attribute === 'tableId') {
return this.setTableId(value);
}
else if (attribute === 'fid' || attribute === 'id') {
return this.setFid(value);
}
else if (attribute === 'usage') {
this._usage = value;
}
else {
if (attribute === 'type') {
attribute = 'fieldType';
}
this._data[attribute] = value;
}
return this;
}
/**
* Sets the defined Field ID
*
* An alias for `.set('id', 6)` and `.set('fid', 6)`.
*
* @param fid Quick Base Field ID
*/
setFid(fid) {
this._fid = fid;
return this;
}
/**
* Sets the defined Table ID
*
* An alias for `.set('tableId', 'xxxxxxxxx')`.
*
* @param tableId Quick Base Field Table ID
*/
setTableId(tableId) {
this._tableId = tableId;
return this;
}
/**
* Rebuild the QBField instance from serialized JSON
*
* @param json QBField serialized JSON
*/
fromJSON(json) {
if (typeof (json) === 'string') {
json = JSON.parse(json);
}
if (typeof (json) !== 'object') {
throw new TypeError('json argument must be type of object or a valid JSON string');
}
if (json.quickbase) {
this._qb = new quickbase_1.QuickBase(json.quickbase);
}
if (json.tableId) {
this.setTableId(json.tableId);
}
if (json.fid || json.id) {
this.setFid(json.fid || json.id || -1);
}
if (json.data) {
Object.entries(json.data).forEach(([key, value]) => {
this.set(key, value);
});
}
if (json.usage) {
this._usage = json.usage;
}
return this;
}
/**
* Serialize the QBField instance into JSON
*/
toJSON() {
return {
quickbase: this._qb.toJSON(),
tableId: this.getTableId(),
fid: this.getFid(),
data: (0, deepmerge_1.default)({}, this._data),
usage: this.getUsage()
};
}
/**
* Create a new QBField instance from serialized JSON
*
* @param json QBField serialized JSON
*/
static fromJSON(json) {
if (typeof (json) === 'string') {
json = JSON.parse(json);
}
if (typeof (json) !== 'object') {
throw new TypeError('json argument must be type of object or a valid JSON string');
}
const newField = new QBField();
return newField.fromJSON(json);
}
/**
* Test if a variable is a `qb-field` object
*
* @param obj A variable you'd like to test
*/
static IsQBField(obj) {
return (obj || {}).CLASS_NAME === QBField.CLASS_NAME;
}
/**
* Returns a new QBField instance built off of `options`, that inherits configuration data from the passed in `attributes` argument.
*
* @param options QBField instance options
* @param attributes Quick Base Field attribute data
*/
static NewField(options, attributes) {
const newField = new QBField(options);
if (attributes) {
Object.entries(attributes).forEach(([attribute, value]) => {
newField.set(attribute, value);
});
}
return newField;
}
}
exports.QBField = QBField;
QBField.CLASS_NAME = 'QBField';
QBField.VERSION = VERSION;
/**
* The default settings of a `QuickBase` instance
*/
QBField.defaults = {
quickbase: {
realm: IS_BROWSER ? window.location.host.split('.')[0] : ''
},
tableId: (() => {
if (IS_BROWSER) {
const tableId = window.location.pathname.match(/^\/db\/(?!main)(.*)$/);
if (tableId) {
return tableId[1];
}
}
return '';
})(),
fid: -1
};
/* Export to Browser */
if (IS_BROWSER) {
window.QBField = exports;
}
//# sourceMappingURL=qb-field.js.map