@projectinvicta/nails 2.0.15 → 3.0.1

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 (153) hide show
  1. package/README.md +70 -84
  2. package/bin/lib/init.js +0 -4
  3. package/bin/test/test_init.sh +33 -0
  4. package/index.ts +11 -0
  5. package/lib/Controller.ts +207 -0
  6. package/lib/Nails.ts +210 -0
  7. package/lib/Router.ts +180 -0
  8. package/lib/{application.js → application.ts} +8 -3
  9. package/lib/config.ts +74 -0
  10. package/package.json +17 -15
  11. package/templates/default/config/db.ts +13 -0
  12. package/{spec/services/integration_sequelize/config/mimes.js → templates/default/config/mimes.ts} +42 -61
  13. package/templates/default/config/routes.ts +22 -0
  14. package/templates/default/config/{service.js → service.ts} +2 -2
  15. package/templates/default/package.json +8 -2
  16. package/templates/default/public/README.xml +68 -85
  17. package/templates/default/server/controllers/home_controller.js +2 -2
  18. package/templates/{server/controllers/home_controller.js → default/server/controllers/users_controller.ts} +29 -34
  19. package/templates/default/server/models/Dog.ts +8 -0
  20. package/templates/default/server/models/User.ts +14 -0
  21. package/templates/default/spec/User.test.js +7 -5
  22. package/templates/default/spec/home_controller.test.js +3 -3
  23. package/tests/bin/init.spec.js +3 -0
  24. package/tests/controller.spec.js +61 -0
  25. package/tests/nails.spec.js +4 -0
  26. package/tests/router.spec.js +105 -0
  27. package/tests/services/integration/config/db.ts +7 -0
  28. package/{spec/services/integration_sequelize → tests/services/integration}/config/service.js +8 -8
  29. package/{spec → tests}/services/integration/server/controllers/classbased_controller.js +2 -2
  30. package/tests/services/integration/server/controllers/default_json_controller.js +32 -0
  31. package/{spec → tests}/services/integration/server/controllers/error_controller.js +2 -2
  32. package/tests/services/integration/server/controllers/home_controller.js +17 -0
  33. package/{spec → tests}/services/integration/server/controllers/json_controller.js +2 -2
  34. package/{spec → tests}/services/integration/server/controllers/manualrenderasync_controller.js +2 -2
  35. package/tests/services/integration/server/controllers/mjs_controller.mjs +9 -0
  36. package/tests/services/integration/server/controllers/modeltest_controller.js +15 -0
  37. package/{spec → tests}/services/integration/server/controllers/websocket_controller.js +1 -1
  38. package/tests/services/integration/server/models/dog.js +8 -0
  39. package/tests/services/integration/server/models/owner.js +13 -0
  40. package/{spec/services/integration_sequelize → tests/services/integration}/server.js +3 -4
  41. package/tests/services.integration.spec.js +210 -0
  42. package/vite.config.ts +23 -0
  43. package/index.js +0 -6
  44. package/lib/collection.js +0 -6
  45. package/lib/controller.js +0 -182
  46. package/lib/database_connector.js +0 -12
  47. package/lib/firebase_connector.js +0 -94
  48. package/lib/model_v2.js +0 -24
  49. package/lib/mongoose_connector.js +0 -49
  50. package/lib/mongoose_mem_connector.js +0 -21
  51. package/lib/nails.js +0 -244
  52. package/lib/router.js +0 -202
  53. package/lib/sequelize_connector.js +0 -31
  54. package/lib/server.js +0 -1
  55. package/spec/bin/init.spec.js +0 -0
  56. package/spec/controller.spec.js +0 -105
  57. package/spec/model_v2.spec.js +0 -75
  58. package/spec/mongodb_connector.util.js +0 -30
  59. package/spec/mongoose_connector.util.js +0 -20
  60. package/spec/nails.spec.js +0 -0
  61. package/spec/router.spec.js +0 -101
  62. package/spec/sequelize_connector.spec.js +0 -91
  63. package/spec/sequelize_connector.util.js +0 -18
  64. package/spec/services/integration/config/db.js +0 -14
  65. package/spec/services/integration/config/service.js +0 -48
  66. package/spec/services/integration/server/controllers/default_json_controller.js +0 -20
  67. package/spec/services/integration/server/controllers/home_controller.js +0 -39
  68. package/spec/services/integration/server/controllers/mjs_controller.mjs +0 -13
  69. package/spec/services/integration/server/controllers/modeltest_controller.js +0 -18
  70. package/spec/services/integration/server/models/dog.js +0 -6
  71. package/spec/services/integration/server.js +0 -9
  72. package/spec/services/integration_sequelize/README.md +0 -5
  73. package/spec/services/integration_sequelize/client/css/styles.css +0 -0
  74. package/spec/services/integration_sequelize/client/download.jpg +0 -0
  75. package/spec/services/integration_sequelize/client/favicon.ico +0 -0
  76. package/spec/services/integration_sequelize/client/index.html +0 -9
  77. package/spec/services/integration_sequelize/client/js/client.js +0 -0
  78. package/spec/services/integration_sequelize/client/js/components/app.jsx +0 -15
  79. package/spec/services/integration_sequelize/config/db.js +0 -4
  80. package/spec/services/integration_sequelize/config/routes.js +0 -25
  81. package/spec/services/integration_sequelize/config/ssl/certificate.pem +0 -22
  82. package/spec/services/integration_sequelize/config/ssl/csr.csr +0 -17
  83. package/spec/services/integration_sequelize/config/ssl/key.pem +0 -28
  84. package/spec/services/integration_sequelize/config/ssl/private_key.pem +0 -30
  85. package/spec/services/integration_sequelize/config/ssl/public_key.pem +0 -9
  86. package/spec/services/integration_sequelize/package.json +0 -23
  87. package/spec/services/integration_sequelize/server/controllers/default_json_controller.js +0 -21
  88. package/spec/services/integration_sequelize/server/controllers/home_controller.js +0 -39
  89. package/spec/services/integration_sequelize/server/models/dog.js +0 -7
  90. package/spec/services/integration_sequelize/server/models/owner.js +0 -10
  91. package/spec/services/integration_sequelize/server/views/defaultjson/testnojson.ejs +0 -1
  92. package/spec/services/integration_sequelize/server/views/testreact/testreact.ejs +0 -15
  93. package/spec/services.integration.spec.js +0 -296
  94. package/spec/services.integration_sequelize.spec.js +0 -60
  95. package/templates/bin/promote.sh +0 -20
  96. package/templates/bin/rollout.sh +0 -74
  97. package/templates/bin/server.js +0 -6
  98. package/templates/bin/start.sh +0 -16
  99. package/templates/common/readme_fetcher.js +0 -4
  100. package/templates/config/db.js +0 -19
  101. package/templates/config/mimes.js +0 -59
  102. package/templates/config/routes.js +0 -38
  103. package/templates/config/service.js +0 -45
  104. package/templates/config/ssl/certificate.pem +0 -22
  105. package/templates/config/ssl/csr.csr +0 -17
  106. package/templates/config/ssl/key.pem +0 -28
  107. package/templates/config/ssl/private_key.pem +0 -30
  108. package/templates/config/ssl/public_key.pem +0 -9
  109. package/templates/default/config/db.js +0 -19
  110. package/templates/default/config/mimes.js +0 -59
  111. package/templates/default/config/routes.js +0 -38
  112. package/templates/default/server/models/User.js +0 -18
  113. package/templates/package-lock.json +0 -9048
  114. package/templates/package.json +0 -43
  115. package/templates/public/README.xml +0 -332
  116. package/templates/public/css/styles.css +0 -17
  117. package/templates/public/download.jpg +0 -0
  118. package/templates/public/favicon.ico +0 -0
  119. package/templates/public/index.html +0 -9
  120. package/templates/public/js/client.js +0 -1
  121. package/templates/server/models/User.js +0 -18
  122. package/templates/server/views/home/index.ejs +0 -14
  123. package/templates/server/views/partials/javascripts.ejs +0 -1
  124. package/templates/server/views/partials/reactapp.ejs +0 -1
  125. package/templates/server/views/partials/styles.ejs +0 -3
  126. package/templates/spec/User.test.js +0 -20
  127. package/templates/spec/home_controller.test.js +0 -28
  128. package/templates/spec/setupTests.js +0 -0
  129. package/templates/src/AboutPage.jsx +0 -9
  130. package/templates/src/HomePage.jsx +0 -9
  131. package/templates/src/Layout.jsx +0 -78
  132. package/templates/src/ReadmePage.jsx +0 -7
  133. package/templates/src/app.jsx +0 -29
  134. package/templates/src/components/ReadmeLoader.jsx +0 -13
  135. package/templates/src/styles/appstyles.css +0 -3
  136. package/templates/vite.config.ts +0 -42
  137. /package/{spec → tests}/services/integration/README.md +0 -0
  138. /package/{spec → tests}/services/integration/client/css/styles.css +0 -0
  139. /package/{spec → tests}/services/integration/client/download.jpg +0 -0
  140. /package/{spec → tests}/services/integration/client/favicon.ico +0 -0
  141. /package/{spec → tests}/services/integration/client/index.html +0 -0
  142. /package/{spec → tests}/services/integration/client/js/client.js +0 -0
  143. /package/{spec → tests}/services/integration/client/js/components/app.jsx +0 -0
  144. /package/{spec → tests}/services/integration/config/mimes.js +0 -0
  145. /package/{spec → tests}/services/integration/config/routes.js +0 -0
  146. /package/{spec → tests}/services/integration/config/ssl/certificate.pem +0 -0
  147. /package/{spec → tests}/services/integration/config/ssl/csr.csr +0 -0
  148. /package/{spec → tests}/services/integration/config/ssl/key.pem +0 -0
  149. /package/{spec → tests}/services/integration/config/ssl/private_key.pem +0 -0
  150. /package/{spec → tests}/services/integration/config/ssl/public_key.pem +0 -0
  151. /package/{spec → tests}/services/integration/package.json +0 -0
  152. /package/{spec → tests}/services/integration/server/views/defaultjson/testnojson.ejs +0 -0
  153. /package/{spec → tests}/services/integration/server/views/testreact/testreact.ejs +0 -0
@@ -0,0 +1,22 @@
1
+ import { type RoutesConfig } from '@projectinvicta/nails';
2
+
3
+ const routes: RoutesConfig = [
4
+ // Routes the root request to index.html, as well as all other requests to static
5
+ ['get', "/", {controller: 'home'}],
6
+ // Routes all requests starting with /public as static requests to the public folder.
7
+ ['get', '/public', {public: true}],
8
+
9
+ // A test route which routes the first part of pathname to controller and the second to the action
10
+ // ['get', /^\/(\w+)\/(\w+)$/i, {0: 'controller', 1: 'action'}],
11
+
12
+ // Maps the first two parts of the path to controller and action, and the third to the id parameter
13
+ // ['get', "/:controller/:action/:id"],
14
+
15
+ // For all other GET requests, render HomeController#index
16
+ ['get', '/:catchall', {controller: 'home'}],
17
+
18
+ // Defines a WebSocket handler
19
+ // ['ws', "/:controller/:action/:id"]
20
+ ];
21
+
22
+ export default routes;
@@ -13,7 +13,7 @@ import fs from 'node:fs';
13
13
  const PRIVATE_KEY_FILE = fs.readFileSync(`${import.meta.dirname}/ssl/key.pem`);
14
14
  const CERTIFICATE_FILE = fs.readFileSync(`${import.meta.dirname}/ssl/certificate.pem`);
15
15
 
16
- var config = {
16
+ var service = {
17
17
  APP_ROOT: APP_ROOT,
18
18
  // root directory for delivering static assets
19
19
  PUBLIC_ROOT: SERVER_ROOT + '/public',
@@ -38,7 +38,7 @@ var config = {
38
38
  };
39
39
 
40
40
  export default {
41
- config,
41
+ service,
42
42
  routes,
43
43
  mimes,
44
44
  db
@@ -22,17 +22,23 @@
22
22
  "version": "latest"
23
23
  }
24
24
  },
25
+ "imports": {
26
+ "#models/*": "./server/models/*",
27
+ "#common/*": "./common/*",
28
+ "#config/*": "./config/*"
29
+ },
25
30
  "dependencies": {
31
+ "@projectinvicta/nails": "*",
26
32
  "@mui/icons-material": "^7.3.1",
27
33
  "@mui/material": "^7.3.1",
28
34
  "@vitejs/plugin-legacy": "^6.1.1",
29
35
  "@vitejs/plugin-react": "^4.7.0",
30
- "nails-boilerplate": ">=1.1.0",
31
36
  "react": "^19.1.0",
32
37
  "react-dom": "^19.1.0",
33
38
  "react-router-dom": "^7.7.0",
34
39
  "sequelize": "^6.37.7",
35
- "vite": "^6.3.5"
40
+ "vite": "^6.3.5",
41
+ "chai-http": "*"
36
42
  },
37
43
  "devDependencies": {
38
44
  "@emotion/react": "^11.14.0",
@@ -1,57 +1,48 @@
1
- <h1 id="nailsboilerplateanodewebserviceframework">Nails-Boilerplate: A Node Webservice Framework</h1>
2
- <p>This framework is designed to provide a lightweight, configurable MVC backend
3
- for node developers. With minimal dependencies, Nails offers a greater
4
- syntactical familiarity than php alongside the creative freedom of well developed
5
- server framework solutions like Rails and Django.</p>
6
- <p>This boilerplate offers the basic necessities to get your MVC site off the ground.
7
- The modules used in Nails Boilerplate can be easily extended to produce the custom
8
- functionality to fit your needs, and you are encouraged to do so.</p>
9
- <h2 id="install">Install</h2>
10
- <pre><code>sudo npm install -g nails-boilerplate
1
+ <h1 id="nailsanodewebserviceframework">Nails: A Node Webservice Framework</h1>
2
+ <p>Nails is a lightweight, configurable MVC-inspired backend framework for Node.js. With minimal dependencies, Nails offers a familiar syntax for developers coming from frameworks like Ruby on Rails or Django, while providing the flexibility of JavaScript.</p>
3
+ <p>Nails provides the essential building blocks to get your MVC-style application up and running quickly. The modules used in Nails can be easily extended to produce the custom functionality to fit your needs, and you are encouraged to do so.</p>
4
+ <h2 id="gettingstarted">Getting Started</h2>
5
+ <p>There are two recommended ways to get started with Nails.</p>
6
+ <h3 id="usingnpxrecommended">Using NPX (Recommended)</h3>
7
+ <p>You can create a new Nails project without a global installation using <code>npx</code>:</p>
8
+ <pre><code class="bash language-bash">npx @projectinvicta/nails init &lt;app_name&gt;
9
+ </code></pre>
10
+ <h3 id="usingglobalinstall">Using Global Install</h3>
11
+ <p>Alternatively, you can install the package globally:</p>
12
+ <pre><code class="bash language-bash">npm install -g @projectinvicta/nails
11
13
 
12
14
  nails init &lt;app_name&gt;
13
15
  </code></pre>
14
- <p>This will initialize a barebones app in the directory of the same name. Take a
15
- look at the self-documented config files and example controller and view before
16
- getting started. Additional controllers and views will automatically be imported
17
- into nails. Now just hook the new controllers in with some new routes and you're
18
- off to a good start.</p>
19
- <pre><code>cd app_name
20
-
16
+ <p>After initializing your app, navigate into the new directory and start the server:</p>
17
+ <pre><code class="bash language-bash">cd &lt;app_name&gt;
21
18
  npm install
22
-
23
19
  npm start
24
20
  </code></pre>
25
21
  <h2 id="gettingtoknowyournailsservice">Getting to know your Nails service</h2>
26
22
  <p>For your convenience, here is a quick outline of the main components of a nails service.
27
23
  Remember: each object comes with an example file to use for reference when building your service.</p>
28
- <h3 id="config">Config</h3>
29
- <p>Your configuration files are stored in app_name/config/. There are three default config files:</p>
30
- <pre><code>service.js
31
- routes.js
32
- db.js
24
+ <h3 id="namedexports">Named Exports</h3>
25
+ <p><code>nails</code> now provides a number of useful named exports. You can import them as follows:</p>
26
+ <pre><code class="js language-js">import Nails, { Controller, Model, DataTypes, /* config types */ } from '@projectinvicta/nails';
33
27
  </code></pre>
28
+ <h3 id="config">Config</h3>
29
+ <p>Your configuration files are stored in app_name/config/.</p>
34
30
  <p>Each default config file is annotated with comments documenting each field to
35
31
  help you tailor your service to your needs.</p>
36
32
  <h4 id="servicejs">service.js</h4>
37
33
  <p>service.js contains information necessary to run your server. By default, it
38
- specifies the port and the location of important libraries. To override these
39
- values in different runtime environments, add a child object.</p>
34
+ specifies the port and the location of important libraries.</p>
40
35
  <pre><code class="js language-js">export default {
41
36
  ...
42
- PORT: 3000,
43
- PROD: {
44
- PORT: 80
45
- }
37
+ SERVER_ROOT: "/path/to/my/nails/service",
38
+ PORT: 3333,
39
+ SSL_PORT: 3334,
46
40
  }
47
41
  </code></pre>
48
- <p>Nails checks the NODE<em>ENV environment variable. If a matching child config
49
- object is present, then those values will override the parent config. In the
50
- above example, PORT will be overridden to 80 if NODE</em>ENV is set to PROD.</p>
51
42
  <p>While most of these values don't need to be changed, feel free to add custom
52
43
  fields. The resulting config will be available to your service through the nails
53
44
  module:</p>
54
- <pre><code class="js language-js">import nails from 'nails-boilerplate';
45
+ <pre><code class="js language-js">import Nails from '@projectinvicta/nails';
55
46
 
56
47
  const service_config = nails.config
57
48
  </code></pre>
@@ -66,7 +57,7 @@ const service_config = nails.config
66
57
  <code>'yourCustomValue'</code>.</p>
67
58
  <h4 id="routesjs">routes.js</h4>
68
59
  <p><em>routes.js</em> is a list defining mappings from a url path to a <em>Controller</em> and
69
- <em>Action</em>. Each entry in the list is an array with three elements:
60
+ <em>Action</em>. Routes are now strongly typed (see <code>lib/config.ts</code> and <code>lib/Router.ts</code>). Each entry in the list is an array with three elements:
70
61
  <code>[method, path, options]</code></p>
71
62
  <p><strong>method</strong> is a string defining the HTTP request method of the route. Supported
72
63
  methods are <em>GET</em>, <em>PUT</em>, <em>POST</em>, <em>DELETE</em>, and <em>ALL</em>. All is a special case
@@ -109,24 +100,18 @@ than indices. You can name your regex captures "controller" and/or "action"
109
100
  to dynamically route your request to the appropriate handler.</li>
110
101
  </ul>
111
102
  <h4 id="dbjs">db.js</h4>
112
- <p>Quickly configure your database connection here. Nails comes pre-configured to
113
- use the sequelize connector, giving your models sequelize support. The initial setup
114
- uses a <em>sqlite3</em> database file <code>config/development.db</code> and an in-memory database in the test environment. Change the address to change the location and
115
- version of your desired sql database. Check out <a href="https://sequelize.org">Sequelize</a>
116
- for more info.</p>
117
- <p>Alternatively, you can configure a connection to MongoDB using the mongoose_connector.js.
118
- If enabled, models will accept <a href="https://mongoosejs.com/docs/">Mongoose</a> schemas and will
119
- be backed by the desired MongoDB. Consider using the in-memory DB during development.</p>
103
+ <p>Quickly configure your database connection here. The initial setup uses a <em>sqlite3</em> database file <code>config/development.db</code>
104
+ and an in-memory database in the test environment. Change the address to change the location and
105
+ version of your desired sql database. Check out <a href="https://sequelize.org">Sequelize</a> for more info.</p>
120
106
  <h2 id="controller">Controller</h2>
121
107
  <p>Controllers are defined in app/controllers/. Each controller module should
122
108
  define a Controller subclass. The name will be used to match routes defined in
123
109
  config/routes.js for incoming requests. Methods on the controller can be used as
124
110
  actions, receiving <strong>params</strong>, <strong>request</strong>, and <strong>response</strong> as arguments.</p>
125
111
  <p>For Example:</p>
126
- <pre><code class="js language-js">// const Controller = requre("nails-boilerplate").Controller
127
- import nails from 'nails-boilerplate';
112
+ <pre><code class="js language-js">import { Controller } from '@projectinvicta/nails';
128
113
 
129
- class HomeController extends nails.Controller {
114
+ class HomeController extends Controller {
130
115
  index(params, request, response) {
131
116
  // default action
132
117
  }
@@ -154,7 +139,9 @@ object returned by the getData function. If the route is changed to:</p>
154
139
  <p><code>["get", "/data", {action: 'getData', json: true}],</code></p>
155
140
  <p>it will accept GET requests to /data instead. All local routes are
156
141
  implicitly routed to their respective parent controllers.</p>
157
- <pre><code class="js language-js">export default class UsersController extends nails.Controller {
142
+ <pre><code class="js language-js">import { Controller } from '@projectinvicta/nails';
143
+
144
+ export default class UsersController extends Controller {
158
145
  routes = [
159
146
  // Routes requests to /absolute/path
160
147
  ['get', '/absolute/path', {action: 'actionA'}],
@@ -226,8 +213,11 @@ overridden to allow for the rendering of views by name.</p>
226
213
  <pre><code class="js language-js">['get', '/your/json/route', {json: true}],
227
214
  </code></pre>
228
215
  <h5 id="apicontrollers">API Controllers</h5>
229
- <p>By setting <code>json</code> to <code>true</code>, all actions in a controller will respond with JSON.</p>
230
- <pre><code class="js language-js">class YourApiController extends nails.Controller {
216
+ <p>By setting <code>json</code> to <code>true</code>, all actions in a controller will respond with JSON by default.
217
+ This can be overridden for individual routes by setting <code>{json: false}</code> in the route options.</p>
218
+ <pre><code class="js language-js">import { Controller } from '@projectinvicta/nails';
219
+
220
+ class YourApiController extends Controller {
231
221
  json = true;
232
222
 
233
223
  action(params, request, response) {
@@ -236,23 +226,24 @@ overridden to allow for the rendering of views by name.</p>
236
226
  }
237
227
  </code></pre>
238
228
  <h2 id="model">Model</h2>
239
- <p>Models are programmatic representations of data you wish to persist in a
240
- database. The constructor for Model accepts two arguments: the <code>modelName</code> and an
241
- <code>options</code> object which is passed to the database connector module.</p>
229
+ <p>Models are programmatic representations of data you wish to persist in a database. Nails connects to
230
+ your database of choice using the Sequelize ORM.</p>
242
231
  <h3 id="sequelizemodels">Sequelize Models</h3>
243
232
  <p>Sequelize models are subclasses of
244
233
  <a href="https://sequelize.org/docs/v6/core-concepts/model-basics/">Sequelize Models</a>, and come with the <code>count()</code>, <code>findAll()</code>,
245
234
  and <code>create()</code> methods, to name a few. You can define your own models by
246
- extending an instance of the <code>Model</code> class provided by Nails:</p>
247
- <pre><code class="js language-js">// const Model = require("nails-boilerplate").Model;
248
- import nails from 'nails-boilerplate';
249
- import {DataTypes} from 'sequelize';
250
- schema = {
235
+ extending an instance of the <code>Model</code> class provided by Nails. Model files must export the Model subclass as a default export and a named <code>schema</code> export.
236
+ They can also export an <code>options</code> object to provide ModelInitializationOptions as well as <code>defer</code>, <code>finalize</code>, and <code>migrate</code> functions.</p>
237
+ <pre><code class="js language-js">import { Model, DataTypes } from '@projectinvicta/nails';
238
+
239
+ // REQUIRED
240
+ export const schema = {
251
241
  name: {type: DataTypes.STRING, allowNull: false},
252
242
  email: {type: DataTypes.STRING, allowNull: false}
253
243
  };
254
244
 
255
- options = {
245
+ // Optional
246
+ export const options = {
256
247
  indexes: [
257
248
  {
258
249
  unique: true,
@@ -261,30 +252,34 @@ options = {
261
252
  ],
262
253
  };
263
254
 
264
- export default class User extends new Model("User", {schema, options}) {
255
+ // REQUIRED
256
+ export default class User extends Model {
265
257
  someHelperMethod() {
266
258
  // This method will be available on all instances of User and is
267
259
  // an ideal way to simplify data manipulation.
268
260
  }
269
261
  };
262
+
263
+ // Optional
264
+ export async function defer(models) {
265
+ // define associations here
266
+ }
267
+
268
+ // Optional
269
+ export async function finalize(models) {
270
+ // any final model setup
271
+ }
272
+
273
+ // Optional
274
+ export async function migrate(queryInterface) {
275
+ // migration logic
276
+ }
270
277
  </code></pre>
271
- <h3 id="mongoosemodels">Mongoose Models</h3>
272
- <p>Mongoose models are subclasses of
273
- <a href="https://mongoosejs.com/docs/api/model.html">Mongoose Models</a>, and come with the <code>save()</code>, <code>find()</code>,
274
- and <code>where()</code> methods, to name a few. You can define your own models by
275
- extending an instance of the <code>Model</code> class provided by Nails:</p>
276
- <pre><code class="js language-js">// const Model = require("nails-boilerplate").Model;
277
- import nails from 'nails-boilerplate';
278
- const userSchema = {name: String, email: String};
279
- export default class User extends new Model("User", {schema: userSchema}) {
280
- // Define your helper methods here
281
- };
282
- </code></pre>
283
- <p>The <code>schema</code> option for Mongoose Models accepts a schema field that is used
284
- to define how documents are stored in MongoDB.</p>
285
278
  <h3 id="modellibrary">Model Library</h3>
286
279
  <p>Nails will store all instantialized models in a single object called <code>MODELS</code>. By accessing these models via the library, you can avoid circular dependencies and ensure all models have been fully initialized.</p>
287
- <pre><code class="js language-js">class User extends nails.Model("User", {schema, options}) {
280
+ <pre><code class="js language-js">import Nails, { Model } from '@projectinvicta/nails';
281
+ // ...
282
+ class User extends Model {
288
283
  // A helper method which depends on anoher model using the
289
284
  // Nails Model Library rather than directly importing the model.
290
285
  async findFriends() {
@@ -293,18 +288,6 @@ to define how documents are stored in MongoDB.</p>
293
288
  }
294
289
  </code></pre>
295
290
  <p>This design pattern is not always necessary, but will help avoid circular dependencies.</p>
296
- <h3 id="databaseconnectors">Database Connectors</h3>
297
- <p>Database connectors are intermediaries which define how a Model interacts with
298
- a database. Database connector modules need to export two methods:</p>
299
- <ul>
300
- <li><em>connect(db</em>config)_ uses the db config defined in <em>db.js</em> to connect to
301
- a database. This function will be called once by Nails.</li>
302
- <li><em>generateModelSuperclass(name, options)</em> uses the provided Model name and
303
- options to generate a Model prototype for use as an interface. A Model
304
- interface is generated for each of your models, allowing them to interact with
305
- a database. Ideally, interfaces will define save() and find() methods, but
306
- these methods and their implementations are up to the individual connector.</li>
307
- </ul>
308
291
  <h2 id="view">View</h2>
309
292
  <p>Views are dynamic templates used to render an html response for a browser.
310
293
  Nails comes prepackaged with EJS templates.
@@ -1,6 +1,6 @@
1
- import nails from "nails-boilerplate";
1
+ import {Controller} from "@projectinvicta/nails";
2
2
 
3
- export default class HomeController extends nails.Controller {
3
+ export default class HomeController extends Controller {
4
4
  /**
5
5
  * You can define a local routing table directly in the controller.
6
6
  * Local routes take precidence over global routes. All local routes
@@ -1,34 +1,29 @@
1
- import nails from "nails-boilerplate";
2
-
3
- export default class HomeController extends nails.Controller {
4
- /**
5
- * You can define a local routing table directly in the controller.
6
- * Local routes take precidence over global routes. All local routes
7
- * are prefixed with the controller name unless they start with '/'.
8
- * For example, in HomeController the following route:
9
- *
10
- * ["get", "data", {action: 'getData', json: true}],
11
- *
12
- * will accept GET requests to /home/data and respond with the json
13
- * object returned by the getData function. If the route is changed to:
14
- *
15
- * ["get", "/data", {action: 'getData', json: true}],
16
- *
17
- * it will accept GET requests to /data instead. All local routes are
18
- * implicitly routed to their respective parent controllers.
19
- */
20
- routes = [
21
- ["get", "data", {action: 'getData', json: true}],
22
- ];
23
-
24
- index(params, request, response) {
25
- return {
26
- title: "My first Nails Service",
27
- welcome_message: "Welcome to Nails"
28
- };
29
- }
30
-
31
- getData(params, request, response) {
32
- return {testData: Math.floor(Math.random() * 10000000)}
33
- }
34
- };
1
+ import {Controller} from "@projectinvicta/nails";
2
+ import User from "../models/User";
3
+
4
+ export default class UsersController extends Controller {
5
+ /**
6
+ * You can define a local routing table directly in the controller.
7
+ * Local routes take precidence over global routes. All local routes
8
+ * are prefixed with the controller name unless they start with '/'.
9
+ * For example, in HomeController the following route:
10
+ *
11
+ * ["get", "data", {action: 'getData', json: true}],
12
+ *
13
+ * will accept GET requests to /home/data and respond with the json
14
+ * object returned by the getData function. If the route is changed to:
15
+ *
16
+ * ["get", "/data", {action: 'getData', json: true}],
17
+ *
18
+ * it will accept GET requests to /data instead. All local routes are
19
+ * implicitly routed to their respective parent controllers.
20
+ */
21
+ routes = [
22
+ ["get", "./list"],
23
+ ];
24
+
25
+ async list(params, request, response) {
26
+ return await User.findAll();
27
+ }
28
+
29
+ };
@@ -0,0 +1,8 @@
1
+ import {Model, DataTypes} from "@projectinvicta/nails";
2
+
3
+ export const schema = {
4
+ good: DataTypes.BOOLEAN,
5
+ name: DataTypes.STRING,
6
+ };
7
+
8
+ export default class Dog extends Model {};
@@ -0,0 +1,14 @@
1
+ import {Model, DataTypes} from "@projectinvicta/nails";
2
+ import Dog from "./Dog";
3
+
4
+ export const schema = {
5
+ name: DataTypes.STRING,
6
+ verified: DataTypes.BOOLEAN,
7
+ email: DataTypes.STRING,
8
+ }
9
+
10
+ export default class User extends Model {};
11
+
12
+ export async function defer() {
13
+ await User.hasMany(Dog);
14
+ }
@@ -1,19 +1,21 @@
1
- import nails from "nails-boilerplate";
2
- import service_config from '../config/service.js';
1
+ import Nails from "@projectinvicta/nails";
2
+ import User from "#models/User";
3
+ import service_config from '#config/service.js';
3
4
  import { beforeAll, test, expect } from "vitest";
4
5
 
5
6
  const TEST_USER_EMAIL = "test@test.com";
6
7
  const TEST_USER_NAME = "JohnDoe";
7
8
  beforeAll(async () => {
8
9
  // Only initialize the Models.
9
- await nails.MODELS.init( service_config );
10
+ await new Nails(service_config).configure();
11
+ // await nails.MODELS.init( service_config );
10
12
  });
11
13
 
12
14
  test("Can create a User", async () => {
13
- const user = await nails.MODELS.User.create({name: TEST_USER_NAME, email: TEST_USER_EMAIL});
15
+ const user = await User.create({name: TEST_USER_NAME, email: TEST_USER_EMAIL});
14
16
 
15
17
  expect(user.id).toBeDefined();
16
- const retrievedUser = await nails.MODELS.User.findByPk(user.id);
18
+ const retrievedUser = await User.findByPk(user.id);
17
19
  expect(retrievedUser.id).toBeDefined();
18
20
  expect(retrievedUser.name).toEqual(TEST_USER_NAME);
19
21
  expect(retrievedUser.email).toEqual(TEST_USER_EMAIL);
@@ -1,4 +1,4 @@
1
- import nails from 'nails-boilerplate';
1
+ import Nails from "@projectinvicta/nails";
2
2
  // import chai from 'chai';
3
3
  import {default as chaiHttp, request} from 'chai-http';
4
4
  import service_config from '../config/service.js';
@@ -8,8 +8,8 @@ let express_app;
8
8
 
9
9
  beforeAll(async () => {
10
10
  // Initialize the application and start the server
11
- (await nails( service_config )).startServer();
12
- express_app = nails.application;
11
+ await new Nails( service_config ).startServer();
12
+ express_app = Nails.application;
13
13
  chai.use(chaiHttp);
14
14
  chai.should();
15
15
  })
@@ -0,0 +1,3 @@
1
+ import { describe, it, expect, vi } from 'vitest';
2
+
3
+ it.todo('Should test something');
@@ -0,0 +1,61 @@
1
+ import { describe, it, expect, vi } from 'vitest';
2
+ import Controller from '../lib/Controller.ts';
3
+ import {EventEmitter} from 'node:events';
4
+
5
+ class TestController extends Controller {
6
+ testAction() {};
7
+ };
8
+
9
+ class TestEs6Controller extends Controller {
10
+ testEs6Action() {
11
+
12
+ }
13
+
14
+ }
15
+
16
+ describe('Controller', () => {
17
+ describe('Controller.setRouter', () => {
18
+ it('should set Controller.router to the router', () => {
19
+ const router = {};
20
+ Controller.setRouter(router);
21
+ expect(Controller.router).toBe(router);
22
+ });
23
+ });
24
+ describe('Controller.constructor', () => {
25
+ it('should set the appropriate listener on the router',
26
+ () => {
27
+ const mockRouter = new EventEmitter();
28
+ const mockParams = {_controller: "test"};
29
+ const mockRequest = {};
30
+ const mockResponse = {headersSent: true};
31
+ Controller.setRouter(mockRouter);
32
+ const testController = new TestEs6Controller();
33
+ const spy = vi.spyOn(testController, "testEs6Action");
34
+
35
+ mockRouter.emit(
36
+ 'dispatchTo:testes6',
37
+ {action: 'testEs6Action', params: mockParams, request: mockRequest, response: mockResponse});
38
+
39
+ expect(spy).toHaveBeenCalledWith(
40
+ mockParams, mockRequest, mockResponse);
41
+ });
42
+ });
43
+ describe('#_do', () => {
44
+ it.todo('should call the function on the controller matching the given action');
45
+ it.todo('should call 404 if the action does not exist on the controller instance');
46
+ it.todo('should call 500 if the action throws an error');
47
+ it.todo('should attempt to render a view');
48
+ it.todo('should not render a view if data has already been sent to the client');
49
+ it.todo('should not render a view if _async is true');
50
+ it.todo('should not render a view if async is true on the action');
51
+ });
52
+ describe('#404', () => {
53
+ it.todo('should test something');
54
+ });
55
+ describe('#500', () => {
56
+ it.todo('should test something');
57
+ });
58
+ describe('#public', () => {
59
+ it.todo('should test something');
60
+ });
61
+ });
@@ -0,0 +1,4 @@
1
+ // TODO test all initialization here
2
+ import { describe, it, expect, vi } from 'vitest';
3
+
4
+ it.todo('Should test something');
@@ -0,0 +1,105 @@
1
+ import { describe, it, expect, beforeEach } from 'vitest';
2
+ import Router from '../lib/Router.ts';
3
+ import express_app from '../lib/application.ts';
4
+
5
+ express_app.set("public_root", import.meta.dirname + "/services/integration/public");
6
+ const testRoutes = [
7
+ ['GET', '^/$', {controller: 'testController', action: 'testAction'}],
8
+ ['GET', /^\/public\/*/, {public: true}]
9
+ ];
10
+
11
+ let router;
12
+
13
+ describe('Router', () => {
14
+ describe('route', () => {
15
+ beforeEach(() => {
16
+ router = new Router(testRoutes);
17
+ });
18
+
19
+ it(`should emit dispatchTo:application if a registered controller does
20
+ not match the action`, async () => {
21
+ const mockRequest = {
22
+ method: 'get',
23
+ url: 'http://www.test.com/public/test.html'
24
+ };
25
+ const mockResponse = {};
26
+ const expectedAction = 404;
27
+
28
+ const dispatchPromise = new Promise(resolve => {
29
+ router.on('dispatchTo:application', ({action, params, request, response}) => {
30
+ resolve({action, params, request, response});
31
+ });
32
+ });
33
+
34
+ router.route(mockRequest, mockResponse);
35
+
36
+ const {action, params, request, response} = await dispatchPromise;
37
+
38
+ expect(action).toEqual(expectedAction);
39
+ expect(typeof(params)).toBe('object');
40
+ expect(params.file).toBeUndefined();
41
+ expect(request).toBe(mockRequest);
42
+ expect(response).toBe(mockResponse);
43
+ });
44
+
45
+ it('should emit dispatch:<controller> event based on the params', async () => {
46
+ const mockParams = {
47
+ _controller: "test",
48
+ _action: "testAction"
49
+ };
50
+ const mockRequest = {
51
+ method: 'get',
52
+ url: 'http://www.test.com/',
53
+ params: mockParams
54
+ };
55
+ const mockResponse = {};
56
+ const expectedAction = 'testAction';
57
+
58
+ const dispatchPromise = new Promise(resolve => {
59
+ router.on('dispatchTo:test', ({action, params, request, response}) => {
60
+ resolve({action, params, request, response});
61
+ });
62
+ });
63
+
64
+ router.route(mockRequest, mockResponse);
65
+
66
+ const {action, params, request, response} = await dispatchPromise;
67
+
68
+ expect(action).toEqual(expectedAction);
69
+ expect(params._controller).toEqual(mockParams._controller);
70
+ expect(params._action).toEqual(mockParams._action);
71
+ expect(request).toBe(mockRequest);
72
+ expect(response).toBe(mockResponse);
73
+ });
74
+
75
+ it("should emit dispatch:<controller> event based on the url query", async () => {
76
+ const mockQuery = {
77
+ _controller: "test",
78
+ _action: "testAction"
79
+ };
80
+ const mockRequest = {
81
+ method: 'get',
82
+ url: 'http://www.test.com/',
83
+ query: mockQuery
84
+ };
85
+ const mockResponse = {};
86
+ const expectedAction = 'testAction';
87
+
88
+ const dispatchPromise = new Promise(resolve => {
89
+ router.on('dispatchTo:test', ({action, params, request, response}) => {
90
+ resolve({action, params, request, response});
91
+ });
92
+ });
93
+
94
+ router.route(mockRequest, mockResponse);
95
+
96
+ const {action, params, request, response} = await dispatchPromise;
97
+
98
+ expect(action).toEqual(expectedAction);
99
+ expect(params._controller).toEqual(mockQuery._controller);
100
+ expect(params._action).toEqual(mockQuery._action);
101
+ expect(request).toBe(mockRequest);
102
+ expect(response).toBe(mockResponse);
103
+ });
104
+ });
105
+ });