@xeplr/base-apis 1.0.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/LICENSE +21 -0
- package/express.js +155 -0
- package/index.js +10 -0
- package/lib/cluster.js +114 -0
- package/lib/genericController.js +218 -0
- package/lib/genericRoute.js +139 -0
- package/lib/requestLogger.js +53 -0
- package/lib/server.js +46 -0
- package/package.json +22 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Xeplr
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/express.js
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
var express = require('express');
|
|
2
|
+
var cors = require('cors');
|
|
3
|
+
var cookieParser = require('cookie-parser');
|
|
4
|
+
var path = require('path');
|
|
5
|
+
var { createServer } = require('./lib/server');
|
|
6
|
+
var logs = require('@xeplr/logs');
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Create and initialize an Express application.
|
|
10
|
+
* Factory function — each call returns a fresh app instance.
|
|
11
|
+
*
|
|
12
|
+
* @param {number|string} port - Port or named pipe to listen on
|
|
13
|
+
* @param {string} appName - Service name (used for debug namespace and console logs)
|
|
14
|
+
* @param {object} [options] - Configuration options
|
|
15
|
+
* @param {object} [options.routes] - Route map: { '/path': router }
|
|
16
|
+
* @param {Function[]} [options.middleware] - Middleware to apply before routes (e.g. authMiddleware)
|
|
17
|
+
* @param {object} [options.views] - { engine: 'pug', dir: '/abs/path' }
|
|
18
|
+
* @param {string} [options.staticDir] - Path to static files directory
|
|
19
|
+
* @param {string} [options.corsOptions] - Custom CORS options (default: allow all)
|
|
20
|
+
* @param {Function} [options.errorHandler] - Custom error handler (req, res, next)
|
|
21
|
+
* @param {object|false} [options.log] - Logger config (false to disable)
|
|
22
|
+
* @param {string} [options.log.logDir='./logs'] - Log directory
|
|
23
|
+
* @param {number} [options.log.fatalThreshold=4] - Level >= this is fatal (4=error, 5=critical)
|
|
24
|
+
* @param {number} [options.log.emailThreshold=5] - Level >= this triggers email
|
|
25
|
+
* @param {string|string[]} [options.log.emailTo] - Email recipient(s)
|
|
26
|
+
* @param {object} [options.log.emailService] - Email service instance
|
|
27
|
+
* @param {object} [options.upload] - File upload config
|
|
28
|
+
* @param {string} [options.upload.route='/internal/upload'] - Upload endpoint path
|
|
29
|
+
* @param {string} [options.upload.destination='./uploads'] - Storage directory
|
|
30
|
+
* @param {string[]} [options.upload.allowedTypes=['*']] - MIME types
|
|
31
|
+
* @param {number} [options.upload.maxSize=5242880] - Max file size in bytes
|
|
32
|
+
* @param {string} [options.upload.fieldName='file'] - Form field name
|
|
33
|
+
* @param {number} [options.upload.maxFiles=10] - Max files per request
|
|
34
|
+
* @param {string} [options.upload.serveRoute='/uploads'] - Static serve path for uploaded files
|
|
35
|
+
* @returns {{ app: Express, server: http.Server }}
|
|
36
|
+
*/
|
|
37
|
+
function createApp(port, appName, options) {
|
|
38
|
+
options = options || {};
|
|
39
|
+
var app = express();
|
|
40
|
+
|
|
41
|
+
// ── Logger ──
|
|
42
|
+
if (options.log !== false) {
|
|
43
|
+
var logCfg = options.log || {};
|
|
44
|
+
logs.configure({
|
|
45
|
+
appName: appName,
|
|
46
|
+
logDir: logCfg.logDir || './logs',
|
|
47
|
+
fatalThreshold: logCfg.fatalThreshold,
|
|
48
|
+
emailThreshold: logCfg.emailThreshold,
|
|
49
|
+
emailTo: logCfg.emailTo,
|
|
50
|
+
emailService: logCfg.emailService,
|
|
51
|
+
isDev: (process.env.NODE_ENV || 'development') !== 'production'
|
|
52
|
+
});
|
|
53
|
+
app.use(logs.requestLogger());
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// ── View engine ──
|
|
57
|
+
if (options.views) {
|
|
58
|
+
app.set('views', options.views.dir);
|
|
59
|
+
app.set('view engine', options.views.engine || 'pug');
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// ── Standard middleware ──
|
|
63
|
+
app.use(cors(options.corsOptions));
|
|
64
|
+
app.use(express.json());
|
|
65
|
+
app.use(express.urlencoded({ extended: false }));
|
|
66
|
+
app.use(cookieParser());
|
|
67
|
+
|
|
68
|
+
// ── Static files ──
|
|
69
|
+
if (options.staticDir) {
|
|
70
|
+
app.use(express.static(options.staticDir));
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// ── File upload (static serve before auth, upload route after auth) ──
|
|
74
|
+
if (options.upload) {
|
|
75
|
+
var serveRoute = options.upload.serveRoute || '/uploads';
|
|
76
|
+
var destination = path.resolve(options.upload.destination || process.env.UPLOAD_DIR || './uploads');
|
|
77
|
+
app.use(serveRoute, express.static(destination));
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// ── Injected middleware (auth, etc.) ──
|
|
81
|
+
if (options.middleware) {
|
|
82
|
+
options.middleware.forEach(function(mw) { app.use(mw); });
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// ── File upload (upload endpoint — behind auth) ──
|
|
86
|
+
if (options.upload) {
|
|
87
|
+
var FileUploader = require('@xeplr/utils').FileUploader;
|
|
88
|
+
var uploadCfg = options.upload;
|
|
89
|
+
var destination = path.resolve(uploadCfg.destination || process.env.UPLOAD_DIR || './uploads');
|
|
90
|
+
var uploader = new FileUploader({
|
|
91
|
+
auth: uploadCfg.auth || null,
|
|
92
|
+
allowedTypes: uploadCfg.allowedTypes || ['*'],
|
|
93
|
+
maxSize: uploadCfg.maxSize || 5 * 1024 * 1024,
|
|
94
|
+
destination: destination
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
var uploadRoute = uploadCfg.route || '/internal/upload';
|
|
98
|
+
var fieldName = uploadCfg.fieldName || 'file';
|
|
99
|
+
var maxFiles = uploadCfg.maxFiles || 10;
|
|
100
|
+
|
|
101
|
+
app.post(uploadRoute, uploader.array(fieldName, maxFiles), function(req, res) {
|
|
102
|
+
if (!req.files || req.files.length === 0) {
|
|
103
|
+
return res.status(400).json({ error: 'No files uploaded' });
|
|
104
|
+
}
|
|
105
|
+
var files = req.files.map(function(f) {
|
|
106
|
+
return {
|
|
107
|
+
filename: f.filename,
|
|
108
|
+
originalName: f.originalname,
|
|
109
|
+
size: f.size,
|
|
110
|
+
mimetype: f.mimetype
|
|
111
|
+
};
|
|
112
|
+
});
|
|
113
|
+
res.json(files.length === 1 ? files[0] : files);
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// ── Routes ──
|
|
118
|
+
if (options.routes) {
|
|
119
|
+
Object.keys(options.routes).forEach(function(routePath) {
|
|
120
|
+
app.use(routePath, options.routes[routePath]);
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// ── 404 handler ──
|
|
125
|
+
if (options.views) {
|
|
126
|
+
var createError = require('http-errors');
|
|
127
|
+
app.use(function(req, res, next) { next(createError(404)); });
|
|
128
|
+
} else {
|
|
129
|
+
app.use(function(req, res) { res.status(404).json({ error: 'Not found' }); });
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// ── Error handler ──
|
|
133
|
+
if (options.errorHandler) {
|
|
134
|
+
app.use(options.errorHandler);
|
|
135
|
+
} else if (options.views) {
|
|
136
|
+
app.use(function(err, req, res, next) {
|
|
137
|
+
res.locals.message = err.message;
|
|
138
|
+
res.locals.error = req.app.get('env') === 'development' ? err : {};
|
|
139
|
+
res.status(err.status || 500);
|
|
140
|
+
res.render('error');
|
|
141
|
+
});
|
|
142
|
+
} else {
|
|
143
|
+
app.use(function(err, req, res, next) {
|
|
144
|
+
res.status(err.status || 500).json({ error: err.message });
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// ── Start HTTP server ──
|
|
149
|
+
app.set('port', port);
|
|
150
|
+
var server = createServer(app, port, appName);
|
|
151
|
+
|
|
152
|
+
return { app: app, server: server };
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
module.exports = createApp;
|
package/index.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
module.exports = {
|
|
2
|
+
createApp: require('./express'),
|
|
3
|
+
createHttpServer: require('./http'),
|
|
4
|
+
genericRoute: require('./lib/genericRoute'),
|
|
5
|
+
genericController: require('./lib/genericController'),
|
|
6
|
+
runCluster: require('./lib/cluster').runCluster,
|
|
7
|
+
broadcast: require('./lib/cluster').broadcast,
|
|
8
|
+
isPrimary: require('./lib/cluster').isPrimary,
|
|
9
|
+
isWorker: require('./lib/cluster').isWorker
|
|
10
|
+
};
|
package/lib/cluster.js
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
var cluster = require('cluster');
|
|
2
|
+
var os = require('os');
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Run an Express app across multiple worker processes using Node.js cluster.
|
|
6
|
+
*
|
|
7
|
+
* The primary process forks workers and manages lifecycle.
|
|
8
|
+
* Each worker runs the app independently with its own event loop.
|
|
9
|
+
*
|
|
10
|
+
* Workers can notify each other via `broadcast()` — primary relays
|
|
11
|
+
* the message to all other workers.
|
|
12
|
+
*
|
|
13
|
+
* Usage:
|
|
14
|
+
*
|
|
15
|
+
* var { runCluster } = require('@xeplr/base-apis');
|
|
16
|
+
*
|
|
17
|
+
* runCluster({
|
|
18
|
+
* workers: 4, // default: CPU count
|
|
19
|
+
* start: function() { // called in each worker
|
|
20
|
+
* var { createApp } = require('@xeplr/base-apis');
|
|
21
|
+
* createApp(3000, 'myapp', { routes: { ... } });
|
|
22
|
+
* },
|
|
23
|
+
* onMessage: function(msg) { // called in each worker when broadcast received
|
|
24
|
+
* if (msg.type === 'cache-clear') clearLocalCache();
|
|
25
|
+
* }
|
|
26
|
+
* });
|
|
27
|
+
*
|
|
28
|
+
* Inside a worker, notify others:
|
|
29
|
+
*
|
|
30
|
+
* var { broadcast } = require('@xeplr/base-apis/lib/cluster');
|
|
31
|
+
* broadcast({ type: 'cache-clear', key: 'users' });
|
|
32
|
+
*
|
|
33
|
+
* @param {object} options
|
|
34
|
+
* @param {Function} options.start - Called in each worker to boot the app
|
|
35
|
+
* @param {number} [options.workers] - Number of workers (default: os.cpus().length)
|
|
36
|
+
* @param {Function} [options.onMessage] - Handler for broadcast messages in workers
|
|
37
|
+
* @param {boolean} [options.respawn] - Restart crashed workers (default: true)
|
|
38
|
+
*/
|
|
39
|
+
function runCluster(options) {
|
|
40
|
+
var workerCount = options.workers || os.cpus().length;
|
|
41
|
+
var respawn = options.respawn !== false;
|
|
42
|
+
|
|
43
|
+
if (cluster.isPrimary) {
|
|
44
|
+
console.log('[cluster] Primary ' + process.pid + ' starting ' + workerCount + ' workers');
|
|
45
|
+
|
|
46
|
+
// Fork workers
|
|
47
|
+
for (var i = 0; i < workerCount; i++) {
|
|
48
|
+
cluster.fork();
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// Relay messages from one worker to all others
|
|
52
|
+
cluster.on('message', function(sender, msg) {
|
|
53
|
+
if (msg && msg._broadcast) {
|
|
54
|
+
for (var id in cluster.workers) {
|
|
55
|
+
var worker = cluster.workers[id];
|
|
56
|
+
if (worker && worker !== sender && !worker.isDead()) {
|
|
57
|
+
worker.send(msg);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
// Respawn dead workers
|
|
64
|
+
cluster.on('exit', function(worker, code, signal) {
|
|
65
|
+
console.log('[cluster] Worker ' + worker.process.pid + ' died (' + (signal || code) + ')');
|
|
66
|
+
if (respawn) {
|
|
67
|
+
console.log('[cluster] Spawning replacement worker');
|
|
68
|
+
cluster.fork();
|
|
69
|
+
}
|
|
70
|
+
});
|
|
71
|
+
} else {
|
|
72
|
+
// Worker process — boot the app
|
|
73
|
+
options.start();
|
|
74
|
+
|
|
75
|
+
// Listen for broadcast messages from other workers
|
|
76
|
+
if (options.onMessage) {
|
|
77
|
+
process.on('message', function(msg) {
|
|
78
|
+
if (msg && msg._broadcast) {
|
|
79
|
+
options.onMessage(msg);
|
|
80
|
+
}
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
console.log('[cluster] Worker ' + process.pid + ' started');
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Send a message to all other workers via the primary process.
|
|
90
|
+
* Call this from within a worker process.
|
|
91
|
+
*
|
|
92
|
+
* @param {object} msg - Any serializable object. Gets `_broadcast: true` added.
|
|
93
|
+
*/
|
|
94
|
+
function broadcast(msg) {
|
|
95
|
+
if (!process.send) return; // not in a cluster worker
|
|
96
|
+
msg._broadcast = true;
|
|
97
|
+
process.send(msg);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Check if current process is the primary.
|
|
102
|
+
*/
|
|
103
|
+
function isPrimary() {
|
|
104
|
+
return cluster.isPrimary;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Check if current process is a worker.
|
|
109
|
+
*/
|
|
110
|
+
function isWorker() {
|
|
111
|
+
return cluster.isWorker;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
module.exports = { runCluster, broadcast, isPrimary, isWorker };
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
var { respond } = require('@xeplr/utils/lib/response');
|
|
2
|
+
var { HTTP, STATUS } = require('@xeplr/utils/isomorphic');
|
|
3
|
+
var { generateId } = require('@xeplr/utils/lib/helpers');
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Generic CRUD controller.
|
|
7
|
+
* Processes the changeset from xeplr-ui-table in a single transaction.
|
|
8
|
+
*
|
|
9
|
+
* Changeset rules:
|
|
10
|
+
* - No id → INSERT (new record)
|
|
11
|
+
* - Has id, deleted → SOFT DELETE (isActive = false)
|
|
12
|
+
* - Has id → PATCH (only changed fields)
|
|
13
|
+
* - Children nested inside parent follow same rules, recursively
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Save handler — processes a changeset array in a single transaction.
|
|
18
|
+
*
|
|
19
|
+
* @param {object} req - Express request. Body: changeset array.
|
|
20
|
+
* @param {object} res - Express response.
|
|
21
|
+
* @param {object} hierarchy - { key, model, children: [...] }
|
|
22
|
+
*/
|
|
23
|
+
async function save(req, res, hierarchy) {
|
|
24
|
+
var changeSet = req.body;
|
|
25
|
+
|
|
26
|
+
if (!Array.isArray(changeSet) || changeSet.length === 0) {
|
|
27
|
+
return respond(res, HTTP.BAD_REQUEST, STATUS.BAD_REQUEST, 'bad_request', {
|
|
28
|
+
message: 'Expected a non-empty changeset array'
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
var rootDef = hierarchy;
|
|
33
|
+
var knex = rootDef.model.knex();
|
|
34
|
+
var updatedIds = [];
|
|
35
|
+
|
|
36
|
+
var trx = await knex.transaction();
|
|
37
|
+
|
|
38
|
+
try {
|
|
39
|
+
for (var i = 0; i < changeSet.length; i++) {
|
|
40
|
+
var ids = await processEntry(changeSet[i], rootDef, trx);
|
|
41
|
+
updatedIds = updatedIds.concat(ids);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
await trx.commit();
|
|
45
|
+
respond(res, HTTP.OK, STATUS.UPDATED, 'updated', { updatedIds: updatedIds });
|
|
46
|
+
} catch (err) {
|
|
47
|
+
await trx.rollback();
|
|
48
|
+
respond(res, HTTP.SERVER_ERROR, STATUS.SERVER_ERROR, 'server_error', { error: err });
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Process a single changeset entry (recursive for children).
|
|
54
|
+
* @param {object} entry - The changeset row
|
|
55
|
+
* @param {object} def - Hierarchy definition { key, model, children, foreignKey }
|
|
56
|
+
* @param {object} trx - Knex transaction
|
|
57
|
+
* @param {string} [parentId] - Parent record ID (set automatically for children)
|
|
58
|
+
*/
|
|
59
|
+
async function processEntry(entry, def, trx, parentId) {
|
|
60
|
+
var Model = def.model;
|
|
61
|
+
var children = def.children || [];
|
|
62
|
+
var ids = [];
|
|
63
|
+
|
|
64
|
+
// ── SOFT DELETE ──
|
|
65
|
+
if (entry.deleted === true) {
|
|
66
|
+
await Model.query(trx).findById(entry.id).patch({ isActive: false });
|
|
67
|
+
ids.push(entry.id);
|
|
68
|
+
return ids;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Separate own fields from child arrays
|
|
72
|
+
var ownFields = {};
|
|
73
|
+
var childData = {};
|
|
74
|
+
var keys = Object.keys(entry);
|
|
75
|
+
|
|
76
|
+
for (var k = 0; k < keys.length; k++) {
|
|
77
|
+
var key = keys[k];
|
|
78
|
+
if (key === 'deleted') continue;
|
|
79
|
+
|
|
80
|
+
var childDef = findChildDef(children, key);
|
|
81
|
+
if (childDef) {
|
|
82
|
+
childData[key] = entry[key];
|
|
83
|
+
} else {
|
|
84
|
+
ownFields[key] = entry[key];
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Auto-set foreign key if this is a child record
|
|
89
|
+
if (def.foreignKey && parentId) {
|
|
90
|
+
ownFields[def.foreignKey] = parentId;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
var recordId = ownFields.id;
|
|
94
|
+
|
|
95
|
+
// ── INSERT ──
|
|
96
|
+
if (!recordId) {
|
|
97
|
+
recordId = generateId();
|
|
98
|
+
ownFields.id = recordId;
|
|
99
|
+
await Model.query(trx).insert(ownFields);
|
|
100
|
+
ids.push(recordId);
|
|
101
|
+
} else {
|
|
102
|
+
// ── PATCH ──
|
|
103
|
+
var patchFields = Object.assign({}, ownFields);
|
|
104
|
+
delete patchFields.id;
|
|
105
|
+
|
|
106
|
+
if (Object.keys(patchFields).length > 0) {
|
|
107
|
+
await Model.query(trx).findById(recordId).patch(patchFields);
|
|
108
|
+
ids.push(recordId);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// ── Process children recursively ──
|
|
113
|
+
for (var c = 0; c < children.length; c++) {
|
|
114
|
+
var cDef = children[c];
|
|
115
|
+
var childEntries = childData[cDef.key];
|
|
116
|
+
if (!childEntries || !Array.isArray(childEntries)) continue;
|
|
117
|
+
|
|
118
|
+
for (var j = 0; j < childEntries.length; j++) {
|
|
119
|
+
var childIds = await processEntry(childEntries[j], cDef, trx, recordId);
|
|
120
|
+
ids = ids.concat(childIds);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
return ids;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function findChildDef(children, key) {
|
|
128
|
+
for (var i = 0; i < children.length; i++) {
|
|
129
|
+
if (children[i].key === key) return children[i];
|
|
130
|
+
}
|
|
131
|
+
return null;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Delete handler — soft delete by ids.
|
|
136
|
+
*/
|
|
137
|
+
async function deleteByIds(req, res, Model) {
|
|
138
|
+
var ids = req.body.ids;
|
|
139
|
+
|
|
140
|
+
if (!Array.isArray(ids) || ids.length === 0) {
|
|
141
|
+
return respond(res, HTTP.BAD_REQUEST, STATUS.BAD_REQUEST, 'bad_request', {
|
|
142
|
+
message: 'Expected a non-empty ids array'
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
try {
|
|
147
|
+
await Model.query().whereIn('id', ids).patch({ isActive: false });
|
|
148
|
+
respond(res, HTTP.OK, STATUS.DELETED, 'deleted', { updatedIds: ids });
|
|
149
|
+
} catch (err) {
|
|
150
|
+
respond(res, HTTP.SERVER_ERROR, STATUS.SERVER_ERROR, 'server_error', { error: err });
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Get by ID — single record with eager children.
|
|
156
|
+
*/
|
|
157
|
+
async function getById(req, res, Model, graph) {
|
|
158
|
+
try {
|
|
159
|
+
var query = Model.query().findById(req.params.id);
|
|
160
|
+
if (graph) {
|
|
161
|
+
query = query.withGraphFetched(graph);
|
|
162
|
+
}
|
|
163
|
+
var record = await query;
|
|
164
|
+
|
|
165
|
+
if (!record) {
|
|
166
|
+
return respond(res, HTTP.NOT_FOUND, STATUS.NOT_FOUND, 'not_found');
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
respond(res, HTTP.OK, STATUS.SUCCESS, 'success', { dataArray: [record] });
|
|
170
|
+
} catch (err) {
|
|
171
|
+
respond(res, HTTP.SERVER_ERROR, STATUS.SERVER_ERROR, 'server_error', { error: err });
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* List — paginated, with optional eager graph.
|
|
177
|
+
*
|
|
178
|
+
* Query params:
|
|
179
|
+
* ?page=1&limit=50 — pagination (default: page 1, limit 50)
|
|
180
|
+
* ?limit=0 — no pagination, return all (use carefully)
|
|
181
|
+
*
|
|
182
|
+
* Response includes pagination metadata in dataArray wrapper:
|
|
183
|
+
* { dataArray: [...], pagination: { page, limit, total, totalPages } }
|
|
184
|
+
*/
|
|
185
|
+
async function list(req, res, Model, graph) {
|
|
186
|
+
try {
|
|
187
|
+
var page = parseInt(req.query.page) || 1;
|
|
188
|
+
var limit = req.query.limit !== undefined ? parseInt(req.query.limit) : 50;
|
|
189
|
+
|
|
190
|
+
var query = Model.query();
|
|
191
|
+
if (graph) {
|
|
192
|
+
query = query.withGraphFetched(graph);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// limit=0 means no pagination (return all)
|
|
196
|
+
if (limit > 0) {
|
|
197
|
+
var countResult = await Model.query().count('* as total').first();
|
|
198
|
+
var total = countResult.total || 0;
|
|
199
|
+
var totalPages = Math.ceil(total / limit);
|
|
200
|
+
var offset = (page - 1) * limit;
|
|
201
|
+
|
|
202
|
+
query = query.limit(limit).offset(offset);
|
|
203
|
+
var records = await query;
|
|
204
|
+
|
|
205
|
+
respond(res, HTTP.OK, STATUS.SUCCESS, 'success', {
|
|
206
|
+
dataArray: records,
|
|
207
|
+
pagination: { page: page, limit: limit, total: total, totalPages: totalPages }
|
|
208
|
+
});
|
|
209
|
+
} else {
|
|
210
|
+
var records = await query;
|
|
211
|
+
respond(res, HTTP.OK, STATUS.SUCCESS, 'success', { dataArray: records });
|
|
212
|
+
}
|
|
213
|
+
} catch (err) {
|
|
214
|
+
respond(res, HTTP.SERVER_ERROR, STATUS.SERVER_ERROR, 'server_error', { error: err });
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
module.exports = { save, deleteByIds, getById, list };
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
var express = require('express');
|
|
2
|
+
var controller = require('./genericController');
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Generate CRUD routes for a model hierarchy.
|
|
6
|
+
*
|
|
7
|
+
* Usage:
|
|
8
|
+
*
|
|
9
|
+
* var { genericRoute } = require('@xeplr/base-apis');
|
|
10
|
+
*
|
|
11
|
+
* // Basic — all routes require auth
|
|
12
|
+
* var deptRoutes = genericRoute(hierarchy, { auth: authMiddleware });
|
|
13
|
+
*
|
|
14
|
+
* // Per-operation auth
|
|
15
|
+
* var deptRoutes = genericRoute(hierarchy, {
|
|
16
|
+
* auth: {
|
|
17
|
+
* list: authMiddleware, // any authenticated user can list
|
|
18
|
+
* getById: authMiddleware,
|
|
19
|
+
* save: [authMiddleware, adminOnly], // save needs admin
|
|
20
|
+
* delete: [authMiddleware, adminOnly]
|
|
21
|
+
* }
|
|
22
|
+
* });
|
|
23
|
+
*
|
|
24
|
+
* // No auth (dev/internal only)
|
|
25
|
+
* var deptRoutes = genericRoute(hierarchy);
|
|
26
|
+
*
|
|
27
|
+
* Hierarchy:
|
|
28
|
+
* {
|
|
29
|
+
* key: 'department',
|
|
30
|
+
* model: Department,
|
|
31
|
+
* children: [
|
|
32
|
+
* { key: 'employees', model: Employee,
|
|
33
|
+
* children: [{ key: 'salaries', model: Salary }]
|
|
34
|
+
* }
|
|
35
|
+
* ]
|
|
36
|
+
* }
|
|
37
|
+
*
|
|
38
|
+
* Generated routes:
|
|
39
|
+
* GET / → list (paginated: ?page=1&limit=50)
|
|
40
|
+
* GET /:id → get by id (with eager children)
|
|
41
|
+
* POST /save → save changeset (transactional)
|
|
42
|
+
* POST /delete → soft delete by ids
|
|
43
|
+
*
|
|
44
|
+
* @param {object} hierarchy - { key, model, children? }
|
|
45
|
+
* @param {object} [options]
|
|
46
|
+
* @param {Function|object} [options.auth] - Single middleware or { list, getById, save, delete }
|
|
47
|
+
* @returns {Router}
|
|
48
|
+
*/
|
|
49
|
+
function genericRoute(hierarchy, options) {
|
|
50
|
+
options = options || {};
|
|
51
|
+
var router = express.Router();
|
|
52
|
+
var Model = hierarchy.model;
|
|
53
|
+
var graph = buildGraph(hierarchy);
|
|
54
|
+
|
|
55
|
+
var auth = resolveAuth(options.auth);
|
|
56
|
+
|
|
57
|
+
// GET / — list (paginated)
|
|
58
|
+
router.get('/', auth.list, function(req, res) {
|
|
59
|
+
controller.list(req, res, Model, graph);
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
// GET /:id — get single with eager children
|
|
63
|
+
router.get('/:id', auth.getById, function(req, res) {
|
|
64
|
+
controller.getById(req, res, Model, graph);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
// POST /save — process changeset
|
|
68
|
+
router.post('/save', auth.save, function(req, res) {
|
|
69
|
+
controller.save(req, res, hierarchy);
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
// POST /delete — soft delete by ids
|
|
73
|
+
router.post('/delete', auth.delete, function(req, res) {
|
|
74
|
+
controller.deleteByIds(req, res, Model);
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
return router;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Resolve auth option into per-operation middleware arrays.
|
|
82
|
+
*
|
|
83
|
+
* Input forms:
|
|
84
|
+
* undefined → no auth (passthrough)
|
|
85
|
+
* Function → same middleware for all operations
|
|
86
|
+
* [Function, Function] → same middleware chain for all operations
|
|
87
|
+
* { list, save, ... } → per-operation middleware
|
|
88
|
+
*/
|
|
89
|
+
function resolveAuth(auth) {
|
|
90
|
+
var noop = function(req, res, next) { next(); };
|
|
91
|
+
var defaults = { list: [noop], getById: [noop], save: [noop], delete: [noop] };
|
|
92
|
+
|
|
93
|
+
if (!auth) return defaults;
|
|
94
|
+
|
|
95
|
+
// Single function or array → apply to all operations
|
|
96
|
+
if (typeof auth === 'function' || Array.isArray(auth)) {
|
|
97
|
+
var mw = Array.isArray(auth) ? auth : [auth];
|
|
98
|
+
return { list: mw, getById: mw, save: mw, delete: mw };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// Per-operation object
|
|
102
|
+
return {
|
|
103
|
+
list: toArray(auth.list) || defaults.list,
|
|
104
|
+
getById: toArray(auth.getById) || defaults.getById,
|
|
105
|
+
save: toArray(auth.save) || defaults.save,
|
|
106
|
+
delete: toArray(auth.delete) || defaults.delete
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function toArray(val) {
|
|
111
|
+
if (!val) return null;
|
|
112
|
+
return Array.isArray(val) ? val : [val];
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Build an Objection.js eager graph string from the hierarchy.
|
|
117
|
+
* { children: [{ key: 'employees', children: [{ key: 'salaries' }] }] }
|
|
118
|
+
* → '[employees.[salaries]]'
|
|
119
|
+
*/
|
|
120
|
+
function buildGraph(hierarchy) {
|
|
121
|
+
var children = hierarchy.children;
|
|
122
|
+
if (!children || children.length === 0) return null;
|
|
123
|
+
|
|
124
|
+
var parts = [];
|
|
125
|
+
for (var i = 0; i < children.length; i++) {
|
|
126
|
+
var child = children[i];
|
|
127
|
+
var childGraph = buildGraph(child);
|
|
128
|
+
if (childGraph) {
|
|
129
|
+
parts.push(child.key + '.' + childGraph);
|
|
130
|
+
} else {
|
|
131
|
+
parts.push(child.key);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
if (parts.length === 1) return parts[0];
|
|
136
|
+
return '[' + parts.join(', ') + ']';
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
module.exports = genericRoute;
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
var fs = require('fs');
|
|
2
|
+
var path = require('path');
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Request logger middleware — logs entry and exit for every API hit to a text file.
|
|
6
|
+
*
|
|
7
|
+
* @param {string} appName - Service name (used in log prefix)
|
|
8
|
+
* @param {object} [options]
|
|
9
|
+
* @param {string} [options.logDir='./logs'] - Directory for log files
|
|
10
|
+
* @param {string} [options.filename] - Log filename (default: <appName>-requests.log)
|
|
11
|
+
*/
|
|
12
|
+
function createRequestLogger(appName, options) {
|
|
13
|
+
options = options || {};
|
|
14
|
+
var logDir = path.resolve(options.logDir || process.env.LOG_DIR || './logs');
|
|
15
|
+
var filename = options.filename || (appName + '-requests.log');
|
|
16
|
+
|
|
17
|
+
if (!fs.existsSync(logDir)) {
|
|
18
|
+
fs.mkdirSync(logDir, { recursive: true });
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
var logPath = path.join(logDir, filename);
|
|
22
|
+
var stream = fs.createWriteStream(logPath, { flags: 'a' });
|
|
23
|
+
|
|
24
|
+
function timestamp() {
|
|
25
|
+
return new Date().toISOString();
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function write(line) {
|
|
29
|
+
stream.write(line + '\n');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
return function requestLogger(req, res, next) {
|
|
33
|
+
var id = Math.random().toString(36).slice(2, 10);
|
|
34
|
+
var method = req.method;
|
|
35
|
+
var url = req.originalUrl || req.url;
|
|
36
|
+
var entryTime = Date.now();
|
|
37
|
+
|
|
38
|
+
write('[' + timestamp() + '] [' + appName + '] [' + id + '] → ' + method + ' ' + url);
|
|
39
|
+
|
|
40
|
+
var originalEnd = res.end;
|
|
41
|
+
res.end = function() {
|
|
42
|
+
res.end = originalEnd;
|
|
43
|
+
res.end.apply(res, arguments);
|
|
44
|
+
|
|
45
|
+
var duration = Date.now() - entryTime;
|
|
46
|
+
write('[' + timestamp() + '] [' + appName + '] [' + id + '] ← ' + method + ' ' + url + ' ' + res.statusCode + ' ' + duration + 'ms');
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
next();
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
module.exports = createRequestLogger;
|
package/lib/server.js
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
const http = require('http');
|
|
2
|
+
|
|
3
|
+
function normalizePort(val) {
|
|
4
|
+
const port = parseInt(val, 10);
|
|
5
|
+
if (isNaN(port)) return val; // named pipe
|
|
6
|
+
if (port >= 0) return port;
|
|
7
|
+
return false;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function createServer(handler, port, name) {
|
|
11
|
+
const dbg = require('debug')('architects:' + name);
|
|
12
|
+
const normalizedPort = normalizePort(port);
|
|
13
|
+
|
|
14
|
+
const server = http.createServer(handler);
|
|
15
|
+
server.listen(normalizedPort);
|
|
16
|
+
|
|
17
|
+
server.on('error', function onError(error) {
|
|
18
|
+
if (error.syscall !== 'listen') throw error;
|
|
19
|
+
const bind = typeof normalizedPort === 'string'
|
|
20
|
+
? 'Pipe ' + normalizedPort
|
|
21
|
+
: 'Port ' + normalizedPort;
|
|
22
|
+
switch (error.code) {
|
|
23
|
+
case 'EACCES':
|
|
24
|
+
console.error(bind + ' requires elevated privileges');
|
|
25
|
+
process.exit(1);
|
|
26
|
+
break;
|
|
27
|
+
case 'EADDRINUSE':
|
|
28
|
+
console.error(bind + ' is already in use');
|
|
29
|
+
process.exit(1);
|
|
30
|
+
break;
|
|
31
|
+
default:
|
|
32
|
+
throw error;
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
server.on('listening', function onListening() {
|
|
37
|
+
const addr = server.address();
|
|
38
|
+
const bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port;
|
|
39
|
+
dbg('Listening on ' + bind);
|
|
40
|
+
console.log(name + ' service listening on ' + bind);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
return server;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
module.exports = { createServer, normalizePort };
|
package/package.json
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@xeplr/base-apis",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Base API bootstrapper — Express and plain HTTP server factories with middleware injection",
|
|
5
|
+
"main": "index.js",
|
|
6
|
+
"files": ["index.js", "lib/", "express.js"],
|
|
7
|
+
"keywords": ["express", "http", "api", "server", "bootstrap", "crud"],
|
|
8
|
+
"author": "xeplr",
|
|
9
|
+
"license": "MIT",
|
|
10
|
+
"repository": { "type": "git", "url": "https://github.com/Xeplr/xeplr-base-apis" },
|
|
11
|
+
"publishConfig": { "access": "public" },
|
|
12
|
+
"dependencies": {
|
|
13
|
+
"cookie-parser": "^1.4.7",
|
|
14
|
+
"cors": "^2.8.6",
|
|
15
|
+
"debug": "^4.4.3",
|
|
16
|
+
"http-errors": "^2.0.1",
|
|
17
|
+
"@xeplr/logs": "^1.0.0"
|
|
18
|
+
},
|
|
19
|
+
"peerDependencies": {
|
|
20
|
+
"express": "^4.0.0 || ^5.0.0"
|
|
21
|
+
}
|
|
22
|
+
}
|