velocious 1.0.22 → 1.0.24

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.
package/README.md CHANGED
@@ -32,13 +32,90 @@ npx velocious db:migrate
32
32
  # Models
33
33
 
34
34
  ```bash
35
- npx velocious g:model Option
35
+ npx velocious g:model Task
36
+ ```
37
+
38
+ # Migrations
39
+ ```bash
40
+ npx velocious g:migration create-tasks
41
+ ```
42
+
43
+ ```js
44
+ import Migration from "velocious/src/database/migration/index.js"
45
+
46
+ export default class CreateEvents extends Migration {
47
+ async up() {
48
+ await this.createTable("tasks", (t) => {
49
+ t.timestamps()
50
+ })
51
+
52
+ await this.createTable("task_translations", (t) => {
53
+ t.references("task", {foreignKey: true, null: false})
54
+ t.string("locale", {null: false})
55
+ t.string("name")
56
+ t.timestamps()
57
+ })
58
+
59
+ await this.addIndex("task_translations", ["task_id", "locale"], {unique: true})
60
+ }
61
+
62
+ async down() {
63
+ await this.dropTable("task_translations")
64
+ await this.dropTable("tasks")
65
+ }
66
+ }
67
+ ```
68
+
69
+ # Querying
70
+
71
+ ```js
72
+ import {Task} from "@/src/models/task"
73
+
74
+ const tasks = await Task
75
+ .preload({project: {account: true}})
76
+ .where({projects: {public: true}})
77
+ .toArray()
36
78
  ```
37
79
 
38
80
  # Testing
39
81
 
82
+ If you are using Velocious for an app, Velocious has a built-in testing framework. You can run your tests like this:
40
83
  ```bash
41
- npm test
84
+ npx velocious test
85
+ ```
86
+
87
+ If you are developing on Velocious, you can run the tests with:
88
+
89
+ ```bash
90
+ npm run test
91
+ ```
92
+
93
+ # Writing a require test
94
+
95
+ First create a test file under something like the following path 'src/routes/accounts/create-test.js' with something like the following content:
96
+
97
+ ```js
98
+ import {describe, expect, it} from "velocious/src/testing/test.js"
99
+ import Account from "../../models/account.js"
100
+
101
+ await describe("accounts - create", {type: "request"}, async () => {
102
+ it("creates an account", async ({client}) => {
103
+ const response = await client.post("/accounts", {account: {name: "My event company"}})
104
+
105
+ expect(response.statusCode()).toEqual(200)
106
+ expect(response.contentType()).toEqual("application/json")
107
+
108
+ const data = JSON.parse(response.body())
109
+
110
+ expect(data.status).toEqual("success")
111
+
112
+ const createdAccount = await Account.last()
113
+
114
+ expect(createdAccount).toHaveAttributes({
115
+ name: "My event company"
116
+ })
117
+ })
118
+ })
42
119
  ```
43
120
 
44
121
  # Running a server
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "velocious": "bin/velocious.js"
4
4
  },
5
5
  "name": "velocious",
6
- "version": "1.0.22",
6
+ "version": "1.0.24",
7
7
  "main": "index.js",
8
8
  "scripts": {
9
9
  "test": "jasmine",
@@ -1,4 +1,4 @@
1
- import TestFilesFinder from "../../../../src/cli/commands/test/test-files-finder.js"
1
+ import TestFilesFinder from "../../../../src/testing/test-files-finder.js"
2
2
 
3
3
  describe("Cli - Commands - test - TestFilesFinder", () => {
4
4
  it("finds the correct test files", async () => {
@@ -43,6 +43,7 @@ export default class VelociousApplication {
43
43
  logger(this, `Starting server on port ${port}`)
44
44
 
45
45
  this.httpServer = new HttpServer({configuration, port})
46
+ this.httpServer.events.on("close", this.onHttpServerClose)
46
47
 
47
48
  await this.httpServer.start()
48
49
  }
@@ -52,4 +53,18 @@ export default class VelociousApplication {
52
53
 
53
54
  await this.httpServer.stop()
54
55
  }
56
+
57
+ onHttpServerClose = () => {
58
+ console.log("HTTP server closed")
59
+
60
+ if (this.waitResolve) {
61
+ this.waitResolve()
62
+ }
63
+ }
64
+
65
+ wait() {
66
+ return new Promise((resolve) => {
67
+ this.waitResolve = resolve
68
+ })
69
+ }
55
70
  }
@@ -5,10 +5,8 @@ export default class VelociousCliCommandsServer extends BaseCommand{
5
5
  async execute() {
6
6
  this.databasePool = this.configuration.getDatabasePool()
7
7
  this.newConfiguration = Object.assign({}, this.databasePool.getConfiguration())
8
-
9
- if (this.args.testing) this.result = []
10
-
11
8
  this.databaseConnection = await this.databasePool.spawnConnectionWithConfiguration(this.newConfiguration)
9
+
12
10
  await this.databaseConnection.connect()
13
11
 
14
12
  const host = "0.0.0.0"
@@ -23,7 +21,7 @@ export default class VelociousCliCommandsServer extends BaseCommand{
23
21
 
24
22
  await application.initialize()
25
23
  await application.startHttpServer()
26
-
27
24
  console.log(`Started Velocious HTTP server on ${host}:${port}`)
25
+ await application.wait()
28
26
  }
29
27
  }
@@ -1,13 +1,12 @@
1
- import BaseCommand from "../../base-command.js"
2
- import TestFilesFinder from "./test-files-finder.js"
3
- import TestRunner from "./test-runner.js"
1
+ import BaseCommand from "../base-command.js"
2
+ import TestFilesFinder from "../../testing/test-files-finder.js"
3
+ import TestRunner from "../../testing/test-runner.js"
4
4
 
5
5
  export default class VelociousCliCommandsInit extends BaseCommand {
6
6
  async execute() {
7
7
  const testFilesFinder = new TestFilesFinder({directory: this.directory(), processArgs: this.processArgs})
8
8
  const testFiles = await testFilesFinder.findTestFiles()
9
-
10
- const testRunner = new TestRunner(testFiles)
9
+ const testRunner = new TestRunner({configuration: this.configuration, testFiles})
11
10
 
12
11
  await testRunner.run()
13
12
  }
@@ -13,16 +13,27 @@ export default class VelociousDatabaseMigrateFromRequireContext {
13
13
 
14
14
  const files = requireContext.keys()
15
15
  .map((file) => {
16
- const match = file.match(/(\d{14})-(.+)\.js$/)
16
+ // "13,14" because somes "require-context"-npm-module deletes first character!?
17
+ const match = file.match(/(\d{13,14})-(.+)\.js$/)
17
18
 
18
19
  if (!match) return null
19
20
 
20
- const date = parseInt(match[1])
21
+ // Fix require-context-npm-module deletes first character
22
+ let fileName = file
23
+ let dateNumber = match[1]
24
+
25
+ if (dateNumber.length == 13) {
26
+ dateNumber = `2${dateNumber}`
27
+ fileName = `2${fileName}`
28
+ }
29
+
30
+ // Parse regex
31
+ const date = parseInt(dateNumber)
21
32
  const migrationName = match[2]
22
33
  const migrationClassName = inflection.camelize(migrationName.replaceAll("-", "_"))
23
34
 
24
35
  return {
25
- file,
36
+ file: fileName,
26
37
  date,
27
38
  migrationClassName
28
39
  }
@@ -5,29 +5,30 @@ import useEnvSense from "env-sense/src/use-env-sense.js"
5
5
  import Configuration from "../configuration.js"
6
6
  import restArgsError from "../utils/rest-args-error.js"
7
7
 
8
- const shared = {
9
- loaded: false
10
- }
11
-
12
8
  const loadMigrations = function loadMigrations({migrationsRequireContext, ...restArgs}) {
9
+ const instance = React.useMemo(() => ({running: false}), [])
13
10
  const {isServer} = useEnvSense()
14
- const [loaded, setLoaded] = React.useState(shared.loaded)
11
+ const [loaded, setLoaded] = React.useState(false)
15
12
 
16
13
  const loadDatabase = React.useCallback(async () => {
17
- await Configuration.current().getDatabasePool().withConnection(async () => {
18
- const databaseMigrateFromRequireContext = new DatabaseMigrateFromRequireContext()
14
+ instance.running = true
19
15
 
20
- await databaseMigrateFromRequireContext.execute(migrationsRequireContext)
21
- })
16
+ try {
17
+ await Configuration.current().getDatabasePool().withConnection(async () => {
18
+ const databaseMigrateFromRequireContext = new DatabaseMigrateFromRequireContext()
22
19
 
23
- await Configuration.current().initialize()
20
+ await databaseMigrateFromRequireContext.execute(migrationsRequireContext)
21
+ })
24
22
 
25
- shared.loaded = true
26
- setLoaded(true)
23
+ await Configuration.current().initialize()
24
+ setLoaded(true)
25
+ } finally {
26
+ instance.running = false
27
+ }
27
28
  }, [])
28
29
 
29
30
  React.useMemo(() => {
30
- if (!loaded && !isServer) {
31
+ if (!loaded && !isServer && !instance.running) {
31
32
  loadDatabase()
32
33
  }
33
34
  }, [loaded])
@@ -157,7 +157,7 @@ export default class RequestBuffer {
157
157
  } else if (this.httpMethod.toUpperCase() == "POST") {
158
158
  this.readingBody = true
159
159
 
160
- const match = this.getHeader("content-type").value.match(/^multipart\/form-data;\s*boundary=(.+)$/i)
160
+ const match = this.getHeader("content-type")?.value?.match(/^multipart\/form-data;\s*boundary=(.+)$/i)
161
161
 
162
162
  if (match) {
163
163
  this.boundary = match[1]
@@ -1,4 +1,5 @@
1
1
  import {digg} from "diggerize"
2
+ import EventEmitter from "events"
2
3
  import logger from "../logger.js"
3
4
  import Net from "net"
4
5
  import ServerClient from "./server-client.js"
@@ -7,6 +8,7 @@ import WorkerHandler from "./worker-handler/index.js"
7
8
  export default class VelociousHttpServer {
8
9
  clientCount = 0
9
10
  clients = {}
11
+ events = new EventEmitter()
10
12
  workerCount = 0
11
13
  workerHandlers = []
12
14
 
@@ -20,6 +22,7 @@ export default class VelociousHttpServer {
20
22
  async start() {
21
23
  await this._ensureAtLeastOneWorker()
22
24
  this.netServer = new Net.Server()
25
+ this.netServer.on("close", this.onClose)
23
26
  this.netServer.on("connection", this.onConnection)
24
27
  await this._netServerListen()
25
28
  }
@@ -72,6 +75,10 @@ export default class VelociousHttpServer {
72
75
  await this.stopServer()
73
76
  }
74
77
 
78
+ onClose = () => {
79
+ this.events.emit("close")
80
+ }
81
+
75
82
  onConnection = (socket) => {
76
83
  const clientCount = this.clientCount
77
84
 
package/src/logger.js CHANGED
@@ -1,5 +1,3 @@
1
- import {digg} from "diggerize"
2
-
3
1
  export default function log(object, ...messages) {
4
2
  if (!object.configuration) console.error(`No configuration on ${object.constructor.name}`)
5
3
 
@@ -0,0 +1,42 @@
1
+ class Response {
2
+ constructor(fetchResponse) {
3
+ this.fetchResponse = fetchResponse
4
+ }
5
+
6
+ async parse() {
7
+ this._body = await this.fetchResponse.text()
8
+ }
9
+
10
+ body = () => this._body
11
+ contentType = () => this.fetchResponse.headers.get("content-type")
12
+ statusCode = () => this.fetchResponse.status
13
+ }
14
+
15
+ export default class RequestClient {
16
+ host = "localhost"
17
+ port = 31006
18
+
19
+ get() {
20
+ throw new Error("get stub")
21
+ }
22
+
23
+ async post(path, data) {
24
+ const fetchResponse = await fetch(
25
+ `http://${this.host}:${this.port}${path}`,
26
+ {
27
+ body: JSON.stringify(data),
28
+ headers: {
29
+ "Content-Type": "application/json"
30
+ },
31
+ method: "POST",
32
+ signal: AbortSignal.timeout(5000)
33
+ }
34
+ )
35
+
36
+ const response = new Response(fetchResponse)
37
+
38
+ await response.parse()
39
+
40
+ return response
41
+ }
42
+ }
@@ -90,7 +90,7 @@ export default class TestFilesFinder {
90
90
  return true
91
91
  }
92
92
  }
93
- } else if (file.match(/-spec\.js/)) {
93
+ } else if (file.match(/-(spec|test)\.js/)) {
94
94
  return true
95
95
  }
96
96
 
@@ -0,0 +1,85 @@
1
+ import Application from "../../src/application.js"
2
+ import RequestClient from "./request-client.js"
3
+ import {tests} from "./test.js"
4
+
5
+ export default class TestRunner {
6
+ constructor({configuration, testFiles}) {
7
+ this.configuration = configuration
8
+ this.testFiles = testFiles
9
+ }
10
+
11
+ async application() {
12
+ if (!this._application) {
13
+ this._application = new Application({
14
+ configuration: this.configuration,
15
+ databases: {
16
+ default: {
17
+ host: "mysql",
18
+ username: "user",
19
+ password: ""
20
+ }
21
+ },
22
+ httpServer: {port: 31006}
23
+ })
24
+
25
+ await this._application.initialize()
26
+ await this._application.startHttpServer()
27
+ }
28
+
29
+ return this._application
30
+ }
31
+
32
+ async requestClient() {
33
+ if (!this._requestClient) {
34
+ this._requestClient = new RequestClient()
35
+ }
36
+
37
+ return this._requestClient
38
+ }
39
+
40
+ async importTestFiles() {
41
+ for (const testFile of this.testFiles) {
42
+ const importTestFile = await import(testFile)
43
+ }
44
+ }
45
+
46
+ async run() {
47
+ await this.importTestFiles()
48
+ await this.runTests(tests, [], 0)
49
+ }
50
+
51
+ async runTests(tests, descriptions, indentLevel) {
52
+ const leftPadding = " ".repeat(indentLevel * 2)
53
+
54
+ for (const testDescription in tests.tests) {
55
+ const testData = tests.tests[testDescription]
56
+ const testArgs = Object.assign({}, testData.args)
57
+ const testName = descriptions.concat([`it ${testDescription}`]).join(" - ")
58
+
59
+ if (testArgs.type == "request") {
60
+ testArgs.application = await this.application()
61
+ testArgs.client = await this.requestClient()
62
+ }
63
+
64
+ console.log(`${leftPadding}it ${testDescription}`)
65
+
66
+ try {
67
+ await testData.function(testArgs)
68
+ } catch (error) {
69
+ // console.error(`${leftPadding} Test failed: ${error.message}`)
70
+ console.error(error.stack)
71
+ }
72
+ }
73
+
74
+ await this.configuration.getDatabasePool().withConnection(async () => {
75
+ for (const subDescription in tests.subs) {
76
+ const subTest = tests.subs[subDescription]
77
+ const newDecriptions = descriptions.concat([subDescription])
78
+
79
+ console.log(`${leftPadding}${subDescription}`)
80
+
81
+ await this.runTests(subTest, newDecriptions, indentLevel + 1)
82
+ }
83
+ })
84
+ }
85
+ }
@@ -0,0 +1,92 @@
1
+ const tests = {
2
+ args: {},
3
+ subs: {},
4
+ tests: {}
5
+ }
6
+
7
+ let currentPath = [tests]
8
+
9
+ class Expect {
10
+ constructor(object) {
11
+ this._object = object
12
+ }
13
+
14
+ toEqual(result) {
15
+ if (this._object != result) {
16
+ throw new Error(`${this._object} wasn't equal to ${result}`)
17
+ }
18
+ }
19
+
20
+ toHaveAttributes(result) {
21
+ const differences = {}
22
+
23
+ for (const key in result) {
24
+ const value = result[key]
25
+ const objectValue = this._object[key]()
26
+
27
+ if (value != objectValue) {
28
+ differences[key] = [value, objectValue]
29
+ }
30
+ }
31
+
32
+ if (Object.keys(differences).length > 0)
33
+ throw new Error(`Object had differet values: ${JSON.stringify(differences)}`)
34
+ }
35
+ }
36
+
37
+ async function describe(description, arg1, arg2) {
38
+ let testArgs, testFunction
39
+
40
+ if (typeof arg2 == "function") {
41
+ testFunction = arg2
42
+ testArgs = arg1
43
+ } else if (typeof arg1 == "function") {
44
+ testFunction = arg1
45
+ testArgs = {}
46
+ } else {
47
+ throw new Error(`Invalid arguments for describe: ${arg1}, ${arg2}`)
48
+ }
49
+
50
+ const currentTest = currentPath[currentPath.length - 1]
51
+ const newTestArgs = Object.assign({}, currentTest.args, testArgs)
52
+
53
+ if (description in currentTest.subs) {
54
+ throw new Error(`Duplicate test description: ${description}`)
55
+ }
56
+
57
+ const newTestData = {args: newTestArgs, subs: {}, tests: {}}
58
+
59
+ currentTest.subs[description] = newTestData
60
+ currentPath.push(newTestData)
61
+
62
+ try {
63
+ await testFunction()
64
+ } finally {
65
+ currentPath.pop()
66
+ }
67
+ }
68
+
69
+ function expect(arg) {
70
+ return new Expect(arg)
71
+ }
72
+
73
+ function it(description, arg1, arg2) {
74
+ const currentTest = currentPath[currentPath.length - 1]
75
+ let testArgs, testFunction
76
+
77
+ if (typeof arg1 == "function") {
78
+ testFunction = arg1
79
+ testArgs = {}
80
+ } else if (typeof arg2 == "function") {
81
+ testFunction = arg2
82
+ testArgs = arg1
83
+ } else {
84
+ throw new Error(`Invalid arguments for it: ${description}, ${arg1}`)
85
+ }
86
+
87
+ const newTestArgs = Object.assign({}, currentTest.args, testArgs)
88
+
89
+ currentTest.tests[description] = {args: newTestArgs, function: testFunction}
90
+ }
91
+
92
+ export {describe, expect, it, tests}
@@ -1,19 +0,0 @@
1
- export default class TestRunner {
2
- constructor(testFiles) {
3
- this.testFiles = testFiles
4
- }
5
-
6
- async importTestFiles() {
7
- for (const testFile of this.testFiles) {
8
- const importTestFile = await import(testFile)
9
- }
10
- }
11
-
12
- async run() {
13
- await this.importTestFiles()
14
-
15
- console.log({foundTestFiles: this.testFiles})
16
-
17
- throw new Error("stub")
18
- }
19
- }