chore: code clean up (#76)

This commit is contained in:
Eric Tuvesson
2024-10-01 16:09:03 +02:00
committed by GitHub
parent d80870e835
commit 5dbb11bac8
4 changed files with 87 additions and 51 deletions

View File

@@ -73,8 +73,9 @@ class CloudStore {
xhr.open(options.method || 'GET', this.endpoint + path, true); xhr.open(options.method || 'GET', this.endpoint + path, true);
xhr.setRequestHeader('X-Parse-Application-Id', this.appId); xhr.setRequestHeader('X-Parse-Application-Id', this.appId);
if (typeof _noodl_cloudservices !== 'undefined') if (typeof _noodl_cloudservices !== 'undefined') {
xhr.setRequestHeader('X-Parse-Master-Key', _noodl_cloudservices.masterKey); xhr.setRequestHeader('X-Parse-Master-Key', _noodl_cloudservices.masterKey);
}
// Check for current users // Check for current users
var _cu = localStorage['Parse/' + this.appId + '/currentUser']; var _cu = localStorage['Parse/' + this.appId + '/currentUser'];
@@ -191,13 +192,13 @@ class CloudStore {
// I don't know which version the API was changed, lets just say above 4 for now. // I don't know which version the API was changed, lets just say above 4 for now.
if (this.dbVersionMajor && this.dbVersionMajor > 4) { if (this.dbVersionMajor && this.dbVersionMajor > 4) {
grouping._id = null; grouping._id = null;
if (options.where) args.push('$match=' + encodeURIComponent(JSON.stringify(options.where))); if (options.where) args.push('$match=' + encodeURIComponent(JSON.stringify(options.where)));
args.push('$group=' + JSON.stringify(grouping)); args.push('$group=' + JSON.stringify(grouping));
} else { } else {
grouping.objectId = null; grouping.objectId = null;
if (options.where) args.push('match=' + encodeURIComponent(JSON.stringify(options.where))); if (options.where) args.push('match=' + encodeURIComponent(JSON.stringify(options.where)));
args.push('group=' + JSON.stringify(grouping)); args.push('group=' + JSON.stringify(grouping));
@@ -257,11 +258,22 @@ class CloudStore {
}); });
} }
/**
*
* @param {{
* objectId: string;
* collection: string;
* include?: string[] | string;
* success: (data: unknown) => void;
* error: (error: unknown) => void;
* }} options
*/
fetch(options) { fetch(options) {
const args = []; const args = [];
if (options.include) if (options.include) {
args.push('include=' + (Array.isArray(options.include) ? options.include.join(',') : options.include)); args.push('include=' + (Array.isArray(options.include) ? options.include.join(',') : options.include));
}
this._makeRequest( this._makeRequest(
'/classes/' + options.collection + '/' + options.objectId + (args.length > 0 ? '?' + args.join('&') : ''), '/classes/' + options.collection + '/' + options.objectId + (args.length > 0 ? '?' + args.join('&') : ''),
@@ -433,6 +445,8 @@ class CloudStore {
* file: { * file: {
* name: string; * name: string;
* } * }
* success: (data: unknown) => void;
* error: (error: unknown) => void;
* }} options * }} options
*/ */
deleteFile(options) { deleteFile(options) {
@@ -563,21 +577,26 @@ function _deserializeJSON(data, type, modelScope) {
} }
function _fromJSON(item, collectionName, modelScope) { function _fromJSON(item, collectionName, modelScope) {
const m = (modelScope || Model).get(item.objectId); const modelStore = modelScope || Model;
m._class = collectionName;
if (collectionName !== undefined && CloudStore._collections[collectionName] !== undefined) const model = modelStore.get(item.objectId);
var schema = CloudStore._collections[collectionName].schema; model._class = collectionName;
for (var key in item) { let schema = undefined;
if (key === 'objectId' || key === 'ACL') continue; if (collectionName !== undefined && CloudStore._collections[collectionName] !== undefined) {
schema = CloudStore._collections[collectionName].schema;
var _type = schema && schema.properties && schema.properties[key] ? schema.properties[key].type : undefined;
m.set(key, _deserializeJSON(item[key], _type, modelScope));
} }
return m; for (const key in item) {
if (key === 'objectId' || key === 'ACL') {
continue;
}
const _type = schema && schema.properties && schema.properties[key] ? schema.properties[key].type : undefined;
model.set(key, _deserializeJSON(item[key], _type, modelScope));
}
return model;
} }
CloudStore._fromJSON = _fromJSON; CloudStore._fromJSON = _fromJSON;

View File

@@ -12,7 +12,7 @@ function createRecordsAPI(modelScope) {
return { return {
async query(className, query, options) { async query(className, query, options) {
if (typeof className === "undefined") throw new Error("'className' is undefined"); if (typeof className === 'undefined') throw new Error("'className' is undefined");
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
cloudstore().query({ cloudstore().query({
collection: className, collection: className,
@@ -27,9 +27,9 @@ function createRecordsAPI(modelScope) {
include: options ? options.include : undefined, include: options ? options.include : undefined,
select: options ? options.select : undefined, select: options ? options.select : undefined,
count: options ? options.count : undefined, count: options ? options.count : undefined,
success: (results,count) => { success: (results, count) => {
const _results = results.map((r) => cloudstore()._fromJSON(r, className)); const _results = results.map((r) => cloudstore()._fromJSON(r, className));
if(count !== undefined) resolve({results:_results,count}); if (count !== undefined) resolve({ results: _results, count });
else resolve(_results); else resolve(_results);
}, },
error: (err) => { error: (err) => {
@@ -40,7 +40,7 @@ function createRecordsAPI(modelScope) {
}, },
async count(className, query) { async count(className, query) {
if (typeof className === "undefined") throw new Error("'className' is undefined"); if (typeof className === 'undefined') throw new Error("'className' is undefined");
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
cloudstore().count({ cloudstore().count({
collection: className, collection: className,
@@ -62,7 +62,7 @@ function createRecordsAPI(modelScope) {
}, },
async distinct(className, property, query) { async distinct(className, property, query) {
if (typeof className === "undefined") throw new Error("'className' is undefined"); if (typeof className === 'undefined') throw new Error("'className' is undefined");
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
cloudstore().distinct({ cloudstore().distinct({
collection: className, collection: className,
@@ -85,7 +85,7 @@ function createRecordsAPI(modelScope) {
}, },
async aggregate(className, group, query) { async aggregate(className, group, query) {
if (typeof className === "undefined") throw new Error("'className' is undefined"); if (typeof className === 'undefined') throw new Error("'className' is undefined");
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
cloudstore().aggregate({ cloudstore().aggregate({
collection: className, collection: className,
@@ -107,20 +107,31 @@ function createRecordsAPI(modelScope) {
}); });
}, },
/**
*
* @param {string | { getId(): string; }} objectOrId
* @param {{
* className: string;
* include?: string[] | string;
* }} options
* @returns {Promise<unknown>}
*/
async fetch(objectOrId, options) { async fetch(objectOrId, options) {
if (typeof objectOrId === 'undefined') return Promise.reject(new Error("'objectOrId' is undefined.")); if (typeof objectOrId === 'undefined') return Promise.reject(new Error("'objectOrId' is undefined."));
if (typeof objectOrId !== 'string') objectOrId = objectOrId.getId(); if (typeof objectOrId !== 'string') objectOrId = objectOrId.getId();
const className = (options ? options.className : undefined) || (modelScope || Model).get(objectOrId)._class; const className = (options ? options.className : undefined) || (modelScope || Model).get(objectOrId)._class;
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (!className) return reject('No class name specified'); if (!className) {
return reject('No class name specified');
}
cloudstore().fetch({ cloudstore().fetch({
collection: className, collection: className,
objectId: objectOrId, objectId: objectOrId,
include: options ? options.include : undefined, include: options ? options.include : undefined,
success: function (response) { success: function (response) {
var record = cloudstore()._fromJSON(response, className); const record = cloudstore()._fromJSON(response, className);
resolve(record); resolve(record);
}, },
error: function (err) { error: function (err) {
@@ -186,7 +197,7 @@ function createRecordsAPI(modelScope) {
}, },
async create(className, properties, options) { async create(className, properties, options) {
if (typeof className === "undefined") throw new Error("'className' is undefined"); if (typeof className === 'undefined') throw new Error("'className' is undefined");
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
cloudstore().create({ cloudstore().create({
collection: className, collection: className,

View File

@@ -2,10 +2,10 @@
const { Node, EdgeTriggeredInput } = require('../../../../noodl-runtime'); const { Node, EdgeTriggeredInput } = require('../../../../noodl-runtime');
var Model = require('../../../model'); const Model = require('../../../model');
const CloudStore = require('../../../api/cloudstore'); const CloudStore = require('../../../api/cloudstore');
var ModelNodeDefinition = { const ModelNodeDefinition = {
name: 'DbModel2', name: 'DbModel2',
docs: 'https://docs.noodl.net/nodes/data/cloud-data/record', docs: 'https://docs.noodl.net/nodes/data/cloud-data/record',
displayNodeName: 'Record', displayNodeName: 'Record',
@@ -21,11 +21,11 @@ var ModelNodeDefinition = {
} }
], ],
initialize: function () { initialize: function () {
var internal = this._internal; const internal = this._internal;
internal.inputValues = {}; internal.inputValues = {};
internal.relationModelIds = {}; internal.relationModelIds = {};
var _this = this; const _this = this;
this._internal.onModelChangedCallback = function (args) { this._internal.onModelChangedCallback = function (args) {
if (_this.isInputConnected('fetch')) return; if (_this.isInputConnected('fetch')) return;
@@ -109,13 +109,18 @@ var ModelNodeDefinition = {
displayName: 'Id', displayName: 'Id',
group: 'General', group: 'General',
set: function (value) { set: function (value) {
if (value instanceof Model) value = value.getId(); if (value instanceof Model) {
// Can be passed as model as well // Can be passed as model as well
else if (typeof value === 'object') value = Model.create(value).getId(); // If this is an js object, dereference it value = value.getId();
} else if (typeof value === 'object') {
// If this is an js object, dereference it
value = Model.create(value).getId();
}
this._internal.modelId = value; // Wait to fetch data this._internal.modelId = value; // Wait to fetch data
if (this.isInputConnected('fetch') === false) this.setModelID(value); if (this.isInputConnected('fetch') === false) {
else { this.setModelID(value);
} else {
this.flagOutputDirty('id'); this.flagOutputDirty('id');
} }
} }
@@ -138,9 +143,10 @@ var ModelNodeDefinition = {
this.setModel(model); this.setModel(model);
}, },
setModel: function (model) { setModel: function (model) {
if (this._internal.model) if (this._internal.model) {
// Remove old listener if existing // Remove old listener if existing
this._internal.model.off('change', this._internal.onModelChangedCallback); this._internal.model.off('change', this._internal.onModelChangedCallback);
}
this._internal.model = model; this._internal.model = model;
this.flagOutputDirty('id'); this.flagOutputDirty('id');
@@ -148,7 +154,9 @@ var ModelNodeDefinition = {
// We have a new model, mark all outputs as dirty // We have a new model, mark all outputs as dirty
for (var key in model.data) { for (var key in model.data) {
if (this.hasOutput('prop-' + key)) this.flagOutputDirty('prop-' + key); if (this.hasOutput('prop-' + key)) {
this.flagOutputDirty('prop-' + key);
}
} }
this.sendSignalOnOutput('fetched'); this.sendSignalOnOutput('fetched');
}, },
@@ -184,7 +192,7 @@ var ModelNodeDefinition = {
} }
}, },
scheduleFetch: function () { scheduleFetch: function () {
var _this = this; const _this = this;
const internal = this._internal; const internal = this._internal;
this.scheduleOnce('Fetch', function () { this.scheduleOnce('Fetch', function () {
@@ -199,12 +207,13 @@ var ModelNodeDefinition = {
collection: internal.collectionId, collection: internal.collectionId,
objectId: internal.modelId, // Get the objectId part of the model id objectId: internal.modelId, // Get the objectId part of the model id
success: function (response) { success: function (response) {
var model = cloudstore._fromJSON(response, internal.collectionId); const model = cloudstore._fromJSON(response, internal.collectionId);
if (internal.model !== model) { if (internal.model !== model) {
// Check if we need to change model // Check if we need to change model
if (internal.model) if (internal.model) {
// Remove old listener if existing // Remove old listener if existing
internal.model.off('change', internal.onModelChangedCallback); internal.model.off('change', internal.onModelChangedCallback);
}
internal.model = model; internal.model = model;
model.on('change', internal.onModelChangedCallback); model.on('change', internal.onModelChangedCallback);
@@ -213,8 +222,10 @@ var ModelNodeDefinition = {
delete response.objectId; delete response.objectId;
for (var key in response) { for (const key in response) {
if (_this.hasOutput('prop-' + key)) _this.flagOutputDirty('prop-' + key); if (_this.hasOutput('prop-' + key)) {
_this.flagOutputDirty('prop-' + key);
}
} }
_this.sendSignalOnOutput('fetched'); _this.sendSignalOnOutput('fetched');
@@ -226,7 +237,6 @@ var ModelNodeDefinition = {
}); });
}, },
scheduleStore: function () { scheduleStore: function () {
var _this = this;
var internal = this._internal; var internal = this._internal;
if (!internal.model) return; if (!internal.model) return;
@@ -247,8 +257,6 @@ var ModelNodeDefinition = {
}); });
}, },
registerInputIfNeeded: function (name) { registerInputIfNeeded: function (name) {
var _this = this;
if (this.hasInput(name)) { if (this.hasInput(name)) {
return; return;
} }
@@ -328,8 +336,7 @@ function updatePorts(nodeId, parameters, editorConnection, graphModel) {
var p = props[key]; var p = props[key];
if (ports.find((_p) => _p.name === key)) continue; if (ports.find((_p) => _p.name === key)) continue;
if (p.type === 'Relation') { if (p.type !== 'Relation') {
} else {
// Other schema type ports // Other schema type ports
const _typeMap = { const _typeMap = {
String: 'string', String: 'string',
@@ -373,16 +380,16 @@ module.exports = {
function _managePortsForNode(node) { function _managePortsForNode(node) {
updatePorts(node.id, node.parameters, context.editorConnection, graphModel); updatePorts(node.id, node.parameters, context.editorConnection, graphModel);
node.on('parameterUpdated', function (event) { node.on('parameterUpdated', function () {
updatePorts(node.id, node.parameters, context.editorConnection, graphModel); updatePorts(node.id, node.parameters, context.editorConnection, graphModel);
}); });
graphModel.on('metadataChanged.dbCollections', function (data) { graphModel.on('metadataChanged.dbCollections', function () {
CloudStore.invalidateCollections(); CloudStore.invalidateCollections();
updatePorts(node.id, node.parameters, context.editorConnection, graphModel); updatePorts(node.id, node.parameters, context.editorConnection, graphModel);
}); });
graphModel.on('metadataChanged.systemCollections', function (data) { graphModel.on('metadataChanged.systemCollections', function () {
CloudStore.invalidateCollections(); CloudStore.invalidateCollections();
updatePorts(node.id, node.parameters, context.editorConnection, graphModel); updatePorts(node.id, node.parameters, context.editorConnection, graphModel);
}); });

View File

@@ -1,10 +1,9 @@
'use strict'; 'use strict';
const { Node } = require('@noodl/runtime'); const { Node } = require('@noodl/runtime');
const Model = require('@noodl/runtime/src/model');
var Model = require('@noodl/runtime/src/model'); const VariableNodeDefinition = {
var VariableNodeDefinition = {
name: 'Variable', name: 'Variable',
docs: 'https://docs.noodl.net/nodes/data/variable', docs: 'https://docs.noodl.net/nodes/data/variable',
category: 'Data', category: 'Data',