codehooks-js 1.1.11 → 1.2.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.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # codehooks-js
2
2
 
3
- Codehooks.io official helper library - provides Express.JS-like syntax for using codehooks.io (and more).
3
+ Codehooks.io official development library - provides Express.JS-like syntax for using codehooks.io.
4
4
 
5
5
  Read the [Quickstart for developers](https://codehooks.io/docs/quickstart-cli).
6
6
 
@@ -8,15 +8,22 @@ For more details navigate to official docs: [https://codehooks.io/docs](https://
8
8
 
9
9
  ## Install
10
10
 
11
+ Install the [Codehooks CLI](https://codehooks.io/docs/cli):
12
+
13
+ ```shell
14
+ $ npm install -g codehooks
15
+ ```
16
+ Next install the codehooks-js NPM package in your project.
17
+
11
18
  ```shell
12
- npm install codehooks-js -s
19
+ npm install codehooks-js
13
20
  ```
14
21
 
15
- ## Usage
22
+ ## JavaScript ES6 development
16
23
 
17
24
  Example code for a serverless backend API and NoSQL database:
18
25
 
19
- ```
26
+ ```javascript
20
27
  /*
21
28
  * REST API with NoSQL database storage.
22
29
  * Codehooks (c) example code.
@@ -42,13 +49,76 @@ app.crudlify({}, {prefix: "/"})
42
49
  export default app.init()
43
50
  ```
44
51
 
45
- ## Deploy
52
+ ## TypeScript development
53
+
54
+ Rename the index.js to index.ts or create a new index.ts file.
55
+ Start developing using TypeScript and strong types shown in the example code below.
56
+
57
+ ```typescript
58
+ /*
59
+ * REST API with NoSQL database storage.
60
+ * Codehooks (c) example code in TypeScript.
61
+ */
62
+
63
+ import {app, datastore, httpResponse, httpRequest} from 'codehooks-js';
64
+
65
+ // Example GET route and a NoSQL database insert operation
66
+ app.get('/myroute', async (req: httpRequest, res: httpResponse) => {
67
+ console.log("GET")
68
+ const conn = await datastore.open()
69
+ const doc = await conn.insertOne('greetings', {"message": "Hello World!", "when": new Date()})
70
+ res.json({...doc})
71
+ });
72
+
73
+ // Serve web content from the uploaded directory /static
74
+ app.static({directory: "/static"})
75
+
76
+ // CRUD REST API for any collection
77
+ app.crudlify({}, {prefix: "/"})
78
+
79
+ // return app to serverless runtime engine
80
+ export default app.init()
81
+ ```
82
+
83
+ ## Compile
84
+
85
+ When running the `coho compile` command, it will automatically create a `tsconfig.json` file in the project directory. The tsconfig file can be further adapted to your needs, the initial configuration is shown in the example below:
86
+
87
+ ```json
88
+ {
89
+ "files": [
90
+ "./index.ts"
91
+ ],
92
+ "compilerOptions": {
93
+ "allowJs": true,
94
+ "lib": [
95
+ "ES6",
96
+ "dom"
97
+ ]
98
+ }
99
+ }
100
+ ```
101
+
102
+ Any syntax or type error will be displayed accordingly from the compile command, for example:
46
103
 
47
- Install the [Codehooks CLI](https://codehooks.io/docs/cli):
48
104
  ```shell
49
- $ npm install -g codehooks
105
+ $ coho compile
106
+
107
+ 🤔 [tsl] ERROR in /Users/jane/projects/tsdemo/index.ts(9,9)
108
+ TS2345: Argument of type '(req: httpRequest, res: httpResponse) => void' is not assignable to parameter of type 'string'.
50
109
  ```
51
110
 
111
+ Correcting the errors should ultimately show a successfull compile output, ready for deployment of your backend app.
112
+
113
+ ```shell
114
+ $ coho compile
115
+
116
+ OK 🙌
117
+
118
+ ```
119
+
120
+ ## Deploy
121
+
52
122
  From the project directory run:
53
123
  ```shell
54
124
  $ codehooks deploy
@@ -1,10 +1,17 @@
1
1
  import lodash from 'lodash';
2
+ /**
3
+ * Persistent NoSql and Kev-Value datastore
4
+ * @typedef {Object} DataStream
5
+ * @property {function(string, function(*)):void} on - Emits data, stream.on('data', (data) => //console.debug(data))
6
+ * @property {function(httpResponse):void} json - Pipe datastream to JSON output
7
+ * @property {function():Promise.<object[]>} toArray - Return an array of objects
8
+ */
2
9
 
3
10
  /**
4
11
  *
5
- * @param {ReadableStream} readable - JSON stream
12
+ * @param {DataStream} readable - JSON stream
6
13
  * @param {Object} spec - JSON aggregation spec
7
- * @returns Promise with aggregation result
14
+ * @returns {Promise} with aggregation result
8
15
  * @example
9
16
  * Spec JSON example:
10
17
  * {
package/index.js CHANGED
@@ -13,32 +13,6 @@ function createRoute(str) {
13
13
  }
14
14
 
15
15
 
16
- /**
17
- * getMany options for query filtering, indexes and projections
18
- * @typedef {Object} getManyOptions
19
- * @property {Object} filter - MongoDB query filter. (Read query language docs)
20
- * @property {string} useIndex - indexed field name.
21
- - Indexes are created with CLI, e.g. coho createindex -c sales -i Region
22
- * @property {string} startIndex - jump into the index
23
- * @property {string} endIndex - where to end in the index
24
- * @property {number} limit - how many items to return
25
- * @property {Object} hints - include or omit fields.
26
- - Include fields example: {$fields: {name: 1, address: 1}.
27
- - Omit fields example: {$fields: {name: 0, _id_: 0}}
28
- * @property {number} offset - how many items to skip before returning any
29
- * @property {boolean} reverse - reverese scan of index, i.e. descending sort
30
- */
31
-
32
- /**
33
- * updateMany options
34
- * @typedef {Object} updateOptions
35
- * @property {Object} filter - MongoDB query filter. (Read query language docs)
36
- * @property {string} useIndex - indexed field name. Indexes are created with CLI,
37
- - e.g. coho createindex -c sales -i Region
38
- * @property {string} startIndex - jump into the index
39
- * @property {string} endIndex - where to end in the index
40
- */
41
-
42
16
  /**
43
17
  * keyvalOptions
44
18
  * @typedef {Object} keyvalOptions
@@ -49,49 +23,55 @@ function createRoute(str) {
49
23
  /**
50
24
  * NoSQL API
51
25
  * @typedef {Object} NoSQLAPI
52
- * @property {function(objectID.<string|Array.<string>):Promise.<Object>} getOne - Get object by ID, returns a Promise with the object
53
- * @property {function(getManyOptions):DataStream} getMany - Get stream of objects by query
54
- * @property {function(getManyOptions):DataStream} find - Get stream of objects by query, alias for getMany
55
- * @property {function(json.<object>):Promise.<Object>} insertOne - Insert a new data object into a collection in the current Datastore
56
- * @property {function(objectID.<string>, document.<Object>):Promise.<Object>} updateOne - Update one data object by ID in a datastore collection.
26
+ * @see https://codehooks.io/docs/nosql-database-api
27
+ * @property {function(string|object):Promise.<object>} getOne - Get object by ID, returns a Promise with the object
28
+ * @property {function(object, object):DataStream} getMany - Get stream of objects by query
29
+ * @property {function(object, object):DataStream} find - Get stream of objects by query, alias for getMany
30
+ * @property {function(object):Promise.<object>} insertOne - Insert a new data object into a collection in the current Datastore
31
+ * @property {function(string|object, object):Promise.<object>} updateOne - Update one data object by ID in a datastore collection.
57
32
  * - Input document is patched with the matched database object
58
- * @property {function(document.<Object>, updateOptions):Promise.<Object>} updateMany - Update multiple data objects in a datastore collection.
33
+ * @property {function(object, object):Promise.<object>} updateMany - Update multiple data objects in a datastore collection.
59
34
  * - Input document is patched with the matched database objects
60
- * @property {function(objectID.<string>, document.<Object>):Promise.<Object>} replaceOne - Replace one data object by ID in a datastore collection.
35
+ * @property {function(string|object, object):Promise.<object>} replaceOne - Replace one data object by ID in a datastore collection.
61
36
  * - Input document overwrites the matched database object, the _id value is not overwritten.
62
- * @property {function(document.<Object>, updateOptions):Promise.<Object>} replaceMany - Replace multiple data objects in a datastore collection.
37
+ * @property {function(object, object):Promise.<object>} replaceMany - Replace multiple data objects in a datastore collection.
63
38
  * - Input document overwrites the matched database objects. The _id value is not overwritten
64
- * @property {function(objectID.<string>):Promise.<Object>} removeOne - Remove one data object by ID in a collection in the current Datastore
65
- * @property {function(updateOptions):Promise.<Object>} removeMany - Remove multiple data objects in a collection in the current Datastore
39
+ * @property {function(string|object):Promise.<object>} removeOne - Remove one data object by ID in a collection in the current Datastore
40
+ * @property {function(object):Promise.<object>} removeMany - Remove multiple data objects in a collection in the current Datastore
66
41
  */
67
42
 
68
43
  /**
69
44
  * Database API
70
45
  * @typedef {Object} DatastoreAPI
71
- * @property {function(collection.<string>):NoSQLAPI} collection - Get database collection by string name, returns an NoSQL API object
72
- * @property {function(collection.<string>, objectID.<string|Array.<string>):Promise.<Object>} getOne - Get object by ID, returns a Promise with the object
73
- * @property {function(collection, getManyOptions):DataStream} getMany - Get stream of objects by query
74
- * @property {function(collection.<string>, json.<object>):Promise.<Object>} insertOne - Insert a new data object into a collection in the current Datastore
75
- * @property {function(collection.<string>, objectID.<string>, document.<Object>):Promise.<Object>} updateOne - Update one data object by ID in a datastore collection.
46
+ * @see https://codehooks.io/docs/nosql-database-api
47
+ * @see https://codehooks.io/docs/key-value-database-api
48
+ * @property {function(string):NoSQLAPI} collection - Get database collection by string name, returns an NoSQL API object
49
+ * @property {function(string, string|object):Promise.<object>} getOne - Get object by Query or ObjectID, returns a Promise with the object
50
+ * @property {function(string, object, object):DataStream} getMany - Get stream of objects by query
51
+ * - @see https://codehooks.io/docs/nosql-database-api#getmanycollection-query-options
52
+ * @property {function(string, object, object):DataStream} find - Alias for getMany
53
+ * - @see https://codehooks.io/docs/nosql-database-api#getmanycollection-query-options
54
+ * @property {function(string, object):Promise.<object>} insertOne - Insert a new data object into a collection in the current Datastore
55
+ * @property {function(string, string, object):Promise.<object>} updateOne - Update one data object by ID in a datastore collection.
76
56
  * - Input document is patched with the matched database object
77
- * @property {function(collection.<string>, document.<Object>, updateOptions):Promise.<Object>} updateMany - Update multiple data objects in a datastore collection.
57
+ * @property {function(string, object, object):Promise.<object>} updateMany - Update multiple data objects in a datastore collection.
78
58
  * - Input document is patched with the matched database objects
79
- * @property {function(collection.<string>, objectID.<string>, document.<Object>):Promise.<Object>} replaceOne - Replace one data object by ID in a datastore collection.
59
+ * @property {function(string, string, object):Promise.<object>} replaceOne - Replace one data object by ID in a datastore collection.
80
60
  * - Input document overwrites the matched database object, the _id value is not overwritten.
81
- * @property {function(collection.<string>, document.<Object>, updateOptions):Promise.<Object>} replaceMany - Replace multiple data objects in a datastore collection.
61
+ * @property {function(string, object, object):Promise.<object>} replaceMany - Replace multiple data objects in a datastore collection.
82
62
  * - Input document overwrites the matched database objects. The _id value is not overwritten
83
- * @property {function(collection.<string>, objectID.<string>):Promise.<Object>} removeOne - Remove one data object by ID in a collection in the current Datastore
84
- * @property {function(collection.<string>, updateOptions):Promise.<Object>} removeMany - Remove multiple data objects in a collection in the current Datastore
85
- * @property {function(key.<string>, value<string>, keyvalOptions):Promise.<Object>} set - Set a key-value pair in the current Datastore
86
- * @property {function(key.<string>, keyvalOptions):Promise.<Object>} get - Get a key-value pair in the current Datastore
87
- * @property {function(keypattern.<string>, keyvalOptions):DataStream} getAll - Get all key-value pair that matches keypattern in the current Datastore
88
- * @property {function(key.<string>, number, keyvalOptions):Promise.<Object>} incr - Increment a key-value pair in the current Datastore
89
- * @property {function(key.<string>, number, keyvalOptions):Promise.<Object>} decr - Decrement a key-value pair in the current Datastore
90
- * @property {function(key.<string>, keyvalOptions):Promise.<Object>} del - Delete a key-value pair in the current Datastore
91
- * @property {function(keypattern.<string>, keyvalOptions):Promise.<Object>} delAll - Delete a range of key-value pairs in the current Datastore
92
- * @property {function(topic.<string>, payload.<Object>, options.<Object>):Promise.<Object>} enqueue - Add a queued job in a datastore.
63
+ * @property {function(string, string):Promise.<object>} removeOne - Remove one data object by ID in a collection in the current Datastore
64
+ * @property {function(string, object):Promise.<object>} removeMany - Remove multiple data objects in a collection in the current Datastore
65
+ * @property {function(string, string, object):Promise.<object>} set - Set a key-value pair in the current Datastore
66
+ * @property {function(string, object):Promise.<object>} get - Get a key-value pair in the current Datastore
67
+ * @property {function(string, object):DataStream} getAll - Get all key-value pair that matches keypattern in the current Datastore
68
+ * @property {function(string, number, object):Promise.<object>} incr - Increment a key-value pair in the current Datastore
69
+ * @property {function(string, number, object):Promise.<object>} decr - Decrement a key-value pair in the current Datastore
70
+ * @property {function(string, object):Promise.<object>} del - Delete a key-value pair in the current Datastore
71
+ * @property {function(string, object):Promise.<object>} delAll - Delete a range of key-value pairs in the current Datastore
72
+ * @property {function(string, object, object):Promise.<object>} enqueue - Add a queued job in a datastore.
93
73
  * - Jobs in the queue are processed by your worker function.
94
- * @property {function(collection.<string>, query.<Object>, topic.<string>, payload.<Object>, options.<Object>):Promise.<Object>} enqueueFromQuery - Add multiple queued jobs from the result of a database query in a datastore.
74
+ * @property {function(string, object, string, object):Promise.<object>} enqueueFromQuery - Add multiple queued jobs from the result of a database query in a datastore.
95
75
  * - Each object from the collection in the query result will be processed by your worker function.
96
76
  * - If your collection has 1000 items, a match all query ({}) will add 1000 items to the queue and call your worker function 1000 times.
97
77
  */
@@ -99,8 +79,10 @@ function createRoute(str) {
99
79
  /**
100
80
  * Persistent NoSql and Kev-Value datastore
101
81
  * @typedef {Object} DataStream
102
- * @property {function("data"|"end"|"error", callback.<Function>):DataStream} on - Emits data, stream.on('data', (data) => //console.debug(data))
103
- * @property {function(httpResponse)} json - Pipe datastream to JSON output
82
+ * @property {function(string, function(*)):void} on - Emits data, stream.on('data', (data) => //console.debug(data))
83
+ * @property {function(httpResponse):void} json - Pipe datastream to JSON output
84
+ * @property {function():Promise.<object[]>} toArray - Return an array of objects
85
+ * @property {function(function(object):void):Promise.<object[]>} forEach - Return an iterator with objects
104
86
  */
105
87
 
106
88
  /**
@@ -112,30 +94,56 @@ function createRoute(str) {
112
94
 
113
95
  /**
114
96
  * @typedef {Object} httpRequest
115
- * @property {object} headers - HTTP header key value pairs, e.g. req.headers['content-type']
116
- * @property {object} query - Get the URL query parameters as key-value pairs
117
- * @property {object} params - Get the URL route variables as key-value pairs
118
- * @property {object} body - Get the request body
119
- * @property {object} path - Get the URL full path, e.g. /dev/myroute
120
- * @property {object} apiPath - Get the URL api path, e.g. /myroute
121
- * @property {object} originalUrl - Get the URL full path and query parameter string
122
- * @property {object} method - Get the HTTP request verb
123
- * @property {object} hostname - Get the project URL domain name
97
+ * @property {*} headers - HTTP header key value pairs, e.g. req.headers['content-type']
98
+ * @property {*} query - Get the URL query parameters as key-value pairs
99
+ * @property {*} params - Get the URL route variables as key-value pairs
100
+ * @property {*} body - Get the request body
101
+ * - JSON payload
102
+ * @property {string} path - Get the URL full path, e.g. /dev/myroute
103
+ * @property {string} apiPath - Get the URL api path, e.g. /myroute
104
+ * @property {string} originalUrl - Get the URL full path and query parameter string
105
+ * @property {string} method - Get the HTTP request verb
106
+ * @property {string} hostname - Get the project URL domain name
124
107
  */
125
108
 
109
+
126
110
  /**
127
111
  * @typedef {Object} httpResponse
128
- * @property {function(data.<string>)} end - End request (optional: send text data to client)
129
- * * @property {function(data.<string>)} send - Send text data to client and end request
130
- * @property {function(data.<json>)} json - End request and send JSON data to client
131
- * @property {function(data.<string>)} write - Write stream data to the client response.
112
+ * @property {function(string|object|void): void} end - End request (optional: send text|JSON data to client)
113
+ * @property {function(string|object): void} send - Send text|JSON data to client and end request
114
+ * @property {function(object)} json - End request and send JSON data to client
115
+ * @property {function(string)} write - Write stream data to the client response.
132
116
  * - Content-type must be set before any write operations
133
- * @property {function(header.<string>, value.<string>)} set - Set a response header value,
117
+ * @property {function(string, string)} set - Set a response header value,
134
118
  * - e.g. res.set('Content-Type', 'text/html; charset=UTF-8');
135
- * @property {function(headers.<json>)} headers - Set multiple response header values,
119
+ * @property {function(object)} headers - Set multiple response header values,
136
120
  * - e.g. res.headers({'Content-Type': 'text/html; charset=UTF-8','X-myheader': '123456890'});
137
- * @property {function(HttpStatusCode.<number>)} status - Return a HTTP response status code for a client request,
121
+ * @property {function(number)} status - Return a HTTP response status code for a client request,
138
122
  * - e.g. res.status(401);
123
+ * @property {function(string, object):void} render - Render template with object data
124
+ * - example: res.render('services', {title: "Services page"})
125
+ */
126
+
127
+ /**
128
+ * @typedef {Object} Filesystem
129
+ *
130
+ * @property {function(string, Object): Promise<ReadableStream>} getReadStream
131
+ * - Get binary file input stream. Takes a path (string) to file (e.g. /static/logo.png) and an options object (Object) for future use. Returns a Promise resolving to a binary data stream emitter.
132
+ *
133
+ * @property {function(string, Object): Promise<string>} readFile
134
+ * - Get file as text. Takes an absolute path (string) to file (e.g. /static/home.html) and an options object (Object) for future use. Returns a Promise resolving to the file content (string).
135
+ *
136
+ * @property {function(string, Buffer, Object): Promise<any>} saveFile
137
+ * - Save file binary buffer. Takes an absolute path (string) to file (e.g. /static/home.html), a buffer (Buffer) to save, and file meta data (Object). Returns a Promise resolving to the save result.
138
+ *
139
+ * @property {function(string, Object): Promise<any>} deleteFile
140
+ * - Delete a file. Takes an absolute path (string) to file and an options object (Object) for future use. Returns a Promise resolving to the result.
141
+ *
142
+ * @property {function(string, Object): Promise<any>} list
143
+ * - List content of a file directory. Takes an absolute path (string) to file and an options object (Object) for future use. Returns a Promise resolving to the result.
144
+ *
145
+ * @property {function(*): Promise<Buffer>} readFileAsBuffer
146
+ * - Read file into a Buffer. Takes an absolute path (*) to file. Returns a Promise resolving to a Buffer.
139
147
  */
140
148
 
141
149
 
@@ -161,7 +169,7 @@ class Codehooks {
161
169
  * res.json({"message": "thanks!"})
162
170
  * })
163
171
  * @param {string} path - API route, e.g. '/foo'
164
- * @param {...function(httpRequest, httpResponse)} hook - callback function(s) with parameters (req, res, [next])
172
+ * @param {...function(httpRequest, httpResponse, function(string):void)} hook - callback function(s) with parameters (req, res, [next])
165
173
  */
166
174
  post = (path, ...hook) => {
167
175
  this.routes[`POST ${createRoute(path)}`] = hook;
@@ -175,7 +183,7 @@ class Codehooks {
175
183
  * res.json({"message": "thanks!"})
176
184
  * })
177
185
  * @param {string} path - API route, e.g. '/foo/:ID'
178
- * @param {...function(httpRequest, httpResponse)} hook - callback function(s) with parameters (req, res, [next])
186
+ * @param {...function(httpRequest, httpResponse, function(string):void)} hook - callback function(s) with parameters (req, res, [next])
179
187
  */
180
188
  get = (path, ...hook) => {
181
189
  this.routes[`GET ${createRoute(path)}`] = hook;
@@ -189,7 +197,7 @@ class Codehooks {
189
197
  * res.json({"message": "thanks!"})
190
198
  * })
191
199
  * @param {string} path - API route, e.g. '/foo/:ID'
192
- * @param {...function(httpRequest, httpResponse)} hook - callback function(s) with parameters (req, res, [next])
200
+ * @param {...function(httpRequest, httpResponse, function(string):void):void} hook - callback function(s) with parameters (req, res, [next])
193
201
  */
194
202
  put = (path, ...hook) => {
195
203
  this.routes[`PUT ${createRoute(path)}`] = hook;
@@ -203,7 +211,7 @@ class Codehooks {
203
211
  * res.json({"message": "thanks!"})
204
212
  * })
205
213
  * @param {string} path - API route, e.g. '/foo/:ID'
206
- * @param {...function(httpRequest, httpResponse)} hook - callback function(s) with parameters (req, res, [next])
214
+ * @param {...function(httpRequest, httpResponse, function(string):void)} hook - callback function(s) with parameters (req, res, [next])
207
215
  */
208
216
  patch = (path, ...hook) => {
209
217
  this.routes[`PATCH ${createRoute(path)}`] = hook;
@@ -216,7 +224,7 @@ class Codehooks {
216
224
  * res.json({"message": "thanks!"})
217
225
  * })
218
226
  * @param {string} path - API route, e.g. '/foo/:ID'
219
- * @param {...function(httpRequest, httpResponse)} hook - callback function(s) with parameters (req, res, [next])
227
+ * @param {...function(httpRequest, httpResponse, function(string):void)} hook - callback function(s) with parameters (req, res, [next])
220
228
  */
221
229
  delete = (path, ...hook) => {
222
230
  this.routes[`DELETE ${createRoute(path)}`] = hook;
@@ -230,7 +238,7 @@ class Codehooks {
230
238
  * res.json({"message": "thanks!"})
231
239
  * })
232
240
  * @param {string} path - API route, e.g. '- API endpoint route, e.g. '/pets'
233
- * @param {...function(httpRequest, httpResponse)} hook - callback function(s) with parameters (req, res, [next])
241
+ * @param {...function(httpRequest, httpResponse, function(string)):void} hook - callback function(s) with parameters (req, res, [next])
234
242
  */
235
243
  all = (path, ...hook) => {
236
244
  this.routes[`* ${createRoute(path)}`] = hook;
@@ -246,8 +254,8 @@ class Codehooks {
246
254
  * res.status(403).end('No soup!')
247
255
  * }
248
256
  * })
249
- * @param {string} path - API route, e.g. '/foo/*'
250
- * @param {...function(httpRequest, httpResponse)} hook - callback function(s) with parameters (req, res, [next])
257
+ * @param {string|RegExp} path - API route, e.g. '/foo/*'
258
+ * @param {...function(httpRequest, httpResponse, function(string):void):void} hook - callback function(s) with parameters (req, res, [next])
251
259
  */
252
260
  auth = (path, ...hook) => {
253
261
  this.auths[createRoute(path)] = hook;
@@ -262,12 +270,12 @@ class Codehooks {
262
270
  * next(); // proceed
263
271
  * })
264
272
  * // middleware on a specific route
265
- * app.use('/myroute', (req, res, next) => {
273
+ * app.useRoute('/myroute', (req, res, next) => {
266
274
  * //console.debug("Route middleware was here!");
267
275
  * next(); // proceed
268
276
  * })
269
277
  * @param {string} path - Optional API route, e.g. '/myroute/*'
270
- * @param {...function(httpRequest, httpResponse, next.<function>)} hook - callback function(s) with parameters (req, res, next)
278
+ * @param {...function(httpRequest, httpResponse, function(string):void):void} hook - callback function(s) with parameters (req, res, next)
271
279
  */
272
280
  use = (...hook) => {
273
281
  if ((typeof hook[0] === 'string')) {
@@ -281,10 +289,30 @@ class Codehooks {
281
289
  this.appmiddleware = this.appmiddleware.flat();
282
290
  };
283
291
 
292
+ /**
293
+ * Global route middleware
294
+ * @example
295
+ * // Global middleware on a specific route
296
+ * app.useRoute('/myroute', (req, res, next) => {
297
+ * //console.debug("Route middleware was here!");
298
+ * next(); // proceed
299
+ * })
300
+ * @param {string|RegExp} path - Optional API route, e.g. '/myroute/*'
301
+ * @param {...function(httpRequest, httpResponse, function(string):void):void} hook - callback function(s) with parameters (req, res, next)
302
+ */
303
+ useRoute = (route, ...hook) => {
304
+ if ((typeof route === 'string')) {
305
+ this.appmiddleware.push({ path: route, func: hook[0]});
306
+ } else if ((route instanceof RegExp)) {
307
+ this.appmiddleware.push({ regex: JSON.stringify({$regex: route.toString()}), func: hook[0]});
308
+ }
309
+ this.appmiddleware = this.appmiddleware.flat();
310
+ };
311
+
284
312
  /**
285
313
  * Process queue job items for topic
286
314
  * @param {string} topic
287
- * @param {...function(httpRequest, httpResponse)} hook - callback function(s) with parameters (req, res, [next])
315
+ * @param {...function(httpRequest, httpResponse, function(string):void)} hook - callback function(s) with parameters (req, res, [next])
288
316
  */
289
317
  queue = (topic, ...hook) => {
290
318
  this.queues[topic] = hook;
@@ -293,7 +321,7 @@ class Codehooks {
293
321
  /**
294
322
  * Add application worker function
295
323
  * @param {string} name a unique worker name
296
- * @param {...function(httpRequest, httpResponse)} hook - callback function(s) with parameters (req, res, [next])
324
+ * @param {...function(httpRequest, httpResponse, function(string):void)} hook - callback function(s) with parameters (req, res, [next])
297
325
  * @example
298
326
  * app.worker('myworker', (data, job) => {
299
327
  * const {body:{payload}} = data
@@ -316,7 +344,7 @@ class Codehooks {
316
344
  * res.end()
317
345
  * })
318
346
  * @param {string} cronExpression - cron expression
319
- * @param {...function(httpRequest, httpResponse)} hook - callback function(s) with parameters (req, res, [next])
347
+ * @param {...function(httpRequest, httpResponse, function(string):void)} hook - callback function(s) with parameters (req, res, [next])
320
348
  */
321
349
  job = (cronExpression, ...hook) => {
322
350
  this.jobs[cronExpression] = hook;
@@ -337,12 +365,18 @@ class Codehooks {
337
365
  * @param {*} val
338
366
  * @example
339
367
  * app.set('views', '/views')
340
- * app.set('view engine', 'handlebars')
368
+ * app.set('view engine', {"hbs": handlebars})
341
369
  */
342
370
  set = (key, val) => {
343
371
  this.settings[key] = val;
344
372
  }
345
373
 
374
+ /**
375
+ *
376
+ * @param {string} view
377
+ * @param {object} data
378
+ * @param {function(string):void)} cb
379
+ */
346
380
  render = async (view, data, cb) => {
347
381
  renderView(view, data, this.settings, cb)
348
382
  /*
@@ -353,11 +387,11 @@ class Codehooks {
353
387
 
354
388
  /**
355
389
  * @description Create CRUD REST API for database
356
- * @param {*} schema
357
- * @param {*} options
390
+ * @param {object} schema
391
+ * @param {object} options
358
392
  * @returns Eventhooks - Promise
359
393
  */
360
- crudlify = (schema, options) => {
394
+ crudlify = (schema={}, options={}) => {
361
395
  return crud(Codehooks.getInstance(), schema, options);
362
396
  }
363
397
 
@@ -365,7 +399,7 @@ class Codehooks {
365
399
  * Returns the Codehooks serverless definitions used by a serverless runtime engine
366
400
  * @example
367
401
  * export default app.init();
368
- * @returns {Object} App instance manifest
402
+ * @returns {Object} App instance
369
403
  */
370
404
  init = () => {
371
405
  const manifest = {
@@ -521,6 +555,7 @@ export const coderunner = coderun;
521
555
  */
522
556
  export const schedule = {
523
557
  /**
558
+ * @async
524
559
  * Call worker function later
525
560
  * @param {Date} datetime to execute
526
561
  * @param {Object} payload data
@@ -537,6 +572,7 @@ export const schedule = {
537
572
  return await conn.runAt(date, payload, worker)
538
573
  },
539
574
  /**
575
+ * @async
540
576
  * Call worker function immediate
541
577
  * @param {Object} payload to worker function
542
578
  * @param {string} worker name
@@ -551,7 +587,7 @@ export const schedule = {
551
587
  }
552
588
 
553
589
  /**
554
- * @description API to access deployed static files
590
+ * @description Virtual filestore
555
591
  */
556
592
  const _filestore = {
557
593
  /**
@@ -576,7 +612,7 @@ const _filestore = {
576
612
  return _coho_fs.getFileStream(path, options);
577
613
  },
578
614
  /**
579
- * Get file as text
615
+ * readFile - Get file as text
580
616
  * @param {string} path Absolute path to file, e.g. /static/home.html
581
617
  * @param {Object} options For future use
582
618
  * @returns Promise with file content
package/package.json CHANGED
@@ -1,9 +1,10 @@
1
1
  {
2
2
  "name": "codehooks-js",
3
- "version": "1.1.11",
3
+ "version": "1.2.0",
4
4
  "type": "module",
5
5
  "description": "Codehooks.io official library - provides express.JS like syntax",
6
6
  "main": "index.js",
7
+ "types": "./types",
7
8
  "files": [
8
9
  "index.js",
9
10
  "coderunner.mjs",
@@ -16,7 +17,9 @@
16
17
  "./crudlify/lib/query/q2m/q2m.mjs",
17
18
  "./crudlify/lib/schema/yup/index.mjs",
18
19
  "./crudlify/lib/schema/json-schema/index.mjs",
19
- "./crudlify/lib/schema/zod/index.mjs"
20
+ "./crudlify/lib/schema/zod/index.mjs",
21
+ "./types",
22
+ "tsconfig.json"
20
23
  ],
21
24
  "scripts": {
22
25
  "test": "echo \"Warning: no tests specified\""
package/tsconfig.json ADDED
@@ -0,0 +1,22 @@
1
+ {
2
+ // Change this to match your project
3
+ "include": ["**/*"],
4
+ "exclude": ["node_modules/**"],
5
+ "compilerOptions": {
6
+ // Tells TypeScript to read JS files, as
7
+ // normally they are ignored as source files
8
+ "allowJs": true,
9
+ // Generate d.ts files
10
+ "declaration": true,
11
+ // This compiler run should
12
+ // only output d.ts files
13
+ "emitDeclarationOnly": true,
14
+ // Types should go into this directory.
15
+ // Removing this would place the .d.ts files
16
+ // next to the .js files
17
+ "outDir": "dist",
18
+ // go to js file when using IDE functions like
19
+ // "Go to Definition" in VSCode
20
+ "declarationMap": true
21
+ }
22
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Persistent NoSql and Kev-Value datastore
3
+ * @typedef {Object} DataStream
4
+ * @property {function(string, function(*)):void} on - Emits data, stream.on('data', (data) => //console.debug(data))
5
+ * @property {function(httpResponse):void} json - Pipe datastream to JSON output
6
+ * @property {function():Promise.<object[]>} toArray - Return an array of objects
7
+ */
8
+ /**
9
+ *
10
+ * @param {DataStream} readable - JSON stream
11
+ * @param {Object} spec - JSON aggregation spec
12
+ * @returns {Promise} with aggregation result
13
+ * @example
14
+ * Spec JSON example:
15
+ * {
16
+ * "$max": {$field: "open", $label: "Open"},
17
+ "$group": {
18
+ "$field": "Ticker",
19
+ $label: "Symbol",
20
+ "$max": "high",
21
+ "$min": {$field: "close", $label: "Low"}
22
+ }
23
+ }
24
+ */
25
+ export function agg(readable: DataStream, spec: any): Promise<any>;
26
+ /**
27
+ * Persistent NoSql and Kev-Value datastore
28
+ */
29
+ export type DataStream = {
30
+ /**
31
+ * - Emits data, stream.on('data', (data) => //console.debug(data))
32
+ */
33
+ on: (arg0: string, arg1: (arg0: any) => any) => void;
34
+ /**
35
+ * - Pipe datastream to JSON output
36
+ */
37
+ json: (arg0: httpResponse) => void;
38
+ /**
39
+ * - Return an array of objects
40
+ */
41
+ toArray: () => Promise<object[]>;
42
+ };
43
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../../aggregation/index.mjs"],"names":[],"mappings":"AACA;;;;;;EAME;AAEF;;;;;;;;;;;;;;;;GAgBG;AACH,8BAfW,UAAU,2BAsCpB;;;;;;;;eA7CqB,MAAM,+BAAe,IAAI;;;;kCACX,IAAI;;;;mBAChB,QAAS,MAAM,EAAE,CAAC"}
@@ -0,0 +1,2 @@
1
+ export default function execAll(funcarr: any, context: any, callfuncs: any, nextfunc: any): void;
2
+ //# sourceMappingURL=coderunner.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"coderunner.d.mts","sourceRoot":"","sources":["../coderunner.mjs"],"names":[],"mappings":"AAAA,iGAqBC"}
@@ -0,0 +1,2 @@
1
+ export default function run(cronexpr: any, theFunc: any): void;
2
+ //# sourceMappingURL=cronjob.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cronjob.d.mts","sourceRoot":"","sources":["../cronjob.mjs"],"names":[],"mappings":"AAMA,+DA6BC"}