melonykit 0.4.2 → 0.5.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.
@@ -0,0 +1,28 @@
1
+ const clients = new Set();
2
+
3
+ export function connectClientEvents(app) {
4
+ app.get('/api/events', (req, res) => {
5
+ res.setHeader('Content-Type', 'text/event-stream');
6
+ res.setHeader('Cache-Control', 'no-cache');
7
+ res.setHeader('Connection', 'keep-alive');
8
+
9
+ res.flushHeaders();
10
+
11
+ clients.add(res);
12
+
13
+ // Immediately establish the stream.
14
+ res.write(': connected\n\n');
15
+
16
+ req.on('close', () => clients.delete(res));
17
+ });
18
+ };
19
+
20
+ export function sendClientEvent(type, data = null) {
21
+ const message =
22
+ `event: ${type}\n` +
23
+ `data: ${JSON.stringify(data)}\n\n`;
24
+
25
+ for (const client of clients) {
26
+ client.write(message);
27
+ }
28
+ };
@@ -1,9 +1,10 @@
1
1
  import { resolve } from 'node:path';
2
2
  import { pathToFileURL } from 'node:url';
3
3
  import { globSync } from 'glob';
4
+ import debug from './_debug.js';
4
5
 
5
- export default async function importModules(
6
- srcFolder = 'src',
6
+ export async function importModules(
7
+ srcFolder,
7
8
  filePathPatterns,
8
9
  callback
9
10
  ) {
@@ -16,3 +17,42 @@ export default async function importModules(
16
17
  await callback?.(module);
17
18
  }
18
19
  };
20
+
21
+ export async function importRestEndpoints(
22
+ srcFolder,
23
+ filePathPatterns,
24
+ app
25
+ ) {
26
+ await importModules(srcFolder, filePathPatterns, module => {
27
+ const endpoints = Array.isArray(module.default)
28
+ ? module.default
29
+ : [module.default];
30
+
31
+ for (const endpoint of endpoints) {
32
+ app[endpoint.method](
33
+ endpoint.path,
34
+ _createEndpointHandler(endpoint.handler)
35
+ );
36
+ }
37
+ });
38
+ };
39
+
40
+ // ----------------------------------------------------------------------------- Private
41
+ function _createEndpointHandler(expressHandler) {
42
+ return async function handler(req, res) {
43
+ const context = {
44
+ req,
45
+ res,
46
+ respondSuccess(data = {}, statusCode = 200) {
47
+ return res.status(statusCode).json(data);
48
+ },
49
+ respondError(error, statusCode = 500) {
50
+ debug(error);
51
+ return res.status(statusCode).json(null);
52
+ }
53
+ };
54
+
55
+ try { return await expressHandler(context); }
56
+ catch (error) { return context.respondError(error); }
57
+ };
58
+ };
@@ -0,0 +1,51 @@
1
+ import { EventEmitter } from 'node:events';
2
+
3
+ const emitter = new EventEmitter();
4
+ const handlers = new Map();
5
+
6
+ emitter.setMaxListeners(50);
7
+
8
+ export function handle(invocationName, handler) {
9
+ if (handlers.has(invocationName)) {
10
+ throw new Error(`Handle - Handler already registered for "${invocationName}".`);
11
+ }
12
+
13
+ handlers.set(invocationName, handler);
14
+
15
+ return () => {
16
+ if (handlers.get(invocationName) === handler) {
17
+ handlers.delete(invocationName);
18
+ }
19
+ };
20
+ };
21
+
22
+ export async function invoke(invocationName, data) {
23
+ const handler = handlers.get(invocationName);
24
+
25
+ if (!handler) {
26
+ throw new Error(`Invoke - No handler registered for "${invocationName}".`);
27
+ }
28
+
29
+ return Promise.resolve().then(() => handler(data));
30
+ };
31
+
32
+
33
+ export function subscribe(eventName, listener) {
34
+ emitter.on(eventName, listener);
35
+
36
+ return () => emitter.off(eventName, listener);
37
+ };
38
+
39
+ export async function publish(eventName, data) {
40
+ const listeners = emitter.listeners(eventName);
41
+
42
+ if (listeners.length === 0) return undefined;
43
+
44
+ if (listeners.length === 1) {
45
+ return Promise.resolve().then(() => listeners[0](data));
46
+ }
47
+
48
+ return Promise.all(listeners.map(
49
+ listener => Promise.resolve().then(() => listener(data))
50
+ ));
51
+ };
@@ -1,3 +1,4 @@
1
- export { default as importModules } from './_import-modules.js';
2
- export { default as importRestEndpoints } from './_import-rest-endpoints.js';
3
1
  export { default as debug } from './_debug.js';
2
+ export { importModules, importRestEndpoints } from './_import-modules.js';
3
+ export { connectClientEvents, sendClientEvent } from './_client-events.js';
4
+ export { handle, invoke, subscribe, publish } from './_server-events.js';
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "author": "Vadim Hermann",
3
3
  "name": "melonykit",
4
- "version": "0.4.2",
4
+ "version": "0.5.0",
5
5
  "type": "module",
6
6
  "description": "Preact based ui and utility functions toolkit",
7
7
  "main": "./dist/index.js",
@@ -1,172 +0,0 @@
1
- import { dirname, join, resolve } from 'node:path';
2
- import { EventEmitter } from 'node:events';
3
- import { fileURLToPath, pathToFileURL } from 'node:url';
4
- import { globSync } from 'glob';
5
- import compression from 'compression';
6
- import express from 'express';
7
- import Mustache from 'mustache';
8
-
9
- const __dirname = dirname(fileURLToPath(import.meta.url));
10
- const srcFolder = resolve(`${__dirname}/../../src`);
11
- const emitter = new EventEmitter();
12
- const clients = new Set();
13
- const handlers = new Map();
14
-
15
- emitter.setMaxListeners(50);
16
-
17
- export async function initModules(app) {
18
- await _importEachModule('**/_database.*.js');
19
- await _importEachModule('**/_service.*.js');
20
- await _importEachModule('**/_endpoints.*.js', module => {
21
- const endpoints = Array.isArray(module.default)
22
- ? module.default
23
- : [module.default];
24
-
25
- for (const endpoint of endpoints) {
26
- app[endpoint.method](
27
- endpoint.path,
28
- _createEndpointHandler(endpoint.handler)
29
- );
30
- }
31
- });
32
- };
33
-
34
- export function connectClientEvents (app) {
35
- app.get('/api/events', (req, res) => {
36
- res.setHeader('Content-Type', 'text/event-stream');
37
- res.setHeader('Cache-Control', 'no-cache');
38
- res.setHeader('Connection', 'keep-alive');
39
-
40
- res.flushHeaders();
41
-
42
- clients.add(res);
43
-
44
- // Immediately establish the stream.
45
- res.write(': connected\n\n');
46
-
47
- req.on('close', () => clients.delete(res));
48
- });
49
- };
50
-
51
- export async function start(app, port = 3000) {
52
- app.use(express.json());
53
-
54
- if (process.env.NODE_ENV === 'production') {
55
- // Enable gzip for prod
56
- app.use(compression());
57
-
58
- const __dirname = dirname(fileURLToPath(import.meta.url));
59
- const buildPath = join(__dirname, '../../dist');
60
-
61
- // Define path to static web files
62
- app.use(express.static(buildPath));
63
-
64
- // Single page application fallback for client routing
65
- app.get(/.*/, (_, res) => {
66
- res.sendFile(join(buildPath, 'index.html'));
67
- });
68
- }
69
-
70
- return app.listen(port,
71
- () => console.log(`Node Server 🚀 http://localhost:${port}`)
72
- );
73
- };
74
-
75
- export function sendClientEvent(type, data = null) {
76
- const message =
77
- `event: ${type}\n` +
78
- `data: ${JSON.stringify(data)}\n\n`;
79
-
80
- for (const client of clients) {
81
- client.write(message);
82
- }
83
- };
84
-
85
- export function renderTemplate (template, data) {
86
- const html = Mustache.render(template, JSON.parse(data));
87
-
88
- return `<!-- Generiertes HTML -->${html}`;
89
- };
90
-
91
- export function subscribe(eventName, listener) {
92
- emitter.on(eventName, listener);
93
-
94
- return () => emitter.off(eventName, listener);
95
- };
96
-
97
- export async function publish(eventName, data) {
98
- const listeners = emitter.listeners(eventName);
99
-
100
- if (listeners.length === 0) return undefined;
101
-
102
- if (listeners.length === 1) {
103
- return Promise.resolve().then(() => listeners[0](data));
104
- }
105
-
106
- return Promise.all(listeners.map(
107
- listener => Promise.resolve().then(() => listener(data))
108
- ));
109
- };
110
-
111
- export function handle(invocationName, handler) {
112
- if (handlers.has(invocationName)) {
113
- throw new Error(`Handle - Handler already registered for "${invocationName}".`);
114
- }
115
-
116
- handlers.set(invocationName, handler);
117
-
118
- return () => {
119
- if (handlers.get(invocationName) === handler) {
120
- handlers.delete(invocationName);
121
- }
122
- };
123
- };
124
-
125
- export async function invoke(invocationName, data) {
126
- const handler = handlers.get(invocationName);
127
-
128
- if (!handler) {
129
- throw new Error(`Invoke - No handler registered for "${invocationName}".`);
130
- }
131
-
132
- return Promise.resolve().then(() => handler(data));
133
- };
134
-
135
- export function debug(error) {
136
- if (!process.env.DEBUG === 'true') return;
137
-
138
- console.log('[DEBUG]: ', error);
139
- }
140
-
141
- // ----------------------------------------------------------------------------- Private
142
- async function _importEachModule(filePathPattern, callback = async () => {}) {
143
- const filePaths = globSync(filePathPattern, {
144
- cwd: srcFolder,
145
- absolute: true
146
- });
147
-
148
- for (const filePath of filePaths) {
149
- const module = await import(pathToFileURL(filePath).href);
150
-
151
- await callback(module);
152
- }
153
- };
154
-
155
- function _createEndpointHandler(expressHandler) {
156
- return async function handler(req, res) {
157
- const context = {
158
- req,
159
- res,
160
- respondSuccess(data = {}, statusCode = 200) {
161
- return res.status(statusCode).json(data);
162
- },
163
- respondError(error, statusCode = 500) {
164
- debug(error);
165
- return res.status(statusCode).json(null);
166
- }
167
- };
168
-
169
- try { return await expressHandler(context); }
170
- catch (error) { return context.respondError(error); }
171
- };
172
- };
@@ -1,40 +0,0 @@
1
- import importModules from './_import-modules.js';
2
-
3
- export default async function importRestEndpoints(
4
- srcFolder,
5
- filePathPatterns,
6
- app
7
- ) {
8
- await importModules(srcFolder, filePathPatterns, module => {
9
- const endpoints = Array.isArray(module.default)
10
- ? module.default
11
- : [module.default];
12
-
13
- for (const endpoint of endpoints) {
14
- app[endpoint.method](
15
- endpoint.path,
16
- _createEndpointHandler(endpoint.handler)
17
- );
18
- }
19
- });
20
- };
21
-
22
- // ----------------------------------------------------------------------------- Private
23
- function _createEndpointHandler(expressHandler) {
24
- return async function handler(req, res) {
25
- const context = {
26
- req,
27
- res,
28
- respondSuccess(data = {}, statusCode = 200) {
29
- return res.status(statusCode).json(data);
30
- },
31
- respondError(error, statusCode = 500) {
32
- debug(error);
33
- return res.status(statusCode).json(null);
34
- }
35
- };
36
-
37
- try { return await expressHandler(context); }
38
- catch (error) { return context.respondError(error); }
39
- };
40
- };