From c4ce158bd87ee837b54f5b7b7a4d7610296c214b Mon Sep 17 00:00:00 2001 From: Tyler Schicke Date: Sat, 13 Apr 2019 14:10:12 -0400 Subject: Fixed bug with database synchronization --- src/server/database.ts | 39 ++++++++++++++++++++------------------- 1 file changed, 20 insertions(+), 19 deletions(-) (limited to 'src/server/database.ts') diff --git a/src/server/database.ts b/src/server/database.ts index 0bc806253..f0435a6c1 100644 --- a/src/server/database.ts +++ b/src/server/database.ts @@ -18,31 +18,32 @@ export class Database { if (this.db) { let collection = this.db.collection('documents'); const prom = this.currentWrites[id]; - const run = (promise: Promise, resolve?: () => void) => { - collection.updateOne({ _id: id }, { $set: value }, { - upsert: true - }, (err, res) => { - if (err) { - console.log(err.message); - console.log(err.errmsg); - } - // if (res) { - // console.log(JSON.stringify(res.result)); - // } - if (this.currentWrites[id] === promise) { - delete this.currentWrites[id]; - } - if (resolve) { + let newProm: Promise; + const run = (): Promise => { + return new Promise(resolve => { + collection.updateOne({ _id: id }, { $set: value }, { + upsert: true + }, (err, res) => { + if (err) { + console.log(err.message); + console.log(err.errmsg); + } + // if (res) { + // console.log(JSON.stringify(res.result)); + // } + if (this.currentWrites[id] === newProm) { + delete this.currentWrites[id]; + } resolve(); - } - callback(); + callback(); + }); }); }; if (prom) { - const newProm: Promise = prom.then(() => run(newProm)); + newProm = prom.then(run); this.currentWrites[id] = newProm; } else { - const newProm: Promise = new Promise(res => run(newProm, res)); + newProm = run(); this.currentWrites[id] = newProm; } } -- cgit v1.2.3-70-g09d2 From c83093bb29c1f6d0e580385d9e7c5eb5f5846ac6 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Sat, 13 Apr 2019 14:38:49 -0400 Subject: some clean up --- src/Utils.ts | 10 +-- .../collections/collectionFreeForm/MarqueeView.tsx | 3 +- src/server/Client.ts | 11 ++- src/server/database.ts | 78 +++++++--------------- 4 files changed, 31 insertions(+), 71 deletions(-) (limited to 'src/server/database.ts') diff --git a/src/Utils.ts b/src/Utils.ts index ff55a2e4e..c629bc263 100644 --- a/src/Utils.ts +++ b/src/Utils.ts @@ -87,16 +87,12 @@ export class Utils { } } -export function returnTrue() { - return true; -} +export function returnTrue() { return true; } -export function returnFalse() { - return false; -} +export function returnFalse() { return false; } export function emptyFunction() { } -export function emptyDocFunction(doc: Document) { console.log("focus " + doc.Title); } +export function emptyDocFunction(doc: Document) { } export type Without = Pick>; \ No newline at end of file diff --git a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx index ccc2fcf0c..a4722a6f8 100644 --- a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx +++ b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx @@ -7,13 +7,12 @@ import { KeyStore } from "../../../../fields/KeyStore"; import { Documents } from "../../../documents/Documents"; import { SelectionManager } from "../../../util/SelectionManager"; import { Transform } from "../../../util/Transform"; +import { undoBatch } from "../../../util/UndoManager"; import { InkingCanvas } from "../../InkingCanvas"; import { PreviewCursor } from "../../PreviewCursor"; import { CollectionFreeFormView } from "./CollectionFreeFormView"; import "./MarqueeView.scss"; import React = require("react"); -import { undo } from "prosemirror-history"; -import { undoBatch } from "../../../util/UndoManager"; interface MarqueeViewProps { getContainerTransform: () => Transform; diff --git a/src/server/Client.ts b/src/server/Client.ts index 02402a5a0..b4c419438 100644 --- a/src/server/Client.ts +++ b/src/server/Client.ts @@ -1,15 +1,12 @@ import { computed } from "mobx"; export class Client { + private _guid: string; + constructor(guid: string) { - this.guid = guid; + this._guid = guid; } - private guid: string; - - @computed - public get GUID(): string { - return this.guid; - } + @computed public get GUID(): string { return this._guid; } } \ No newline at end of file diff --git a/src/server/database.ts b/src/server/database.ts index 0bc806253..51eefeb8d 100644 --- a/src/server/database.ts +++ b/src/server/database.ts @@ -7,9 +7,7 @@ export class Database { private db?: mongodb.Db; constructor() { - this.MongoClient.connect(this.url, (err, client) => { - this.db = client.db(); - }); + this.MongoClient.connect(this.url, (err, client) => this.db = client.db()); } private currentWrites: { [_id: string]: Promise } = {}; @@ -21,14 +19,11 @@ export class Database { const run = (promise: Promise, resolve?: () => void) => { collection.updateOne({ _id: id }, { $set: value }, { upsert: true - }, (err, res) => { + }, (err, result) => { if (err) { console.log(err.message); console.log(err.errmsg); } - // if (res) { - // console.log(JSON.stringify(res.result)); - // } if (this.currentWrites[id] === promise) { delete this.currentWrites[id]; } @@ -38,70 +33,43 @@ export class Database { callback(); }); }; - if (prom) { - const newProm: Promise = prom.then(() => run(newProm)); - this.currentWrites[id] = newProm; - } else { - const newProm: Promise = new Promise(res => run(newProm, res)); - this.currentWrites[id] = newProm; - } + + let newProm: Promise = new Promise(resolve => run(newProm, resolve)); + this.currentWrites[id] = newProm; + if (prom) + prom.then(() => newProm); + else newProm; } } public delete(id: string) { - if (this.db) { - let collection = this.db.collection('documents'); - collection.remove({ _id: id }); - } + this.db && this.db.collection('documents').remove({ _id: id }); } public deleteAll(collectionName: string = 'documents'): Promise { - return new Promise(res => { - if (this.db) { - let collection = this.db.collection(collectionName); - collection.deleteMany({}, res); - } - }); + return new Promise(res => + this.db && this.db.collection(collectionName).deleteMany({}, res)); } public insert(kvpairs: any) { - if (this.db) { - let collection = this.db.collection('documents'); - collection.insertOne(kvpairs, (err: any, res: any) => { - if (err) { - // console.log(err) - return; - } - }); - } + this.db && this.db.collection('documents').insertOne(kvpairs, (err: any, res: any) => + err // && console.log(err) + ); } public getDocument(id: string, fn: (res: any) => void) { - var result: JSON; - if (this.db) { - let collection = this.db.collection('documents'); - collection.findOne({ _id: id }, (err: any, res: any) => { - result = res; - if (!result) { - fn(undefined); - } - fn(result); - }); - } + this.db && this.db.collection('documents').findOne({ _id: id }, (err: any, result: any) => + fn(result ? result : undefined)); } public getDocuments(ids: string[], fn: (res: any) => void) { - if (this.db) { - let collection = this.db.collection('documents'); - let cursor = collection.find({ _id: { "$in": ids } }); - cursor.toArray((err, docs) => { - if (err) { - console.log(err.message); - console.log(err.errmsg); - } - fn(docs); - }); - } + this.db && this.db.collection('documents').find({ _id: { "$in": ids } }).toArray((err, docs) => { + if (err) { + console.log(err.message); + console.log(err.errmsg); + } + fn(docs); + }); } public print() { -- cgit v1.2.3-70-g09d2 From a23b160d19beff9163f970f7ae678c2aed9ce14e Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Sat, 13 Apr 2019 15:27:57 -0400 Subject: some code tweaking --- src/server/database.ts | 26 +++++------ src/server/index.ts | 124 ++++++++++++++++++------------------------------- 2 files changed, 58 insertions(+), 92 deletions(-) (limited to 'src/server/database.ts') diff --git a/src/server/database.ts b/src/server/database.ts index 6cc9945b9..e08385d98 100644 --- a/src/server/database.ts +++ b/src/server/database.ts @@ -1,20 +1,20 @@ import * as mongodb from 'mongodb'; export class Database { + public static DocumentsCollection = 'documents'; public static Instance = new Database(); private MongoClient = mongodb.MongoClient; private url = 'mongodb://localhost:27017/Dash'; + private currentWrites: { [_id: string]: Promise } = {}; private db?: mongodb.Db; constructor() { this.MongoClient.connect(this.url, (err, client) => this.db = client.db()); } - private currentWrites: { [_id: string]: Promise } = {}; - - public update(id: string, value: any, callback: () => void) { + public update(id: string, value: any, callback: () => void, collectionName = Database.DocumentsCollection) { if (this.db) { - let collection = this.db.collection('documents'); + let collection = this.db.collection(collectionName); const prom = this.currentWrites[id]; const run = (): Promise => { let newProm = new Promise(resolve => { @@ -40,28 +40,28 @@ export class Database { } } - public delete(id: string) { - this.db && this.db.collection('documents').remove({ _id: id }); + public delete(id: string, collectionName = Database.DocumentsCollection) { + this.db && this.db.collection(collectionName).remove({ _id: id }); } - public deleteAll(collectionName: string = 'documents'): Promise { + public deleteAll(collectionName = Database.DocumentsCollection): Promise { return new Promise(res => this.db && this.db.collection(collectionName).deleteMany({}, res)); } - public insert(kvpairs: any) { - this.db && this.db.collection('documents').insertOne(kvpairs, (err: any, res: any) => + public insert(kvpairs: any, collectionName = Database.DocumentsCollection) { + this.db && this.db.collection(collectionName).insertOne(kvpairs, (err, res) => err // && console.log(err) ); } - public getDocument(id: string, fn: (res: any) => void) { - this.db && this.db.collection('documents').findOne({ _id: id }, (err: any, result: any) => + public getDocument(id: string, fn: (res: any) => void, collectionName = Database.DocumentsCollection) { + this.db && this.db.collection(collectionName).findOne({ _id: id }, (err, result) => fn(result ? result : undefined)); } - public getDocuments(ids: string[], fn: (res: any) => void) { - this.db && this.db.collection('documents').find({ _id: { "$in": ids } }).toArray((err, docs) => { + public getDocuments(ids: string[], fn: (res: any) => void, collectionName = Database.DocumentsCollection) { + this.db && this.db.collection(collectionName).find({ _id: { "$in": ids } }).toArray((err, docs) => { if (err) { console.log(err.message); console.log(err.errmsg); diff --git a/src/server/index.ts b/src/server/index.ts index b9c7448b4..a6fe6fa2c 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -1,49 +1,45 @@ +import * as bodyParser from 'body-parser'; +import { exec } from 'child_process'; +import * as cookieParser from 'cookie-parser'; import * as express from 'express'; -const app = express(); -import * as webpack from 'webpack'; -import * as wdm from 'webpack-dev-middleware'; -import * as whm from 'webpack-hot-middleware'; -import * as path from 'path'; +import * as session from 'express-session'; +import * as expressValidator from 'express-validator'; import * as formidable from 'formidable'; +import * as fs from 'fs'; +import * as mobileDetect from 'mobile-detect'; +import { ObservableMap } from 'mobx'; import * as passport from 'passport'; -import { MessageStore, Transferable } from "./Message"; -import { Client } from './Client'; +import * as path from 'path'; +import * as request from 'request'; +import * as io from 'socket.io'; import { Socket } from 'socket.io'; +import * as webpack from 'webpack'; +import * as wdm from 'webpack-dev-middleware'; +import * as whm from 'webpack-hot-middleware'; +import { Field, FieldId } from '../fields/Field'; import { Utils } from '../Utils'; -import { ObservableMap } from 'mobx'; -import { FieldId, Field } from '../fields/Field'; +import { getForgot, getLogin, getLogout, getReset, getSignup, postForgot, postLogin, postReset, postSignup } from './authentication/controllers/user_controller'; +import { DashUserModel } from './authentication/models/user_model'; +import { Client } from './Client'; import { Database } from './database'; -import * as io from 'socket.io'; -import { getLogin, postLogin, getSignup, postSignup, getLogout, postReset, getForgot, postForgot, getReset } from './authentication/controllers/user_controller'; +import { MessageStore, Transferable } from "./Message"; +import { RouteStore } from './RouteStore'; +const app = express(); const config = require('../../webpack.config'); const compiler = webpack(config); const port = 1050; // default port to listen const serverPort = 4321; -import * as expressValidator from 'express-validator'; import expressFlash = require('express-flash'); import flash = require('connect-flash'); -import * as bodyParser from 'body-parser'; -import * as session from 'express-session'; -import * as cookieParser from 'cookie-parser'; -import * as mobileDetect from 'mobile-detect'; import c = require("crypto"); const MongoStore = require('connect-mongo')(session); const mongoose = require('mongoose'); -import { DashUserModel } from './authentication/models/user_model'; -import * as fs from 'fs'; -import * as request from 'request'; -import { RouteStore } from './RouteStore'; -import { exec } from 'child_process'; -const download = (url: string, dest: fs.PathLike) => { - request.get(url).pipe(fs.createWriteStream(dest)); -}; +const download = (url: string, dest: fs.PathLike) => request.get(url).pipe(fs.createWriteStream(dest));; const mongoUrl = 'mongodb://localhost:27017/Dash'; mongoose.connect(mongoUrl); -mongoose.connection.on('connected', function () { - console.log("connected"); -}); +mongoose.connection.on('connected', () => console.log("connected")); // SESSION MANAGEMENT AND AUTHENTICATION MIDDLEWARE // ORDER OF IMPORTS MATTERS @@ -54,9 +50,7 @@ app.use(session({ resave: true, cookie: { maxAge: 7 * 24 * 60 * 60 * 1000 }, saveUninitialized: true, - store: new MongoStore({ - url: 'mongodb://localhost:27017/Dash' - }) + store: new MongoStore({ url: 'mongodb://localhost:27017/Dash' }) })); app.use(flash()); @@ -71,9 +65,7 @@ app.use((req, res, next) => { next(); }); -app.get("/hello", (req, res) => { - res.send("

Hello

"); -}); +app.get("/hello", (req, res) => res.send("

Hello

")); enum Method { GET, @@ -112,21 +104,17 @@ function addSecureRoute(method: Method, } // STATIC FILE SERVING - -let FieldStore: ObservableMap = new ObservableMap(); - app.use(express.static(__dirname + RouteStore.public)); app.use(RouteStore.images, express.static(__dirname + RouteStore.public)); -app.get("/pull", (req, res) => { +app.get("/pull", (req, res) => exec('"C:\\Program Files\\Git\\git-bash.exe" -c "git pull"', (err, stdout, stderr) => { if (err) { res.send(err.message); return; } res.redirect("/"); - }); -}); + })); // GETTERS @@ -143,11 +131,8 @@ addSecureRoute( Method.GET, (user, res, req) => { let detector = new mobileDetect(req.headers['user-agent'] || ""); - if (detector.mobile() !== null) { - res.sendFile(path.join(__dirname, '../../deploy/mobile/image.html')); - } else { - res.sendFile(path.join(__dirname, '../../deploy/index.html')); - } + let filename = detector.mobile() !== null ? 'mobile/image.html' : 'index.html'; + res.sendFile(path.join(__dirname, '../../deploy/' + filename)); }, undefined, RouteStore.home, @@ -163,12 +148,7 @@ addSecureRoute( addSecureRoute( Method.GET, - (user, res) => { - res.send(JSON.stringify({ - id: user.id, - email: user.email - })); - }, + (user, res) => res.send(JSON.stringify({ id: user.id, email: user.email })), undefined, RouteStore.getCurrUser ); @@ -185,10 +165,9 @@ addSecureRoute( console.log("upload"); form.parse(req, (err, fields, files) => { console.log("parsing"); - let names: any[] = []; + let names: string[] = []; for (const name in files) { - let file = files[name]; - names.push(`/files/` + path.basename(file.path)); + names.push(`/files/` + path.basename(files[name].path)); } res.send(names); }); @@ -218,28 +197,22 @@ app.post(RouteStore.forgot, postForgot); app.get(RouteStore.reset, getReset); app.post(RouteStore.reset, postReset); -app.use(RouteStore.corsProxy, (req, res) => { - req.pipe(request(req.url.substring(1))).pipe(res); -}); +app.use(RouteStore.corsProxy, (req, res) => + req.pipe(request(req.url.substring(1))).pipe(res)); -app.get(RouteStore.delete, (req, res) => { - deleteFields().then(() => res.redirect(RouteStore.home)); -}); +app.get(RouteStore.delete, (req, res) => + deleteFields().then(() => res.redirect(RouteStore.home))); -app.get(RouteStore.deleteAll, (req, res) => { - deleteAll().then(() => res.redirect(RouteStore.home)); -}); +app.get(RouteStore.deleteAll, (req, res) => + deleteAll().then(() => res.redirect(RouteStore.home))); -app.use(wdm(compiler, { - publicPath: config.output.publicPath -})); +app.use(wdm(compiler, { publicPath: config.output.publicPath })); app.use(whm(compiler)); // start the Express server -app.listen(port, () => { - console.log(`server started at http://localhost:${port}`); -}); +app.listen(port, () => + console.log(`server started at http://localhost:${port}`)); const server = io(); interface Map { @@ -274,14 +247,8 @@ function barReceived(guid: String) { } function getField([id, callback]: [string, (result: any) => void]) { - Database.Instance.getDocument(id, (result: any) => { - if (result) { - callback(result); - } - else { - callback(undefined); - } - }); + Database.Instance.getDocument(id, (result: any) => + callback(result ? result : undefined)); } function getFields([ids, callback]: [string[], (result: any) => void]) { @@ -289,9 +256,8 @@ function getFields([ids, callback]: [string[], (result: any) => void]) { } function setField(socket: Socket, newValue: Transferable) { - Database.Instance.update(newValue._id, newValue, () => { - socket.broadcast.emit(MessageStore.SetField.Message, newValue); - }); + Database.Instance.update(newValue._id, newValue, () => + socket.broadcast.emit(MessageStore.SetField.Message, newValue)); } server.listen(serverPort); -- cgit v1.2.3-70-g09d2 From 22888445b70e374cec082933505017c66bf1fba6 Mon Sep 17 00:00:00 2001 From: Tyler Schicke Date: Sat, 13 Apr 2019 17:46:14 -0400 Subject: Re-fixed database stuff and added DocumentText to formatted text --- src/client/views/nodes/FormattedTextBox.tsx | 3 +++ src/server/database.ts | 7 ++++--- 2 files changed, 7 insertions(+), 3 deletions(-) (limited to 'src/server/database.ts') diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index 8ea747b1c..3a2a8a554 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -14,6 +14,8 @@ import { Main } from "../Main"; import { FieldView, FieldViewProps } from "./FieldView"; import "./FormattedTextBox.scss"; import React = require("react"); +import { TextField } from "../../../fields/TextField"; +import { KeyStore } from "../../../fields/KeyStore"; const { buildMenuItems } = require("prosemirror-example-setup"); const { menuBar } = require("prosemirror-menu"); @@ -64,6 +66,7 @@ export class FormattedTextBox extends React.Component<(FieldViewProps & Formatte JSON.stringify(state.toJSON()), RichTextField ); + this.props.Document.SetDataOnPrototype(KeyStore.DocumentText, state.doc.textBetween(0, state.doc.content.size, "\n\n"), TextField); // doc.SetData(fieldKey, JSON.stringify(state.toJSON()), RichTextField); } } diff --git a/src/server/database.ts b/src/server/database.ts index e08385d98..3290edde0 100644 --- a/src/server/database.ts +++ b/src/server/database.ts @@ -16,8 +16,9 @@ export class Database { if (this.db) { let collection = this.db.collection(collectionName); const prom = this.currentWrites[id]; + let newProm: Promise; const run = (): Promise => { - let newProm = new Promise(resolve => { + return new Promise(resolve => { collection.updateOne({ _id: id }, { $set: value }, { upsert: true } , (err, res) => { if (err) { @@ -34,9 +35,9 @@ export class Database { callback(); }); }); - return newProm; }; - this.currentWrites[id] = prom ? prom.then(run) : run(); + newProm = prom ? prom.then(run) : run(); + this.currentWrites[id] = newProm; } } -- cgit v1.2.3-70-g09d2 From d6fd8338a440085c1ba865c4771c0871208e961e Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Sat, 13 Apr 2019 19:39:37 -0400 Subject: cleaning up network data transfer. --- src/Utils.ts | 4 +- src/client/Server.ts | 20 +-- src/client/SocketStub.ts | 58 ++------- src/client/northstar/dash-fields/HistogramField.ts | 5 +- src/fields/AudioField.ts | 4 +- src/fields/BooleanField.ts | 4 +- src/fields/Document.ts | 17 +-- src/fields/DocumentReference.ts | 4 +- src/fields/Field.ts | 4 +- src/fields/HtmlField.ts | 4 +- src/fields/ImageField.ts | 4 +- src/fields/InkField.ts | 4 +- src/fields/Key.ts | 4 +- src/fields/ListField.ts | 4 +- src/fields/NumberField.ts | 4 +- src/fields/PDFField.ts | 4 +- src/fields/RichTextField.ts | 4 +- src/fields/ScriptField.ts | 4 +- src/fields/TextField.ts | 4 +- src/fields/TupleField.ts | 4 +- src/fields/VideoField.ts | 4 +- src/fields/WebField.ts | 4 +- src/server/Message.ts | 137 ++------------------- src/server/ServerUtil.ts | 99 ++++++--------- src/server/database.ts | 64 +++++----- src/server/index.ts | 8 +- 26 files changed, 150 insertions(+), 330 deletions(-) (limited to 'src/server/database.ts') diff --git a/src/Utils.ts b/src/Utils.ts index c629bc263..2e672db9a 100644 --- a/src/Utils.ts +++ b/src/Utils.ts @@ -1,7 +1,7 @@ import v4 = require('uuid/v4'); import v5 = require("uuid/v5"); import { Socket } from 'socket.io'; -import { Message, Types } from './server/Message'; +import { Message, Types, Transferable } from './server/Message'; import { Document } from './fields/Document'; export class Utils { @@ -48,7 +48,7 @@ export class Utils { if (this.logFilter !== undefined && this.logFilter !== message.type) { return; } - let idString = (message._id || message.id || "").padStart(36, ' '); + let idString = (message.id || message.id || "").padStart(36, ' '); prefix = prefix.padEnd(16, ' '); console.log(`${prefix}: ${idString}, ${receiving ? 'receiving' : 'sending'} ${messageName} with data ${JSON.stringify(message)}`); } diff --git a/src/client/Server.ts b/src/client/Server.ts index 3bbbebe72..66e9878d9 100644 --- a/src/client/Server.ts +++ b/src/client/Server.ts @@ -12,7 +12,6 @@ export class Server { static Socket: SocketIOClient.Socket = OpenSocket(`${window.location.protocol}//${window.location.hostname}:4321`); static GUID: string = Utils.GenerateGuid(); - // Retrieves the cached value of the field and sends a request to the server for the real value (if it's not cached). // Call this is from within a reaction and test whether the return value is FieldWaiting. public static GetField(fieldid: FieldId): Promise>; @@ -127,13 +126,6 @@ export class Server { } } - public static AddDocument(document: Document) { - SocketStub.SEND_ADD_DOCUMENT(document); - } - public static AddDocumentField(doc: Document, key: Key, value: Field) { - console.log("Add doc field " + doc.Title + " " + key.Name + " fid " + value.Id + " " + value); - SocketStub.SEND_ADD_DOCUMENT_FIELD(doc, key, value); - } public static DeleteDocumentField(doc: Document, key: Key) { SocketStub.SEND_DELETE_DOCUMENT_FIELD(doc, key); } @@ -161,18 +153,18 @@ export class Server { } @action - static updateField(field: { _id: string, data: any, type: Types }) { - if (Server.ClientFieldsCached.has(field._id)) { - var f = Server.ClientFieldsCached.get(field._id); + static updateField(field: { id: string, data: any, type: Types }) { + if (Server.ClientFieldsCached.has(field.id)) { + var f = Server.ClientFieldsCached.get(field.id); if (f) { - // console.log("Applying : " + field._id); + // console.log("Applying : " + field.id); f.UpdateFromServer(field.data); f.init(emptyFunction); } else { - // console.log("Not applying wa : " + field._id); + // console.log("Not applying wa : " + field.id); } } else { - // console.log("Not applying mi : " + field._id); + // console.log("Not applying mi : " + field.id); } } } diff --git a/src/client/SocketStub.ts b/src/client/SocketStub.ts index 5e2ca6a98..382a81f66 100644 --- a/src/client/SocketStub.ts +++ b/src/client/SocketStub.ts @@ -2,7 +2,7 @@ import { Key } from "../fields/Key"; import { Field, FieldId, Opt } from "../fields/Field"; import { ObservableMap } from "mobx"; import { Document } from "../fields/Document"; -import { MessageStore, DocumentTransfer } from "../server/Message"; +import { MessageStore, Transferable } from "../server/Message"; import { Utils } from "../Utils"; import { Server } from "./Server"; import { ServerUtils } from "../server/ServerUtil"; @@ -16,35 +16,12 @@ export interface FieldMap { export class SocketStub { static FieldStore: ObservableMap = new ObservableMap(); - public static SEND_ADD_DOCUMENT(document: Document) { - - // Send a serialized version of the document to the server - // ...SOCKET(ADD_DOCUMENT, serialied document) - - // server stores each document field in its repository of stored fields - // document.fields.forEach((f, key) => this.FieldStore.set((f as Field).Id, f as Field)); - // let strippedDoc = new Document(document.Id); - // document.fields.forEach((f, key) => { - // if (f) { - // // let args: SetFieldArgs = new SetFieldArgs(f.Id, f.GetValue()) - // let args: Transferable = f.ToJson() - // Utils.Emit(Server.Socket, MessageStore.SetField, args) - // } - // }) - - // // server stores stripped down document (w/ only field id proxies) in the field store - // this.FieldStore.set(document.Id, new Document(document.Id)); - // document.fields.forEach((f, key) => (this.FieldStore.get(document.Id) as Document)._proxies.set(key.Id, (f as Field).Id)); - - console.log("sending " + document.Title); - Utils.Emit(Server.Socket, MessageStore.AddDocument, new DocumentTransfer(document.ToJson())); - } public static SEND_FIELD_REQUEST(fieldid: FieldId): Promise>; public static SEND_FIELD_REQUEST(fieldid: FieldId, callback: (field: Opt) => void): void; public static SEND_FIELD_REQUEST(fieldid: FieldId, callback?: (field: Opt) => void): Promise> | void { let fn = function (cb: (field: Opt) => void) { - Utils.EmitCallback(Server.Socket, MessageStore.GetField, fieldid, (field: any) => { + Utils.EmitCallback(Server.Socket, MessageStore.GetField, fieldid, (field: Transferable) => { if (field) { ServerUtils.FromJson(field).init(cb); } else { @@ -60,36 +37,15 @@ export class SocketStub { } public static SEND_FIELDS_REQUEST(fieldIds: FieldId[], callback: (fields: FieldMap) => any) { - Utils.EmitCallback(Server.Socket, MessageStore.GetFields, fieldIds, (fields: any[]) => { - let fieldMap: any = {}; - let proms: Promise[] = []; - for (let field of fields) { - let f = ServerUtils.FromJson(field); - fieldMap[field._id] = f; - proms.push(new Promise(res => f.init(res))); - } + Utils.EmitCallback(Server.Socket, MessageStore.GetFields, fieldIds, (fields: Transferable[]) => { + let fieldMap: FieldMap = {}; + fields.map(field => fieldMap[field.id] = ServerUtils.FromJson(field)); + let proms = Object.values(fieldMap).map(val => + new Promise(resolve => val!.init(resolve))); Promise.all(proms).then(() => callback(fieldMap)); }); } - public static SEND_ADD_DOCUMENT_FIELD(doc: Document, key: Key, value: Field) { - - // Send a serialized version of the field to the server along with the - // associated info of the document id and key where it is used. - - // ...SOCKET(ADD_DOCUMENT_FIELD, document id, key id, serialized field) - - // server updates its document to hold a proxy mapping from key => fieldId - var document = this.FieldStore.get(doc.Id) as Document; - if (document) { - document._proxies.set(key.Id, value.Id); - } - - // server adds the field to its repository of fields - this.FieldStore.set(value.Id, value); - // Utils.Emit(Server.Socket, MessageStore.AddDocument, new DocumentTransfer(doc.ToJson())) - } - public static SEND_DELETE_DOCUMENT_FIELD(doc: Document, key: Key) { // Send a request to delete the field stored under the specified key from the document diff --git a/src/client/northstar/dash-fields/HistogramField.ts b/src/client/northstar/dash-fields/HistogramField.ts index 6abde4677..82de51d56 100644 --- a/src/client/northstar/dash-fields/HistogramField.ts +++ b/src/client/northstar/dash-fields/HistogramField.ts @@ -35,12 +35,11 @@ export class HistogramField extends BasicField { } - ToJson(): { type: Types, data: string, _id: string } { + ToJson() { return { type: Types.HistogramOp, - data: this.toString(), - _id: this.Id + id: this.Id }; } diff --git a/src/fields/AudioField.ts b/src/fields/AudioField.ts index 996d2556d..87e47a715 100644 --- a/src/fields/AudioField.ts +++ b/src/fields/AudioField.ts @@ -20,11 +20,11 @@ export class AudioField extends BasicField { return new AudioField(this.Data); } - ToJson(): { type: Types, data: string, _id: string } { + ToJson() { return { type: Types.Audio, data: this.Data.href, - _id: this.Id + id: this.Id }; } diff --git a/src/fields/BooleanField.ts b/src/fields/BooleanField.ts index d319b4021..d49bfe82b 100644 --- a/src/fields/BooleanField.ts +++ b/src/fields/BooleanField.ts @@ -15,11 +15,11 @@ export class BooleanField extends BasicField { return new BooleanField(this.Data); } - ToJson(): { type: Types; data: boolean; _id: string } { + ToJson() { return { type: Types.Boolean, data: this.Data, - _id: this.Id + id: this.Id }; } } diff --git a/src/fields/Document.ts b/src/fields/Document.ts index 628fe684c..7cf784f0e 100644 --- a/src/fields/Document.ts +++ b/src/fields/Document.ts @@ -26,6 +26,12 @@ export class Document extends Field { Server.UpdateField(this); } } + static FromJson(data: any, id: string, save: boolean): Document { + let doc = new Document(id, save); + let fields = data as [string, string][]; + fields.forEach(pair => doc._proxies.set(pair[0], pair[1])); + return doc; + } UpdateFromServer(data: [string, string][]) { for (const key in data) { @@ -410,18 +416,15 @@ export class Document extends Field { return copy; } - ToJson(): { type: Types; data: [string, string][]; _id: string } { + ToJson() { let fields: [string, string][] = []; - this._proxies.forEach((field, key) => { - if (field) { - fields.push([key, field]); - } - }); + this._proxies.forEach((field, key) => + field && fields.push([key, field])); return { type: Types.Document, data: fields, - _id: this.Id + id: this.Id }; } } diff --git a/src/fields/DocumentReference.ts b/src/fields/DocumentReference.ts index 6c0c1ef82..303754177 100644 --- a/src/fields/DocumentReference.ts +++ b/src/fields/DocumentReference.ts @@ -47,11 +47,11 @@ export class DocumentReference extends Field { return ""; } - ToJson(): { type: Types, data: FieldId, _id: string } { + ToJson() { return { type: Types.DocumentReference, data: this.document.Id, - _id: this.Id + id: this.Id }; } } \ No newline at end of file diff --git a/src/fields/Field.ts b/src/fields/Field.ts index d9db23b9e..3b3e95c2b 100644 --- a/src/fields/Field.ts +++ b/src/fields/Field.ts @@ -1,6 +1,6 @@ import { Utils } from "../Utils"; -import { Types } from "../server/Message"; +import { Types, Transferable } from "../server/Message"; import { computed } from "mobx"; export function Cast(field: FieldValue, ctor: { new(): T }): Opt { @@ -65,5 +65,5 @@ export abstract class Field { abstract Copy(): Field; - abstract ToJson(): { _id: string, type: Types, data: any }; + abstract ToJson(): Transferable; } \ No newline at end of file diff --git a/src/fields/HtmlField.ts b/src/fields/HtmlField.ts index 65665cf7a..a1d880070 100644 --- a/src/fields/HtmlField.ts +++ b/src/fields/HtmlField.ts @@ -15,11 +15,11 @@ export class HtmlField extends BasicField { return new HtmlField(this.Data); } - ToJson(): { _id: string; type: Types; data: string; } { + ToJson() { return { type: Types.Html, data: this.Data, - _id: this.Id, + id: this.Id, }; } } \ No newline at end of file diff --git a/src/fields/ImageField.ts b/src/fields/ImageField.ts index dd843026f..bce20f242 100644 --- a/src/fields/ImageField.ts +++ b/src/fields/ImageField.ts @@ -19,11 +19,11 @@ export class ImageField extends BasicField { return new ImageField(this.Data); } - ToJson(): { type: Types, data: string, _id: string } { + ToJson() { return { type: Types.Image, data: this.Data.href, - _id: this.Id + id: this.Id }; } } \ No newline at end of file diff --git a/src/fields/InkField.ts b/src/fields/InkField.ts index ab706ee30..2eacd7d0c 100644 --- a/src/fields/InkField.ts +++ b/src/fields/InkField.ts @@ -31,11 +31,11 @@ export class InkField extends BasicField { return new InkField(this.Data); } - ToJson(): { _id: string; type: Types; data: any; } { + ToJson() { return { type: Types.Ink, data: this.Data, - _id: this.Id, + id: this.Id, }; } diff --git a/src/fields/Key.ts b/src/fields/Key.ts index c7f806b88..57e2dadf0 100644 --- a/src/fields/Key.ts +++ b/src/fields/Key.ts @@ -40,11 +40,11 @@ export class Key extends Field { return name; } - ToJson(): { type: Types, data: string, _id: string } { + ToJson() { return { type: Types.Key, data: this.name, - _id: this.Id + id: this.Id }; } } \ No newline at end of file diff --git a/src/fields/ListField.ts b/src/fields/ListField.ts index 8311e737b..e24099126 100644 --- a/src/fields/ListField.ts +++ b/src/fields/ListField.ts @@ -176,14 +176,14 @@ export class ListField extends BasicField { this._proxies = data.fields; this._scriptIds = data.scripts; } - ToJson(): { type: Types, data: { fields: string[], scripts: string[] }, _id: string } { + ToJson() { return { type: Types.List, data: { fields: this._proxies, scripts: this._scriptIds, }, - _id: this.Id + id: this.Id }; } diff --git a/src/fields/NumberField.ts b/src/fields/NumberField.ts index 45b920e31..7eea360c0 100644 --- a/src/fields/NumberField.ts +++ b/src/fields/NumberField.ts @@ -15,9 +15,9 @@ export class NumberField extends BasicField { return new NumberField(this.Data); } - ToJson(): { _id: string, type: Types, data: number } { + ToJson() { return { - _id: this.Id, + id: this.Id, type: Types.Number, data: this.Data }; diff --git a/src/fields/PDFField.ts b/src/fields/PDFField.ts index 65e179894..718a1a4c0 100644 --- a/src/fields/PDFField.ts +++ b/src/fields/PDFField.ts @@ -22,11 +22,11 @@ export class PDFField extends BasicField { return `new PDFField("${this.Data}")`; } - ToJson(): { type: Types, data: string, _id: string } { + ToJson() { return { type: Types.PDF, data: this.Data.href, - _id: this.Id + id: this.Id }; } diff --git a/src/fields/RichTextField.ts b/src/fields/RichTextField.ts index 6f7b3074a..f53f48ca6 100644 --- a/src/fields/RichTextField.ts +++ b/src/fields/RichTextField.ts @@ -15,11 +15,11 @@ export class RichTextField extends BasicField { return new RichTextField(this.Data); } - ToJson(): { type: Types, data: string, _id: string } { + ToJson() { return { type: Types.RichText, data: this.Data, - _id: this.Id + id: this.Id }; } diff --git a/src/fields/ScriptField.ts b/src/fields/ScriptField.ts index 34c8a7544..7f87be45d 100644 --- a/src/fields/ScriptField.ts +++ b/src/fields/ScriptField.ts @@ -73,7 +73,7 @@ export class ScriptField extends Field { }); } - ToJson(): { _id: string, type: Types, data: ScriptData } { + ToJson() { const { options, originalScript } = this.script; let capturedIds: { [id: string]: string } = {}; for (const capt in options.capturedVariables) { @@ -85,7 +85,7 @@ export class ScriptField extends Field { }; delete (opts as any).capturedVariables; return { - _id: this.Id, + id: this.Id, type: Types.Script, data: { script: originalScript, diff --git a/src/fields/TextField.ts b/src/fields/TextField.ts index 69d26f42f..ddedec9b1 100644 --- a/src/fields/TextField.ts +++ b/src/fields/TextField.ts @@ -15,11 +15,11 @@ export class TextField extends BasicField { return new TextField(this.Data); } - ToJson(): { type: Types, data: string, _id: string } { + ToJson() { return { type: Types.Text, data: this.Data, - _id: this.Id + id: this.Id }; } } \ No newline at end of file diff --git a/src/fields/TupleField.ts b/src/fields/TupleField.ts index ad0f6f350..347f1fa05 100644 --- a/src/fields/TupleField.ts +++ b/src/fields/TupleField.ts @@ -49,11 +49,11 @@ export class TupleField extends BasicField<[T, U]> { return new TupleField(this.Data); } - ToJson(): { type: Types, data: [T, U], _id: string } { + ToJson() { return { type: Types.Tuple, data: this.Data, - _id: this.Id + id: this.Id }; } } \ No newline at end of file diff --git a/src/fields/VideoField.ts b/src/fields/VideoField.ts index d7cd7e968..838b811b1 100644 --- a/src/fields/VideoField.ts +++ b/src/fields/VideoField.ts @@ -19,11 +19,11 @@ export class VideoField extends BasicField { return new VideoField(this.Data); } - ToJson(): { type: Types, data: string, _id: string } { + ToJson() { return { type: Types.Video, data: this.Data.href, - _id: this.Id + id: this.Id }; } diff --git a/src/fields/WebField.ts b/src/fields/WebField.ts index 6023e9e6b..8b276a552 100644 --- a/src/fields/WebField.ts +++ b/src/fields/WebField.ts @@ -19,11 +19,11 @@ export class WebField extends BasicField { return new WebField(this.Data); } - ToJson(): { type: Types, data: string, _id: string } { + ToJson() { return { type: Types.Web, data: this.Data.href, - _id: this.Id + id: this.Id }; } diff --git a/src/server/Message.ts b/src/server/Message.ts index d22e5c17c..bbe4ffcad 100644 --- a/src/server/Message.ts +++ b/src/server/Message.ts @@ -1,146 +1,35 @@ import { Utils } from "../Utils"; export class Message { - private name: string; - private guid: string; - - get Name(): string { - return this.name; - } - - get Message(): string { - return this.guid; - } + private _name: string; + private _guid: string; constructor(name: string) { - this.name = name; - this.guid = Utils.GenerateDeterministicGuid(name); - } - - GetValue() { - return this.Name; - } -} - -class TestMessageArgs { - hello: string = ""; -} - -export class SetFieldArgs { - field: string; - value: any; - - constructor(f: string, v: any) { - this.field = f; - this.value = v; + this._name = name; + this._guid = Utils.GenerateDeterministicGuid(name); } -} -export class GetFieldArgs { - field: string; - - constructor(f: string) { - this.field = f; - } + get Name(): string { return this._name; } + get Message(): string { return this._guid; } } export enum Types { - Number, - List, - Key, - Image, - Web, - Document, - Text, - RichText, - DocumentReference, - Html, - Video, - Audio, - Ink, - PDF, - Tuple, - HistogramOp, - Boolean, - Script, -} - -export class DocumentTransfer implements Transferable { - readonly type = Types.Document; - _id: string; - - constructor( - readonly obj: { type: Types; data: [string, string][]; _id: string } - ) { - this._id = obj._id; - } -} - -export class ImageTransfer implements Transferable { - readonly type = Types.Image; - - constructor(readonly _id: string) { } -} - -export class KeyTransfer implements Transferable { - name: string; - readonly _id: string; - readonly type = Types.Key; - - constructor(i: string, n: string) { - this.name = n; - this._id = i; - } -} - -export class ListTransfer implements Transferable { - type = Types.List; - - constructor(readonly _id: string) { } -} - -export class NumberTransfer implements Transferable { - readonly type = Types.Number; - - constructor(readonly value: number, readonly _id: string) { } -} - -export class TextTransfer implements Transferable { - value: string; - readonly _id: string; - readonly type = Types.Text; - - constructor(t: string, i: string) { - this.value = t; - this._id = i; - } -} - -export class RichTextTransfer implements Transferable { - value: string; - readonly _id: string; - readonly type = Types.Text; - - constructor(t: string, i: string) { - this.value = t; - this._id = i; - } + Number, List, Key, Image, Web, Document, Text, RichText, DocumentReference, + Html, Video, Audio, Ink, PDF, Tuple, HistogramOp, Boolean, Script, } export interface Transferable { - readonly _id: string; + readonly id: string; readonly type: Types; + readonly data?: any; } export namespace MessageStore { export const Foo = new Message("Foo"); export const Bar = new Message("Bar"); - export const AddDocument = new Message("Add Document"); - export const SetField = new Message<{ _id: string; data: any; type: Types }>( - "Set Field" - ); - export const GetField = new Message("Get Field"); - export const GetFields = new Message("Get Fields"); + export const SetField = new Message("Set Field"); // send Transferable (no reply) + export const GetField = new Message("Get Field"); // send string 'id' get Transferable back + export const GetFields = new Message("Get Fields"); // send string[] of 'id' get Transferable[] back export const GetDocument = new Message("Get Document"); export const DeleteAll = new Message("Delete All"); } diff --git a/src/server/ServerUtil.ts b/src/server/ServerUtil.ts index 0973f82b1..818230c1a 100644 --- a/src/server/ServerUtil.ts +++ b/src/server/ServerUtil.ts @@ -1,83 +1,56 @@ -import { Field } from "./../fields/Field"; -import { TextField } from "./../fields/TextField"; -import { NumberField } from "./../fields/NumberField"; -import { RichTextField } from "./../fields/RichTextField"; -import { Key } from "./../fields/Key"; -import { ImageField } from "./../fields/ImageField"; -import { ListField } from "./../fields/ListField"; -import { Document } from "./../fields/Document"; -import { Server } from "./../client/Server"; -import { Types } from "./Message"; -import { Utils } from "../Utils"; -import { HtmlField } from "../fields/HtmlField"; -import { WebField } from "../fields/WebField"; +import { HistogramField } from "../client/northstar/dash-fields/HistogramField"; import { AudioField } from "../fields/AudioField"; -import { VideoField } from "../fields/VideoField"; +import { BooleanField } from "../fields/BooleanField"; +import { HtmlField } from "../fields/HtmlField"; import { InkField } from "../fields/InkField"; import { PDFField } from "../fields/PDFField"; -import { TupleField } from "../fields/TupleField"; -import { BooleanField } from "../fields/BooleanField"; -import { HistogramField } from "../client/northstar/dash-fields/HistogramField"; import { ScriptField } from "../fields/ScriptField"; +import { TupleField } from "../fields/TupleField"; +import { VideoField } from "../fields/VideoField"; +import { WebField } from "../fields/WebField"; +import { Utils } from "../Utils"; +import { Document } from "./../fields/Document"; +import { Field } from "./../fields/Field"; +import { ImageField } from "./../fields/ImageField"; +import { Key } from "./../fields/Key"; +import { ListField } from "./../fields/ListField"; +import { NumberField } from "./../fields/NumberField"; +import { RichTextField } from "./../fields/RichTextField"; +import { TextField } from "./../fields/TextField"; +import { Transferable, Types } from "./Message"; export class ServerUtils { public static prepend(extension: string): string { return window.location.origin + extension; } - public static FromJson(json: any): Field { - let obj = json; - let data: any = obj.data; - let id: string = obj._id; - let type: Types = obj.type; + public static FromJson(json: Transferable): Field { - if (!(data !== undefined && id && type !== undefined)) { + if (!(json.data !== undefined && json.id && json.type !== undefined)) { console.log( "how did you manage to get an object that doesn't have a data or an id?" ); return new TextField("Something to fill the space", Utils.GenerateGuid()); } - switch (type) { - case Types.Boolean: - return new BooleanField(data, id, false); - case Types.Number: - return new NumberField(data, id, false); - case Types.Text: - return new TextField(data, id, false); - case Types.Html: - return new HtmlField(data, id, false); - case Types.Web: - return new WebField(new URL(data), id, false); - case Types.RichText: - return new RichTextField(data, id, false); - case Types.Key: - return new Key(data, id, false); - case Types.Image: - return new ImageField(new URL(data), id, false); - case Types.HistogramOp: - return HistogramField.FromJson(id, data); - case Types.PDF: - return new PDFField(new URL(data), id, false); - case Types.List: - return ListField.FromJson(id, data); - case Types.Script: - return ScriptField.FromJson(id, data); - case Types.Audio: - return new AudioField(new URL(data), id, false); - case Types.Video: - return new VideoField(new URL(data), id, false); - case Types.Tuple: - return new TupleField(data, id, false); - case Types.Ink: - return InkField.FromJson(id, data); - case Types.Document: - let doc: Document = new Document(id, false); - let fields: [string, string][] = data as [string, string][]; - fields.forEach(element => { - doc._proxies.set(element[0], element[1]); - }); - return doc; + switch (json.type) { + case Types.Boolean: return new BooleanField(json.data, json.id, false); + case Types.Number: return new NumberField(json.data, json.id, false); + case Types.Text: return new TextField(json.data, json.id, false); + case Types.Html: return new HtmlField(json.data, json.id, false); + case Types.Web: return new WebField(new URL(json.data), json.id, false); + case Types.RichText: return new RichTextField(json.data, json.id, false); + case Types.Key: return new Key(json.data, json.id, false); + case Types.Image: return new ImageField(new URL(json.data), json.id, false); + case Types.HistogramOp: return HistogramField.FromJson(json.id, json.data); + case Types.PDF: return new PDFField(new URL(json.data), json.id, false); + case Types.List: return ListField.FromJson(json.id, json.data); + case Types.Script: return ScriptField.FromJson(json.id, json.data); + case Types.Audio: return new AudioField(new URL(json.data), json.id, false); + case Types.Video: return new VideoField(new URL(json.data), json.id, false); + case Types.Tuple: return new TupleField(json.data, json.id, false); + case Types.Ink: return InkField.FromJson(json.id, json.data); + case Types.Document: return Document.FromJson(json.data, json.id, false); default: throw Error( "Error, unrecognized field type received from server. If you just created a new field type, be sure to add it here" diff --git a/src/server/database.ts b/src/server/database.ts index e08385d98..c51d4a3f6 100644 --- a/src/server/database.ts +++ b/src/server/database.ts @@ -1,47 +1,55 @@ import * as mongodb from 'mongodb'; +import { Transferable } from './Message'; export class Database { public static DocumentsCollection = 'documents'; public static Instance = new Database(); private MongoClient = mongodb.MongoClient; private url = 'mongodb://localhost:27017/Dash'; - private currentWrites: { [_id: string]: Promise } = {}; + private currentWrites: { [id: string]: Promise } = {}; private db?: mongodb.Db; constructor() { this.MongoClient.connect(this.url, (err, client) => this.db = client.db()); } - public update(id: string, value: any, callback: () => void, collectionName = Database.DocumentsCollection) { + public update(id: string, value: any, callback: () => void) { if (this.db) { - let collection = this.db.collection(collectionName); + let collection = this.db.collection('documents'); const prom = this.currentWrites[id]; + let newProm: Promise; const run = (): Promise => { - let newProm = new Promise(resolve => { - collection.updateOne({ _id: id }, { $set: value }, { upsert: true } - , (err, res) => { - if (err) { - console.log(err.message); - console.log(err.errmsg); - } - // if (res) { - // console.log(JSON.stringify(res.result)); - // } - if (this.currentWrites[id] === newProm) { - delete this.currentWrites[id]; - } - resolve(); - callback(); - }); + return new Promise(resolve => { + collection.updateOne({ _id: id }, { $set: value }, { + upsert: true + }, (err, res) => { + if (err) { + console.log(err.message); + console.log(err.errmsg); + } + // if (res) { + // console.log(JSON.stringify(res.result)); + // } + if (this.currentWrites[id] === newProm) { + delete this.currentWrites[id]; + } + resolve(); + callback(); + }); }); - return newProm; }; - this.currentWrites[id] = prom ? prom.then(run) : run(); + if (prom) { + newProm = prom.then(run); + this.currentWrites[id] = newProm; + } else { + newProm = run(); + this.currentWrites[id] = newProm; + } } } public delete(id: string, collectionName = Database.DocumentsCollection) { - this.db && this.db.collection(collectionName).remove({ _id: id }); + this.db && this.db.collection(collectionName).remove({ id: id }); } public deleteAll(collectionName = Database.DocumentsCollection): Promise { @@ -55,18 +63,18 @@ export class Database { ); } - public getDocument(id: string, fn: (res: any) => void, collectionName = Database.DocumentsCollection) { - this.db && this.db.collection(collectionName).findOne({ _id: id }, (err, result) => - fn(result ? result : undefined)); + public getDocument(id: string, fn: (result?: Transferable) => void, collectionName = Database.DocumentsCollection) { + this.db && this.db.collection(collectionName).findOne({ id: id }, (err, result) => + fn(result ? ({ id: result._id, type: result.type, data: result.data }) : undefined)) } - public getDocuments(ids: string[], fn: (res: any) => void, collectionName = Database.DocumentsCollection) { - this.db && this.db.collection(collectionName).find({ _id: { "$in": ids } }).toArray((err, docs) => { + public getDocuments(ids: string[], fn: (result: Transferable[]) => void, collectionName = Database.DocumentsCollection) { + this.db && this.db.collection(collectionName).find({ id: { "$in": ids } }).toArray((err, docs) => { if (err) { console.log(err.message); console.log(err.errmsg); } - fn(docs); + fn(docs.map(doc => ({ id: doc._id, type: doc.type, data: doc.data }))); }); } diff --git a/src/server/index.ts b/src/server/index.ts index a6fe6fa2c..a86638186 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -246,17 +246,17 @@ function barReceived(guid: String) { clients[guid.toString()] = new Client(guid.toString()); } -function getField([id, callback]: [string, (result: any) => void]) { - Database.Instance.getDocument(id, (result: any) => +function getField([id, callback]: [string, (result?: Transferable) => void]) { + Database.Instance.getDocument(id, (result?: Transferable) => callback(result ? result : undefined)); } -function getFields([ids, callback]: [string[], (result: any) => void]) { +function getFields([ids, callback]: [string[], (result: Transferable[]) => void]) { Database.Instance.getDocuments(ids, callback); } function setField(socket: Socket, newValue: Transferable) { - Database.Instance.update(newValue._id, newValue, () => + Database.Instance.update(newValue.id, newValue, () => socket.broadcast.emit(MessageStore.SetField.Message, newValue)); } -- cgit v1.2.3-70-g09d2 From 5782ae7c2bcbdf0026387ba4ac1fcba273930c1c Mon Sep 17 00:00:00 2001 From: Tyler Schicke Date: Tue, 16 Apr 2019 00:08:23 -0400 Subject: Changed config stuff to make compilation faster Fixed linter errors --- package.json | 2 ++ src/client/views/MainOverlayTextBox.tsx | 2 +- .../views/collections/CollectionDockingView.tsx | 2 +- .../collectionFreeForm/CollectionFreeFormView.tsx | 2 +- src/client/views/nodes/ImageBox.tsx | 2 +- src/server/authentication/models/user_model.ts | 3 +-- src/server/database.ts | 2 +- src/server/index.ts | 2 +- tslint.json | 3 ++- webpack.config.js | 19 +++++++++---------- 10 files changed, 20 insertions(+), 19 deletions(-) (limited to 'src/server/database.ts') diff --git a/package.json b/package.json index 8c9c865e0..608204231 100644 --- a/package.json +++ b/package.json @@ -20,10 +20,12 @@ "copy-webpack-plugin": "^4.6.0", "css-loader": "^2.1.1", "file-loader": "^3.0.1", + "fork-ts-checker-webpack-plugin": "^1.0.2", "mocha": "^5.2.0", "sass-loader": "^7.1.0", "scss-loader": "0.0.1", "style-loader": "^0.23.1", + "ts-loader": "^5.3.3", "ts-node": "^7.0.1", "tslint": "^5.15.0", "tslint-loader": "^3.5.4", diff --git a/src/client/views/MainOverlayTextBox.tsx b/src/client/views/MainOverlayTextBox.tsx index 6d43d88f0..422a45d59 100644 --- a/src/client/views/MainOverlayTextBox.tsx +++ b/src/client/views/MainOverlayTextBox.tsx @@ -101,7 +101,7 @@ export class MainOverlayTextBox extends React.Component s[0] = Math.sqrt((s[0] - t[0]) * (s[0] - t[0]) + (s[1] - t[1]) * (s[1] - t[1])); return
- this._textXf} focus={emptyDocFunction} />
; diff --git a/src/client/views/collections/CollectionDockingView.tsx b/src/client/views/collections/CollectionDockingView.tsx index 2b96e7678..4ea21b2f5 100644 --- a/src/client/views/collections/CollectionDockingView.tsx +++ b/src/client/views/collections/CollectionDockingView.tsx @@ -263,7 +263,7 @@ export class CollectionDockingView extends React.Component${count}
`); tab.element.append(counter); counter.DashDocId = tab.contentItem.config.props.documentId; - (tab as any).reactionDisposer = reaction(() => [f.GetT(KeyStore.LinkedFromDocs, ListField), f.GetT(KeyStore.LinkedToDocs, ListField)], + tab.reactionDisposer = reaction(() => [f.GetT(KeyStore.LinkedFromDocs, ListField), f.GetT(KeyStore.LinkedToDocs, ListField)], (lists) => { let count = (lists.length > 0 && lists[0] && lists[0]!.Data ? lists[0]!.Data.length : 0) + (lists.length > 1 && lists[1] && lists[1]!.Data ? lists[1]!.Data.length : 0); diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx index 03426cb27..c193f38df 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx @@ -290,7 +290,7 @@ export class CollectionFreeFormView extends CollectionSubView { @computed get views() { - let pw = this.props.CollectionView.props + let pw = this.props.CollectionView.props; var curPage = this.props.Document.GetNumber(KeyStore.CurPage, -1); let docviews = this.props.Document.GetList(this.props.fieldKey, [] as Document[]).filter(doc => doc).reduce((prev, doc) => { var page = doc.GetNumber(KeyStore.Page, -1); diff --git a/src/client/views/nodes/ImageBox.tsx b/src/client/views/nodes/ImageBox.tsx index 9bdbfbb5d..edd7f55fc 100644 --- a/src/client/views/nodes/ImageBox.tsx +++ b/src/client/views/nodes/ImageBox.tsx @@ -81,7 +81,7 @@ export class ImageBox extends React.Component { } e.stopPropagation(); } - })) + })); // de.data.removeDocument() bcz: need to implement } } diff --git a/src/server/authentication/models/user_model.ts b/src/server/authentication/models/user_model.ts index d5c84c311..ee85e1c05 100644 --- a/src/server/authentication/models/user_model.ts +++ b/src/server/authentication/models/user_model.ts @@ -85,8 +85,7 @@ userSchema.pre("save", function save(next) { }); const comparePassword: comparePasswordFunction = function (this: DashUserModel, candidatePassword, cb) { - bcrypt.compare(candidatePassword, this.password, (err: mongoose.Error, isMatch: boolean) => - cb(err, isMatch)); + bcrypt.compare(candidatePassword, this.password, cb); }; userSchema.methods.comparePassword = comparePassword; diff --git a/src/server/database.ts b/src/server/database.ts index 7914febf8..5457e4dd5 100644 --- a/src/server/database.ts +++ b/src/server/database.ts @@ -59,7 +59,7 @@ export class Database { public getDocument(id: string, fn: (result?: Transferable) => void, collectionName = Database.DocumentsCollection) { this.db && this.db.collection(collectionName).findOne({ id: id }, (err, result) => - fn(result ? ({ id: result._id, type: result.type, data: result.data }) : undefined)) + fn(result ? ({ id: result._id, type: result.type, data: result.data }) : undefined)); } public getDocuments(ids: string[], fn: (result: Transferable[]) => void, collectionName = Database.DocumentsCollection) { diff --git a/src/server/index.ts b/src/server/index.ts index 3cbe1ca76..70a7d266c 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -35,7 +35,7 @@ import c = require("crypto"); const MongoStore = require('connect-mongo')(session); const mongoose = require('mongoose'); -const download = (url: string, dest: fs.PathLike) => request.get(url).pipe(fs.createWriteStream(dest));; +const download = (url: string, dest: fs.PathLike) => request.get(url).pipe(fs.createWriteStream(dest)); const mongoUrl = 'mongodb://localhost:27017/Dash'; mongoose.connect(mongoUrl); diff --git a/tslint.json b/tslint.json index aa4dee4e5..76d28b375 100644 --- a/tslint.json +++ b/tslint.json @@ -52,5 +52,6 @@ // } // ], // "ordered-imports": true - } + }, + "defaultSeverity": "warning" } \ No newline at end of file diff --git a/webpack.config.js b/webpack.config.js index 574401807..c08742272 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -1,6 +1,7 @@ var path = require('path'); var webpack = require('webpack'); const CopyWebpackPlugin = require("copy-webpack-plugin"); +const ForkTsCheckerWebpackPlugin = require("fork-ts-checker-webpack-plugin"); module.exports = { mode: 'development', @@ -11,6 +12,9 @@ module.exports = { inkControls: ["./src/mobile/InkControls.tsx", 'webpack-hot-middleware/client?reload=true'], imageUpload: ["./src/mobile/ImageUpload.tsx", 'webpack-hot-middleware/client?reload=true'], }, + optimization: { + noEmitOnErrors: true + }, devtool: "source-map", node: { fs: 'empty', @@ -30,17 +34,10 @@ module.exports = { module: { rules: [ { - test: [/\.tsx?$/, /\.ts?$/,], - enforce: 'pre', + test: [/\.tsx?$/], use: [ - { - loader: "tslint-loader", - } + { loader: 'ts-loader', options: { transpileOnly: true } } ] - }, { - test: [/\.tsx?$/, /\.ts?$/,], - loader: "awesome-typescript-loader", - include: path.join(__dirname, 'src') }, { test: /\.scss|css$/, @@ -78,9 +75,11 @@ module.exports = { }, plugins: [ new CopyWebpackPlugin([{ from: "deploy", to: path.join(__dirname, "build") }]), + new ForkTsCheckerWebpackPlugin({ + tslint: true, useTypescriptIncrementalApi: true + }), new webpack.optimize.OccurrenceOrderPlugin(), new webpack.HotModuleReplacementPlugin(), - new webpack.NoEmitOnErrorsPlugin() ], devServer: { compress: false, -- cgit v1.2.3-70-g09d2