te.js 1.2.0 → 1.2.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.
@@ -1,11 +1,10 @@
1
- import { Target } from 'te.js';
2
-
3
- const target = new Target();
4
-
5
- target.register('/hello', (ammo) => {
6
- throw new Error('Error thrown to demonstrate robust error handling of te.js');
7
- ammo.fire({
8
- status: 200,
9
- body: 'Hello, World!'
10
- });
11
- });
1
+ import { Target, listAllEndpoints } from 'te.js';
2
+
3
+ const target = new Target();
4
+
5
+ target.register('/', (ammo) => {
6
+ ammo.fire({
7
+ status: 200,
8
+ body: listAllEndpoints(true),
9
+ });
10
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "te.js",
3
- "version": "1.2.0",
3
+ "version": "1.2.1",
4
4
  "description": "A nodejs framework",
5
5
  "type": "module",
6
6
  "main": "te.js",
@@ -1,44 +1,55 @@
1
- import isMiddlewareValid from './middleware-validator.js';
2
-
3
- class TargetRegistry {
4
- constructor() {
5
- if (TargetRegistry.instance) {
6
- return TargetRegistry.instance;
7
- }
8
-
9
- TargetRegistry.instance = this;
10
-
11
- // TODO - Add a default target
12
- this.targets = [];
13
- this.globalMiddlewares = [];
14
- }
15
-
16
- addGlobalMiddleware() {
17
- if (!arguments) return;
18
-
19
- const middlewares = [...arguments];
20
- const validMiddlewares = middlewares.filter(isMiddlewareValid);
21
- this.globalMiddlewares = this.globalMiddlewares.concat(validMiddlewares);
22
- }
23
-
24
- /**
25
- * @param {Array || Object} targets
26
- */
27
- register(targets) {
28
- if (Array.isArray(targets)) {
29
- this.targets = this.targets.concat(targets);
30
- } else {
31
- this.targets.push(targets);
32
- }
33
- }
34
-
35
- aim(method, endpoint) {
36
- return this.targets.find((target) => {
37
- return (
38
- target.endpoint === endpoint
39
- );
40
- });
41
- }
42
- }
43
-
44
- export default TargetRegistry;
1
+ import isMiddlewareValid from './middleware-validator.js';
2
+
3
+ class TargetRegistry {
4
+ constructor() {
5
+ if (TargetRegistry.instance) {
6
+ return TargetRegistry.instance;
7
+ }
8
+
9
+ TargetRegistry.instance = this;
10
+
11
+ // TODO - Add a default target
12
+ this.targets = [];
13
+ this.globalMiddlewares = [];
14
+ }
15
+
16
+ addGlobalMiddleware() {
17
+ if (!arguments) return;
18
+
19
+ const middlewares = [...arguments];
20
+ const validMiddlewares = middlewares.filter(isMiddlewareValid);
21
+ this.globalMiddlewares = this.globalMiddlewares.concat(validMiddlewares);
22
+ }
23
+
24
+ /**
25
+ * @param {Array || Object} targets
26
+ */
27
+ register(targets) {
28
+ if (Array.isArray(targets)) {
29
+ this.targets = this.targets.concat(targets);
30
+ } else {
31
+ this.targets.push(targets);
32
+ }
33
+ }
34
+
35
+ aim(method, endpoint) {
36
+ return this.targets.find((target) => {
37
+ return target.endpoint === endpoint;
38
+ });
39
+ }
40
+
41
+ getAllEndpoints(grouped) {
42
+ if (grouped) {
43
+ return this.targets.reduce((acc, target) => {
44
+ const group = target.endpoint.split('/')[1];
45
+ if (!acc[group]) acc[group] = [];
46
+ acc[group].push(target.endpoint);
47
+ return acc;
48
+ }, {});
49
+ } else {
50
+ return this.targets.map((target) => target.endpoint);
51
+ }
52
+ }
53
+ }
54
+
55
+ export default TargetRegistry;
package/te.js CHANGED
@@ -1,129 +1,135 @@
1
- import { createServer } from 'node:http';
2
-
3
- import { env, setEnv } from 'tej-env';
4
- import TejLogger from 'tej-logger';
5
- import database from './database/index.js';
6
-
7
- import TargetRegistry from './server/targets/registry.js';
8
-
9
- import { loadConfigFile, standardizeObj } from './utils/configuration.js';
10
-
11
- import targetHandler from './server/handler.js';
12
- import { findTargetFiles } from './utils/auto-register.js';
13
- import { pathToFileURL } from 'node:url';
14
-
15
- const logger = new TejLogger('Tejas');
16
- const targetRegistry = new TargetRegistry();
17
-
18
- class Tejas {
19
- /*
20
- * Constructor for Tejas
21
- * @param {Object} args - Arguments for Tejas
22
- * @param {Number} args.port - Port to run Tejas on
23
- * @param {Boolean} args.log.http_requests - Whether to log incoming HTTP requests
24
- * @param {Boolean} args.log.exceptions - Whether to log exceptions
25
- * @param {String} args.db.type - Database type. It can be 'mongodb', 'mysql', 'postgres', 'sqlite'
26
- * @param {String} args.db.uri - Connection URI string for the database
27
- */
28
- constructor(args) {
29
- if (Tejas.instance) return Tejas.instance;
30
- Tejas.instance = this;
31
-
32
- this.generateConfiguration(args);
33
- this.registerTargetsDir();
34
- }
35
-
36
- /*
37
- * Connect to a database
38
- * @param {Object}
39
- * @param {String} args.db - Database type. It can be 'mongodb', 'mysql', 'postgres', 'sqlite'
40
- * @param {String} args.uri - Connection URI string for the database
41
- * @param {Object} args.options - Options for the database connection
42
- */
43
- connectDatabase(args) {
44
- const db = env('DB_TYPE');
45
- const uri = env('DB_URI');
46
-
47
- if (!db) return;
48
- if (!uri) {
49
- logger.error(
50
- `Tejas could not connect to ${db} as it couldn't find a connection URI. See our documentation for more information.`,
51
- false,
52
- );
53
- return;
54
- }
55
-
56
- const connect = database[db];
57
- if (!connect) {
58
- logger.error(
59
- `Tejas could not connect to ${db} as it is not supported. See our documentation for more information.`,
60
- false,
61
- );
62
- return;
63
- }
64
-
65
- connect(uri, {}, (error) => {
66
- if (error) {
67
- logger.error(
68
- `Tejas could not connect to ${db}. Error: ${error}`,
69
- false,
70
- );
71
- return;
72
- }
73
-
74
- logger.info(`Tejas connected to ${db} successfully.`);
75
- });
76
- }
77
-
78
- generateConfiguration(options) {
79
- const configVars = standardizeObj(loadConfigFile());
80
- const envVars = standardizeObj(process.env);
81
- const userVars = standardizeObj(options);
82
-
83
- const config = { ...configVars, ...envVars, ...userVars };
84
- for (const key in config) {
85
- if (config.hasOwnProperty(key)) {
86
- setEnv(key, config[key]);
87
- }
88
- }
89
-
90
- // Load defaults
91
- if (!env('PORT')) setEnv('PORT', 1403);
92
- }
93
-
94
- midair() {
95
- if (!arguments) return;
96
- targetRegistry.addGlobalMiddleware(...arguments);
97
- }
98
-
99
- registerTargetsDir() {
100
- findTargetFiles().then((targetFiles) => {
101
- if (targetFiles) {
102
- for (const file of targetFiles) {
103
- import(pathToFileURL(`${file.path}/${file.name}`));
104
- }
105
- }
106
-
107
- }).catch((err) => {
108
- logger.error(
109
- `Tejas could not register target files. Error: ${err}`,
110
- false,
111
- );
112
- });
113
- }
114
-
115
- takeoff() {
116
- this.engine = createServer(targetHandler);
117
- this.engine.listen(env('PORT'), () => {
118
- logger.info(`Took off from port ${env('PORT')}`);
119
- this.connectDatabase();
120
- });
121
- }
122
- }
123
-
124
- export {default as Target} from './server/target.js';
125
- export {default as TejFileUploader} from './server/files/uploader.js';
126
- export default Tejas;
127
-
128
- // TODO Ability to register a target (route) from tejas instance
129
- // TODO tejas as CLI tool
1
+ import { createServer } from 'node:http';
2
+
3
+ import { env, setEnv } from 'tej-env';
4
+ import TejLogger from 'tej-logger';
5
+ import database from './database/index.js';
6
+
7
+ import TargetRegistry from './server/targets/registry.js';
8
+
9
+ import { loadConfigFile, standardizeObj } from './utils/configuration.js';
10
+
11
+ import targetHandler from './server/handler.js';
12
+ import { findTargetFiles } from './utils/auto-register.js';
13
+ import { pathToFileURL } from 'node:url';
14
+
15
+ const logger = new TejLogger('Tejas');
16
+ const targetRegistry = new TargetRegistry();
17
+
18
+ class Tejas {
19
+ /*
20
+ * Constructor for Tejas
21
+ * @param {Object} args - Arguments for Tejas
22
+ * @param {Number} args.port - Port to run Tejas on
23
+ * @param {Boolean} args.log.http_requests - Whether to log incoming HTTP requests
24
+ * @param {Boolean} args.log.exceptions - Whether to log exceptions
25
+ * @param {String} args.db.type - Database type. It can be 'mongodb', 'mysql', 'postgres', 'sqlite'
26
+ * @param {String} args.db.uri - Connection URI string for the database
27
+ */
28
+ constructor(args) {
29
+ if (Tejas.instance) return Tejas.instance;
30
+ Tejas.instance = this;
31
+
32
+ this.generateConfiguration(args);
33
+ this.registerTargetsDir();
34
+ }
35
+
36
+ /*
37
+ * Connect to a database
38
+ * @param {Object}
39
+ * @param {String} args.db - Database type. It can be 'mongodb', 'mysql', 'postgres', 'sqlite'
40
+ * @param {String} args.uri - Connection URI string for the database
41
+ * @param {Object} args.options - Options for the database connection
42
+ */
43
+ connectDatabase(args) {
44
+ const db = env('DB_TYPE');
45
+ const uri = env('DB_URI');
46
+
47
+ if (!db) return;
48
+ if (!uri) {
49
+ logger.error(
50
+ `Tejas could not connect to ${db} as it couldn't find a connection URI. See our documentation for more information.`,
51
+ false,
52
+ );
53
+ return;
54
+ }
55
+
56
+ const connect = database[db];
57
+ if (!connect) {
58
+ logger.error(
59
+ `Tejas could not connect to ${db} as it is not supported. See our documentation for more information.`,
60
+ false,
61
+ );
62
+ return;
63
+ }
64
+
65
+ connect(uri, {}, (error) => {
66
+ if (error) {
67
+ logger.error(
68
+ `Tejas could not connect to ${db}. Error: ${error}`,
69
+ false,
70
+ );
71
+ return;
72
+ }
73
+
74
+ logger.info(`Tejas connected to ${db} successfully.`);
75
+ });
76
+ }
77
+
78
+ generateConfiguration(options) {
79
+ const configVars = standardizeObj(loadConfigFile());
80
+ const envVars = standardizeObj(process.env);
81
+ const userVars = standardizeObj(options);
82
+
83
+ const config = { ...configVars, ...envVars, ...userVars };
84
+ for (const key in config) {
85
+ if (config.hasOwnProperty(key)) {
86
+ setEnv(key, config[key]);
87
+ }
88
+ }
89
+
90
+ // Load defaults
91
+ if (!env('PORT')) setEnv('PORT', 1403);
92
+ }
93
+
94
+ midair() {
95
+ if (!arguments) return;
96
+ targetRegistry.addGlobalMiddleware(...arguments);
97
+ }
98
+
99
+ registerTargetsDir() {
100
+ findTargetFiles()
101
+ .then((targetFiles) => {
102
+ if (targetFiles) {
103
+ for (const file of targetFiles) {
104
+ import(pathToFileURL(`${file.path}/${file.name}`));
105
+ }
106
+ }
107
+ })
108
+ .catch((err) => {
109
+ logger.error(
110
+ `Tejas could not register target files. Error: ${err}`,
111
+ false,
112
+ );
113
+ });
114
+ }
115
+
116
+ takeoff() {
117
+ this.engine = createServer(targetHandler);
118
+ this.engine.listen(env('PORT'), () => {
119
+ logger.info(`Took off from port ${env('PORT')}`);
120
+ this.connectDatabase();
121
+ });
122
+ }
123
+ }
124
+
125
+ const listAllEndpoints = (grouped = false) => {
126
+ return targetRegistry.getAllEndpoints(grouped);
127
+ };
128
+
129
+ export { default as Target } from './server/target.js';
130
+ export { default as TejFileUploader } from './server/files/uploader.js';
131
+ export { listAllEndpoints };
132
+ export default Tejas;
133
+
134
+ // TODO Ability to register a target (route) from tejas instance
135
+ // TODO tejas as CLI tool