@projectinvicta/nails 2.0.15 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/README.md +70 -84
  2. package/bin/test/test_init.sh +33 -0
  3. package/index.ts +11 -0
  4. package/lib/Controller.ts +207 -0
  5. package/lib/Nails.ts +210 -0
  6. package/lib/Router.ts +180 -0
  7. package/lib/{application.js → application.ts} +8 -3
  8. package/lib/config.ts +74 -0
  9. package/package.json +14 -11
  10. package/spec/controller.spec.js +5 -51
  11. package/spec/nails.spec.js +1 -0
  12. package/spec/router.spec.js +5 -5
  13. package/spec/services/integration/config/db.ts +7 -0
  14. package/spec/services/integration/config/service.js +8 -8
  15. package/spec/services/integration/server/controllers/classbased_controller.js +2 -2
  16. package/spec/services/integration/server/controllers/default_json_controller.js +19 -7
  17. package/spec/services/integration/server/controllers/error_controller.js +2 -2
  18. package/spec/services/integration/server/controllers/home_controller.js +6 -28
  19. package/spec/services/integration/server/controllers/json_controller.js +2 -2
  20. package/spec/services/integration/server/controllers/manualrenderasync_controller.js +2 -2
  21. package/spec/services/integration/server/controllers/mjs_controller.mjs +2 -6
  22. package/spec/services/integration/server/controllers/modeltest_controller.js +6 -9
  23. package/spec/services/integration/server/controllers/websocket_controller.js +1 -1
  24. package/spec/services/integration/server/models/dog.js +7 -5
  25. package/spec/services/integration/server/models/owner.js +13 -0
  26. package/spec/services/integration/server.js +3 -4
  27. package/spec/services.integration.spec.js +45 -17
  28. package/templates/default/config/db.ts +13 -0
  29. package/{spec/services/integration_sequelize/config/mimes.js → templates/default/config/mimes.ts} +42 -61
  30. package/templates/default/config/routes.ts +22 -0
  31. package/templates/{config/service.js → default/config/service.ts} +2 -2
  32. package/templates/default/package.json +8 -2
  33. package/templates/default/public/README.xml +68 -85
  34. package/templates/default/server/controllers/home_controller.js +2 -2
  35. package/templates/{server/controllers/home_controller.js → default/server/controllers/users_controller.ts} +29 -34
  36. package/templates/default/server/models/Dog.ts +8 -0
  37. package/templates/default/server/models/User.ts +14 -0
  38. package/templates/default/spec/User.test.js +7 -5
  39. package/templates/default/spec/home_controller.test.js +3 -3
  40. package/index.js +0 -6
  41. package/lib/collection.js +0 -6
  42. package/lib/controller.js +0 -182
  43. package/lib/database_connector.js +0 -12
  44. package/lib/firebase_connector.js +0 -94
  45. package/lib/model_v2.js +0 -24
  46. package/lib/mongoose_connector.js +0 -49
  47. package/lib/mongoose_mem_connector.js +0 -21
  48. package/lib/nails.js +0 -244
  49. package/lib/router.js +0 -202
  50. package/lib/sequelize_connector.js +0 -31
  51. package/lib/server.js +0 -1
  52. package/spec/model_v2.spec.js +0 -75
  53. package/spec/mongodb_connector.util.js +0 -30
  54. package/spec/mongoose_connector.util.js +0 -20
  55. package/spec/sequelize_connector.spec.js +0 -91
  56. package/spec/sequelize_connector.util.js +0 -18
  57. package/spec/services/integration/config/db.js +0 -14
  58. package/spec/services/integration_sequelize/README.md +0 -5
  59. package/spec/services/integration_sequelize/client/css/styles.css +0 -0
  60. package/spec/services/integration_sequelize/client/download.jpg +0 -0
  61. package/spec/services/integration_sequelize/client/favicon.ico +0 -0
  62. package/spec/services/integration_sequelize/client/index.html +0 -9
  63. package/spec/services/integration_sequelize/client/js/client.js +0 -0
  64. package/spec/services/integration_sequelize/client/js/components/app.jsx +0 -15
  65. package/spec/services/integration_sequelize/config/db.js +0 -4
  66. package/spec/services/integration_sequelize/config/routes.js +0 -25
  67. package/spec/services/integration_sequelize/config/service.js +0 -48
  68. package/spec/services/integration_sequelize/config/ssl/certificate.pem +0 -22
  69. package/spec/services/integration_sequelize/config/ssl/csr.csr +0 -17
  70. package/spec/services/integration_sequelize/config/ssl/key.pem +0 -28
  71. package/spec/services/integration_sequelize/config/ssl/private_key.pem +0 -30
  72. package/spec/services/integration_sequelize/config/ssl/public_key.pem +0 -9
  73. package/spec/services/integration_sequelize/package.json +0 -23
  74. package/spec/services/integration_sequelize/server/controllers/default_json_controller.js +0 -21
  75. package/spec/services/integration_sequelize/server/controllers/home_controller.js +0 -39
  76. package/spec/services/integration_sequelize/server/models/dog.js +0 -7
  77. package/spec/services/integration_sequelize/server/models/owner.js +0 -10
  78. package/spec/services/integration_sequelize/server/views/defaultjson/testnojson.ejs +0 -1
  79. package/spec/services/integration_sequelize/server/views/testreact/testreact.ejs +0 -15
  80. package/spec/services/integration_sequelize/server.js +0 -9
  81. package/spec/services.integration_sequelize.spec.js +0 -60
  82. package/templates/bin/promote.sh +0 -20
  83. package/templates/bin/rollout.sh +0 -74
  84. package/templates/bin/server.js +0 -6
  85. package/templates/bin/start.sh +0 -16
  86. package/templates/common/readme_fetcher.js +0 -4
  87. package/templates/config/db.js +0 -19
  88. package/templates/config/mimes.js +0 -59
  89. package/templates/config/routes.js +0 -38
  90. package/templates/config/ssl/certificate.pem +0 -22
  91. package/templates/config/ssl/csr.csr +0 -17
  92. package/templates/config/ssl/key.pem +0 -28
  93. package/templates/config/ssl/private_key.pem +0 -30
  94. package/templates/config/ssl/public_key.pem +0 -9
  95. package/templates/default/config/db.js +0 -19
  96. package/templates/default/config/mimes.js +0 -59
  97. package/templates/default/config/routes.js +0 -38
  98. package/templates/default/config/service.js +0 -45
  99. package/templates/default/server/models/User.js +0 -18
  100. package/templates/package-lock.json +0 -9048
  101. package/templates/package.json +0 -43
  102. package/templates/public/README.xml +0 -332
  103. package/templates/public/css/styles.css +0 -17
  104. package/templates/public/download.jpg +0 -0
  105. package/templates/public/favicon.ico +0 -0
  106. package/templates/public/index.html +0 -9
  107. package/templates/public/js/client.js +0 -1
  108. package/templates/server/models/User.js +0 -18
  109. package/templates/server/views/home/index.ejs +0 -14
  110. package/templates/server/views/partials/javascripts.ejs +0 -1
  111. package/templates/server/views/partials/reactapp.ejs +0 -1
  112. package/templates/server/views/partials/styles.ejs +0 -3
  113. package/templates/spec/User.test.js +0 -20
  114. package/templates/spec/home_controller.test.js +0 -28
  115. package/templates/spec/setupTests.js +0 -0
  116. package/templates/src/AboutPage.jsx +0 -9
  117. package/templates/src/HomePage.jsx +0 -9
  118. package/templates/src/Layout.jsx +0 -78
  119. package/templates/src/ReadmePage.jsx +0 -7
  120. package/templates/src/app.jsx +0 -29
  121. package/templates/src/components/ReadmeLoader.jsx +0 -13
  122. package/templates/src/styles/appstyles.css +0 -3
  123. package/templates/vite.config.ts +0 -42
@@ -1,94 +0,0 @@
1
- // TODO: multiple async requests here... need to
2
- // consider how this will be used by the models
3
- import {EventEmitter} from 'node:events';
4
- // var EventEmitter = require('events').EventEmitter;
5
- import { MongoClient } from 'mongodb';
6
- // const MongoClient = require('mongodb').MongoClient;
7
- // const test = require('assert');
8
- import test from 'assert';
9
-
10
- module.exports = MongoDBConnector;
11
-
12
- // TODO: need to deal with clustered databases...
13
-
14
- MongoDBConnector.prototype.__proto__ = EventEmitter.prototype;
15
- function MongoDBConnector(config) {
16
- EventEmitter.call(this);
17
- var url = config.url || 'mongodb://localhost';
18
- var port = config.port || '27017';
19
- var database = config.database || 'nails';
20
- this.exec_once_connected = [];
21
- MongoClient.connect(url + ':' + port)
22
- .then((err, client) => {
23
- this._client = client;
24
- this._db = client.db(database);
25
- }).catch({
26
- // TODO: handle a failed mongodb connection
27
- });
28
- }
29
-
30
- /**
31
- * Need to implement these methods for a connector to work
32
- */
33
- // maybe use rest methods as names for any database connector used...
34
- MongoDBConnector.prototype.post = function(model_or_collection) {
35
- if (model_or_collection.is_model)
36
- this._post_one(model_or_collection._collection_name(),
37
- model_or_collection.attributes);
38
- }
39
- MongoDBConnector.prototype._post_one = function(collection_name, doc_attributes, callback) {
40
- this._db.collection(collection_name).insert(doc_attributes);
41
- }
42
- MongoDBConnector.prototype._post_many = function(collection) {
43
- this._db.collection(collection.name())
44
- .save(collection.model_attributes());
45
- }
46
-
47
- // update a record in the collection
48
- MongoDBConnector.prototype.put = function(model_or_collection) {
49
- if (model_or_collection.is_model)
50
- this._put_one(model_or_collection._collection_name(), model_or_collection.attributes);
51
- }
52
- MongoDBConnector.prototype._put_one = function(collection_name, doc) {
53
- // TODO: replacing document completely is sow
54
- // will want to only send changed attr
55
- // TODO: write concerns?
56
- this._db.collection(collection_name).update({_id: doc._id}, doc);
57
- }
58
- /**
59
- * _put_many will call _update on each individual object in collection
60
- * if that object has changed
61
- */
62
- MongoDBConnector.prototype._put_many = function(collection) {
63
- }
64
-
65
- // return a single record from a collection
66
- // or a collection of records if requested...
67
- // if a model or collection is passed,
68
- MongoDBConnector.prototype.get = function(model_or_collection) {
69
- if (model_or_collection.is_model)
70
- this._get_one(model_or_collection._collection_name(), model_or_collection.id, null,
71
- this._on_doc_response.bind(model_or_collection));
72
- }
73
- MongoDBConnector.prototype._get_one = function(collection_name, id, options, callback) {
74
- options = options || {};
75
- this._db.collection(collection_name).findOne(id, options, callback);
76
- }
77
- MongoDBConnector.prototype._get_many = function(collection) {
78
- return this._db.collection(collection.name()).find({
79
- _id: collection.collect('_id')});
80
- }
81
-
82
- // delete a record from a collection
83
- MongoDBConnector.prototype.delete = function(model) {
84
- return this._db.collection(model.collection_name())
85
- .remove(model.attributes._id);
86
- }
87
- // MongoDBConnector.prototype._delete_one
88
- // MongoDBConnector.prototype._delete_many
89
-
90
- MongoDBConnector.prototype._on_doc_response = function(err, doc) {
91
- if (err) return console.log('error retrieving from', collection_name, '\n', err);
92
- delete doc._id;
93
- this._merge_attributes(doc);
94
- }
package/lib/model_v2.js DELETED
@@ -1,24 +0,0 @@
1
- let dbConnector = null;
2
-
3
- const FINALIZATIONS = [];
4
-
5
- export default class Model {
6
- static finalize(extraWork) {
7
- FINALIZATIONS.push(extraWork);
8
- }
9
-
10
- static async _doFinalize() {
11
- await Promise.all(FINALIZATIONS.map(extraWork => extraWork()));
12
- }
13
-
14
- static setConnector(connector) {
15
- // TODO: enforce environment using variables
16
- if (dbConnector)
17
- console.warn("WARNING: Model#setConnector should not be called multiple times outside of tests");
18
- dbConnector = connector;
19
- }
20
-
21
- constructor(modelName, connectorOptions) {
22
- return dbConnector.generateModelSuperclass(modelName, connectorOptions);
23
- }
24
- }
@@ -1,49 +0,0 @@
1
- // const mongoose = require('mongoose');
2
- import mongoose from 'mongoose';
3
- import DbConnector from './database_connector.js';
4
-
5
- class MongooseDbConnector extends DbConnector{
6
- async connect(options) {
7
- if (options.uri) {
8
- this.connection = await mongoose.createConnection(options.uri/*, mongooseOptions*/).asPromise();
9
- } else {
10
- var url = options.url || 'mongodb://127.0.0.1';
11
- var port = options.port || '27017';
12
- var database = options.database || options.dbName || 'nails';
13
- this.connection = await mongoose.createConnection(`${url}:${port}/${database}`).asPromise();
14
- }
15
- }
16
-
17
- generateModelSuperclass(name, options) {
18
- if (!this.connection) console.error("NO CONNECTION\n", this);
19
- let schema = options.schema instanceof mongoose.Schema
20
- ? options.schema
21
- : new mongoose.Schema(options.schema);
22
- if (options.indexes) {
23
- options.indexes.forEach(index => schema.index(index));
24
- }
25
- return this.connection.model(name, options.schema);
26
- }
27
- }
28
- export default MongooseDbConnector;
29
- /*
30
- module.exports.connect = function(options) {
31
- if (options.uri) return mongoose.createConnection(options.uri, mongooseOptions);
32
- else {
33
- var url = options.url || 'mongodb://localhost';
34
- var port = options.port || '27017';
35
- var database = options.database || 'nails';
36
- return mongoose.createConnection(`${url}:${port}/${database}`, mongooseOptions);
37
- }
38
- }
39
-
40
- module.exports.generateModelSuperclass = function(name, options) {
41
- let schema = options.schema instanceof mongoose.Schema
42
- ? options.schema
43
- : new mongoose.Schema(options.schema);
44
- if (options.indexes) {
45
- options.indexes.forEach(index => schema.index(index));
46
- }
47
- return mongoose.model(name, options.schema);
48
- }
49
- */
@@ -1,21 +0,0 @@
1
- // const mongoose = require('mongoose');
2
- // const {MongoMemoryServer} = require('mongodb-memory-server');
3
- import { MongoMemoryServer } from 'mongodb-memory-server';
4
- import MongooseDbConnector from './mongoose_connector.js';
5
- // const MongooseDbConnector = require('./mongoose_connector');
6
-
7
- export default class MongooseMemoryConnector extends MongooseDbConnector {
8
-
9
- async connect() {
10
- try {
11
- const mongod = await MongoMemoryServer.create();
12
- const uri = mongod.getUri();
13
- console.error("The URI", uri);
14
- const dbConfig = {uri: uri};
15
- return super.connect(dbConfig);
16
- } catch (e) {
17
- console.error("Could not connect to MongoMemoryServer");
18
- console.error(e);
19
- }
20
- }
21
- }
package/lib/nails.js DELETED
@@ -1,244 +0,0 @@
1
- // The file which configures the nails application
2
- // import http from 'node:http';
3
- import https from 'node:https';
4
- // import URL from 'node:url';
5
- import path from 'node:path';
6
- import fs from 'node:fs';
7
- import { EventEmitter } from 'node:events';
8
-
9
- import Controller from './controller.js';
10
- import ModelV2 from './model_v2.js';
11
- import Router from './router.js';
12
-
13
- import express_app from './application.js';
14
- import { Model } from 'mongoose';
15
-
16
- // TODO: add key value pairs to express app singleton.
17
- var application = {};
18
- application.config = {};
19
-
20
- // TODO: this should return a function (the configure function).
21
- // Calling the function should return { startServer: startServer }.
22
- // export defulat nails;
23
-
24
- export default async function nails(app_config) {
25
- nails.config = app_config.config;
26
- application._onceConfigured = configure(app_config);
27
- await application._onceConfigured;
28
- return {startServer: startServer};
29
- }
30
-
31
- nails.application = express_app;
32
- nails.Controller = Controller;
33
- nails.Model = ModelV2;
34
- nails.events = new EventEmitter();
35
- nails._dbConnector = null;
36
- nails.MODELS = {init: initializeModels};
37
-
38
- async function configure( app_config ) {
39
- express_app.set('nails_config', application);
40
- application.config = app_config.config;
41
- // TODO: may not need mimes any more.
42
- application.mimes = app_config.mimes;
43
-
44
- // Init view engine. Defaults to ejs.
45
- express_app.set('view engine', 'ejs');
46
- if (app_config.config.VIEW_ENGINE) {
47
- if (typeof app_config.config.VIEW_ENGINE == "string") {
48
- console.log("using consolidate for some reason");
49
- }
50
- express_app.engine(
51
- app_config.config.VIEW_ENGINE_EXT,
52
- app_config.config.VIEW_ENGINE);
53
- express_app.set('view engine', app_config.config.VIEW_ENGINE_EXT);
54
- }
55
- express_app.set('views', app_config.config.VIEWS_ROOT);
56
-
57
- // set up router and controllers
58
- express_app.set("public_root", app_config.config.PUBLIC_ROOT);
59
- console.log("Initializing Router...");
60
- // application.router = new Router( app_config.routes || [] );
61
- application.router = new Router( [] );
62
- console.log("Application Router initialized");
63
-
64
- // init models
65
- await initializeModels(app_config);
66
-
67
- // init Controllers
68
- Controller.setRouter(application.router);
69
- application.controller = Controller.extend(ApplicationController);
70
- console.log('initializing controllers: ', app_config.config.CONTROLLERS_ROOT);
71
- await init_controllers(app_config.config.CONTROLLERS_ROOT);
72
- application.router.addRoutes(app_config.routes);
73
- };
74
-
75
- export async function initializeModels( app_config ) {
76
- // init models
77
- console.log("Initializing DB connection...");
78
- var DBConnector = await get_dbconnector(app_config.db.connector);
79
-
80
- console.log("Instantiating DBConnector and Connecting to DB...");
81
- // Try to instantiate DBConnector
82
- const dbConnector = new DBConnector();
83
- nails._dbConnector = dbConnector;
84
- await dbConnector.connect(app_config.db);
85
- console.log("Generating model superclass...");
86
- ModelV2.setConnector(dbConnector);
87
- await init_models_v2(app_config.config.MODELS_ROOT);
88
- console.log("Done importing models");
89
- await dbConnector.afterInitialization();
90
- await ModelV2._doFinalize();
91
- console.log("DB Connection complete");
92
- }
93
-
94
- function startServer(config) {
95
- // Log the config.
96
- console.log(config);
97
- // await application._onceConfigured;
98
- console.log("CONFIGURATION COMPLETE");
99
- // TODO: Use logging middleware.
100
- application._onceConfigured.then(() => {
101
- // Use the router middleware.
102
- express_app.use(application.router.express_router);
103
- var ip = application.config.IP || 'localhost';
104
- var port = application.config.PORT || 3000;
105
-
106
- let startHttp = 'ENABLE_HTTP' in application.config && !!application.config.ENABLE_HTTP;
107
- let startHttps = !!application.config.ENABLE_HTTPS;
108
-
109
- if (!startHttp && !startHttps) {
110
- console.error("Either ENABLE_HTTPS or ENABLE_HTTP must be set for nails to start");
111
- }
112
-
113
- let atLeastOneServerStarted = false;
114
- let serverStartedCallback = () => {
115
- console.log("Started");
116
- if (atLeastOneServerStarted) return;
117
- nails.events.emit("ready", null);
118
- atLeastOneServerStarted = true;
119
- }
120
-
121
- if (startHttp) {
122
- console.log("starting nails HTTP server. listening to ", ip + ':' + port);
123
- express_app.listen(port, ip, serverStartedCallback);
124
-
125
- }
126
- if (startHttps) {
127
- console.log(`starting nails HTTPS server. Listening to ${ip}:${application.config.SSL_PORT}`);
128
- https.createServer({
129
- key: application.config.PRIVATE_KEY,
130
- cert: application.config.CERTIFICATE
131
- }, express_app).listen(application.config.SSL_PORT, serverStartedCallback);
132
- }
133
- });
134
- }
135
-
136
- // TODO: create an initializer lib file.
137
- async function init_controllers(controller_lib) {
138
- await init_app_lib(Controller, controller_lib);
139
- }
140
-
141
- async function init_app_lib(superclass, abs_path) {
142
- console.log('attempting to import:', abs_path);
143
- if (!fs.existsSync(abs_path))
144
- return console.log('Cannot initialize. Path not found.', abs_path);
145
- if (fs.statSync(abs_path).isFile()) {
146
- let subclass = (await import(abs_path)).default;
147
- // Constructor function was provided
148
- if (!superclass.isPrototypeOf(subclass))
149
- return superclass.extend(subclass);
150
- // ES6 Class was provided
151
- const subInstance = new subclass();
152
- if (superclass == Controller) {
153
- subInstance._registerControllerRoutes();
154
- }
155
- return subInstance;
156
- }
157
- for (const rel_path of fs.readdirSync(abs_path)) {
158
- await init_app_lib(superclass, path.join(abs_path, rel_path));
159
- }
160
- }
161
-
162
- async function init_models_v2(abs_path) {
163
- if (!fs.existsSync(abs_path))
164
- return console.log('Cannot initialize. Path not found.', abs_path);
165
- if (fs.statSync(abs_path).isFile()) {
166
- console.log('attempting to import:', abs_path);
167
- // We just need to import each model once so the generateSuperclass
168
- // method is called at least once for each model.
169
- const modelModule = await import(abs_path);
170
- let modelClass = modelModule.default;
171
- if (modelClass && modelClass.name) {
172
- console.log('imported model:', modelClass.name);
173
- nails.MODELS[modelClass.name] = modelClass;
174
- if (modelModule.defer) {
175
- await modelModule.defer();
176
- }
177
- }
178
- else console.warn("No model found at:", abs_path);
179
- return;
180
- }
181
- const directory_contents = fs.readdirSync(abs_path);
182
- for (const rel_path of directory_contents) {
183
- await init_models_v2(path.join(abs_path, rel_path));
184
- };
185
- }
186
-
187
- // retrieves the connector object. If cannot
188
- // require the module with the same name,
189
- // try grabbing connector from lib
190
- // (default connectors)
191
- async function get_dbconnector(connector_name) {
192
- console.log("Getting DBConnector:", connector_name);
193
- var DBConnector;
194
- //TODO: put mongodbconnector in its own module
195
- try {
196
- DBConnector = (await import(connector_name)).default;
197
- } catch(e) {
198
- DBConnector = (await import('./'+connector_name)).default;
199
- }
200
- console.log("Got DBConnector:", DBConnector.name);
201
- return DBConnector;
202
- }
203
-
204
- // Define default views and controllers
205
- // TODO: clean this up... all this logic shouldnt be here
206
- function ApplicationController(){};
207
-
208
- /**
209
- * Application Views
210
- */
211
- function JSONView(){};
212
- // TODO: add error template for error view
213
- function ErrorView() {}
214
- ErrorView.prototype.render = function(params, response) {
215
- response.statusCode = params.code || 500;
216
- // TODO: change this to use the error jade template
217
- response.setHeader('content-type', 'text/plain');
218
- var content = params.error ?
219
- params.error.message + '\n' + params.error.stack :
220
- params.message;
221
- response.end(content);
222
- }
223
- // TODO: consider changing public to static...
224
- function PublicView(){};
225
- PublicView.prototype.get_full_path = function(filepath) {
226
- var pubroot = application.config.PUBLIC_ROOT;
227
- var partial_path = filepath;
228
- if (filepath.substr(0, pubroot.length) != pubroot)
229
- partial_path = path.join(pubroot, filepath);
230
- return path.join(application.config.SERVER_ROOT, partial_path);
231
- };
232
- PublicView.prototype.render = function(params, response) {
233
- var file_path = this.get_full_path(params.path);
234
-
235
- var content = '';
236
- try {
237
- content = fs.readFileSync(file_path);
238
- } catch(e) {
239
- console.log(e.message, "\n", e.stack);
240
- response.statusCode = 404;
241
- } finally {
242
- response.end(content);
243
- }
244
- };
package/lib/router.js DELETED
@@ -1,202 +0,0 @@
1
- // The Router object which handles incoming urls and executes the correct
2
- // server-side logic based on the matching route in the Routing Table
3
- // ( See example/config/routes.js or config/routes.js for a description of the routes )
4
-
5
- import {EventEmitter} from 'node:events';
6
- // var EventEmitter = require('events').EventEmitter;
7
- import URL from 'node:url';
8
- // var URL = require('url');
9
-
10
- import path from 'node:path';
11
- import querystring from 'node:querystring';
12
- import express from 'express';
13
- import expressWs from 'express-ws';
14
- import app from './application.js'
15
- // TODO use modular js only
16
- import {_extend} from 'util';
17
-
18
- // var path = require('path');
19
- // var querystring = require('querystring');
20
- // var expressWs = require('express-ws');
21
- // var app = require('./application.js');
22
- // //var nails = require('./nails.js');
23
- // var _extend = require('util')._extend;
24
-
25
- /**
26
- * Creates a Router from an Array of route definitions
27
- * may want to change this to singleton... just to continue paradigm
28
- * emits: "contoller_name:action" on successful route
29
- * controllers and the viewer listen to this object for instructions on doing shit
30
- *
31
- * @param routes the array of route definitions from the application config.
32
- * @param application the nails application singleton.
33
- */
34
- class Router extends EventEmitter {
35
- static get webSocketsEnabled() {
36
- return this._webSocketsEnabled;
37
- }
38
- static set webSocketsEnabled(enabled) {
39
- this._webSocketsEnabled = enabled;
40
- }
41
-
42
- static set expressWs(ews) {
43
- this._expressWs = ews;
44
- }
45
- static get expressWs() {
46
- return this._expressWs;
47
- }
48
-
49
- enableWebSockets() {
50
- if (Router.webSocketsEnabled) return;
51
- Router.webSocketsEnabled = true;
52
- Router.expressWs = expressWs(this.application);
53
- expressWs(this.express_router);
54
- // console.log("WS is still:", this.express_router.ws);
55
- }
56
- constructor(routes) {
57
- super();
58
- this.application = app;
59
- // this.express_router = express.Router();
60
- // console.log("the router is:", this.express_router);
61
- // console.log("the ws is:", this.express_router.ws);
62
- this.express_router = app.Router();
63
- this.addRoutes(routes);
64
- }
65
-
66
- addRoutes(routes) {
67
- this.routes = routes;
68
- routes.forEach(this.addRoute.bind(this));
69
- }
70
-
71
- addRoute(route) {
72
- var method = route[0].toLowerCase();
73
- var path_matcher = route[1];
74
- var consequences = route[2];
75
- console.log("setting route for", method, path_matcher, consequences);
76
- if (method.match(/ws/i)) { // For some reason this hangs
77
- this.enableWebSockets();
78
- this.express_router.ws(
79
- path_matcher,
80
- this.get_websocket_handler(consequences));
81
- } else if (consequences && consequences.public) // Is a request for public asset
82
- this.express_router.use(path_matcher,
83
- this.application.static(this.application.get('public_root')));
84
- else this.express_router[method](path_matcher,
85
- this.get_express_route_handler(consequences));
86
- }
87
-
88
- // TODO: override these for shortcutting crud methods
89
- // Router.prototype.get;
90
- // Router.prototype.put;
91
- // Router.prototype.post;
92
- // Router.prototype.delete;
93
- // end crud methods
94
-
95
- // TODO: Combine this with the regular route method
96
- routeWs(ws, request) {
97
- console.log(
98
- '\nSERVER_LOG:: WebSocket Router received request for: ',
99
- request.method,
100
- request.url,
101
- '\n'
102
- );
103
- var params = _extend({}, request.params);
104
- _extend(params, request.querty);
105
-
106
- var controller = params._controller;
107
- var action = params._action;
108
- console.log('the action is:', controller, action, params);
109
- console.log('the params are:', params);
110
- console.log('ws router emitting:', 'dispatchTo:' + controller);
111
- this.emit('dispatchTo:' + controller, action, params, request, null, ws);
112
-
113
- if (!request.handled_by_controller) {
114
- params.error = {message: 'controller ' + controller + ' does not exist'};
115
- console.log('closing websocket');
116
- return ws.close(1003, "Action Not available: #" + action);
117
- //this.emit('dispatchTo:application', 404, params, request, null, ws);
118
- }
119
- }
120
-
121
- route(request, response) {
122
- // TODO: use express logging.
123
- console.log(
124
- '\nSERVER_LOG:: Router recieved request for: ',
125
- request.method, request.url, '\n');
126
-
127
- var params = _extend({}, request.params);
128
- _extend(params, request.query);
129
-
130
- var controller = params._controller;
131
- //var action = routeParams.action || routeParams.file || routeParams.path;
132
- //var params = routeParams.params || {};
133
- var action = params._action;
134
- console.log('the action is:', controller, action, params);
135
- console.log('the params are:', params);
136
-
137
- console.log('router emitting:', 'dispatchTo:' + controller);
138
- this.emit('dispatchTo:' + controller, action, params, request, response);
139
- // TODO: raise 404 error using express
140
- params.error = {message: 'controller ' + controller + ' does not exist'};
141
- if (!request.handled_by_controller)
142
- this.emit('dispatchTo:application', 404, params, request, response);
143
- }
144
-
145
- get_websocket_handler(route_options) {
146
- route_options = route_options || {};
147
- return (ws, request) => {
148
- console.log("handling a websocket request");
149
- var controller = route_options['controller'];
150
- var action = route_options['action'];
151
- for (var i = 0; route_options[i]; i++) {
152
- if (route_options[i] == 'action') action = action || request.params[i];
153
- else if (route_options[i] == 'controller')
154
- controller = controller || request.params[i];
155
- else request.params[route_options[i]] = request.params[i];
156
- }
157
- request.params._action = action || request.params.action || "index";
158
- request.params._controller =
159
- controller || request.params.controller || "application";
160
-
161
- this.routeWs(ws, request);
162
- };
163
- }
164
-
165
- get_express_route_handler(route_options) {
166
- route_options = route_options || {};
167
- return (request, response) => {
168
- // See if controller and action are set explicitly.
169
- var controller = route_options['controller'];
170
- var action = route_options['action'];
171
- // TODO: see if there is a way to use mimie types for this.
172
- var json = !!route_options['json'];
173
- var path = route_options['path']; // TODO: what to do with this under express.
174
- var async = route_options['async'];
175
- var autorender = route_options['disable_autorender'];
176
-
177
- // Check for controller and action from regex assignments.
178
- for (var i = 0; route_options[i]; i++) {
179
- if (route_options[i] == 'action') action = action || request.params[i];
180
- else if (route_options[i] == 'controller')
181
- controller = controller || request.params[i];
182
- else if (route_options[i] == 'json')
183
- json = json || request.params[i];
184
- else request.params[route_options[i]] = request.params[i];
185
- }
186
-
187
- // Check for controller and action in parameters.
188
- request.params._action = action || request.params.action || "index";
189
- request.params._controller =
190
- controller || request.params.controller || "application";
191
- request.params._json = json || !!request.params.json;
192
- request.params._async = async == null || async == undefined ?
193
- !!this.application.get('nails_config').config.ASYNC : async;
194
- // autorender should default to true if it is not defined
195
- request.params._autorender = autorender ? !!autorender : true;
196
-
197
- this.route(request, response);
198
- };
199
- }
200
- }
201
-
202
- export default Router;
@@ -1,31 +0,0 @@
1
- import DbConnector from './database_connector.js';
2
- import { Sequelize, Model } from 'sequelize';
3
-
4
- export default class SequelizeConnector extends DbConnector {
5
- sequelize;
6
-
7
- async connect(options) {
8
- this.sequelize = new Sequelize(options.address);
9
- try {
10
- await this.sequelize.authenticate();
11
- console.log('Connection has been established successfully.');
12
- } catch (error) {
13
- console.error('Unable to connect to the database:', error);
14
- }
15
- }
16
-
17
- /**
18
- * @returns {Model}
19
- */
20
- generateModelSuperclass(name, options) {
21
- if (options.schema) {
22
- return this.sequelize.define(name, options.schema, options.options);
23
- }
24
- return this.sequelize.define(name, options);
25
- }
26
-
27
- async afterInitialization() {
28
- console.log("SEQUELIZE::Writing changes to SQL Database");
29
- await this.sequelize.sync({alter: {drop: false}});
30
- }
31
- }
package/lib/server.js DELETED
@@ -1 +0,0 @@
1
- // TODO refractor the server to this module