@lazyapps/express 0.1.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 ADDED
@@ -0,0 +1,15 @@
1
+ ISC License
2
+
3
+ Copyright (c) 2026, Oliver Sturm
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any
6
+ purpose with or without fee is hereby granted, provided that the above
7
+ copyright notice and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
12
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
14
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15
+ PERFORMANCE OF THIS SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,13 @@
1
+ # @lazyapps/express
2
+
3
+ Express HTTP bindings for LazyApps. Provides HTTP command receiver endpoints, read model query endpoints, and change notification listener functionality.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pnpm add @lazyapps/express
9
+ ```
10
+
11
+ ## Part of LazyApps
12
+
13
+ This package is part of the [LazyApps](https://github.com/oliversturm/lazyapps-libs) event-sourcing and CQRS framework.
@@ -0,0 +1,32 @@
1
+ import { getLogger } from '@lazyapps/logger';
2
+
3
+ export const adminHandler = (context) => (req, res) => {
4
+ const { correlationId } = req.body;
5
+ const log = getLogger('EX/CP/AdHandler', correlationId);
6
+
7
+ const { command } = req.params;
8
+ const handler = context.handleAdminCommand;
9
+ if (!handler) {
10
+ log.error(`Invalid admin command ${command}`);
11
+ res.sendStatus(400).send('Invalid admin command');
12
+ return;
13
+ }
14
+
15
+ log.debug(
16
+ `Admin command ${command} with params ${JSON.stringify(req.body.params)}`,
17
+ );
18
+ return handler(
19
+ context,
20
+ command,
21
+ req.body.params,
22
+ req.auth,
23
+ req.body.correlationId,
24
+ )
25
+ .then(() => {
26
+ res.sendStatus(200);
27
+ })
28
+ .catch((err) => {
29
+ log.error(`Error: ${err}`);
30
+ res.sendStatus(500);
31
+ });
32
+ };
@@ -0,0 +1,78 @@
1
+ import { getLogger } from '@lazyapps/logger';
2
+
3
+ export const createApiHandler =
4
+ ({ aggregateStore, eventStore, eventBus, aggregates, handleCommand }) =>
5
+ (req, res) => {
6
+ // Record timestamp as early as possible
7
+ const reqTimestamp = Date.now();
8
+
9
+ const { command, aggregateName, aggregateId, payload, correlationId } =
10
+ req.body;
11
+ const log = getLogger('EX/CP/Handler', correlationId);
12
+ log.debug(
13
+ `Command received: ${JSON.stringify({
14
+ command,
15
+ aggregateName,
16
+ aggregateId,
17
+ payload,
18
+ })}`,
19
+ );
20
+ const auth = req.auth;
21
+ if (!command || !aggregateName || !aggregateId) {
22
+ res.status(400).send('Missing field');
23
+ return;
24
+ }
25
+
26
+ const aggregate = aggregates[aggregateName];
27
+ if (!aggregate) {
28
+ res.status(400).send('Invalid aggregate name');
29
+ return;
30
+ }
31
+
32
+ const commandHandler = aggregate.commands && aggregate.commands[command];
33
+ if (!commandHandler) {
34
+ res.status(400).send('Invalid command name');
35
+ return;
36
+ }
37
+
38
+ return handleCommand(
39
+ aggregateStore,
40
+ eventStore,
41
+ eventBus,
42
+ command,
43
+ aggregateName,
44
+ aggregateId,
45
+ payload,
46
+ commandHandler,
47
+ auth,
48
+ reqTimestamp,
49
+ correlationId,
50
+ )
51
+ .then(() => {
52
+ res.sendStatus(200);
53
+ })
54
+ .catch((err) => {
55
+ if (err.name === 'ValidationError') {
56
+ log.error(`Validation error while handling command ${command} for aggregate ${aggregateName}(${aggregateId}) with payload:
57
+
58
+ ${JSON.stringify(payload)}
59
+
60
+ ${err}`);
61
+ res.sendStatus(400);
62
+ } else if (err.name === 'AuthorizationError') {
63
+ log.error(`Unauthorized while handling command ${command} for aggregate ${aggregateName}(${aggregateId}) with payload:
64
+
65
+ ${JSON.stringify(payload)}
66
+
67
+ ${err}`);
68
+ res.sendStatus(403);
69
+ } else {
70
+ log.error(`Unknown error handling command ${command} for aggregate ${aggregateName}(${aggregateId}) with payload:
71
+
72
+ ${JSON.stringify(payload)}
73
+
74
+ ${err}`);
75
+ res.sendStatus(500);
76
+ }
77
+ });
78
+ };
@@ -0,0 +1,17 @@
1
+ import { createApiHandler } from './command-api-handler.js';
2
+ import { runExpress } from '../runExpress.js';
3
+ import { getLogger } from '@lazyapps/logger';
4
+ import { adminHandler } from './admin-handler.js';
5
+
6
+ const log = getLogger('EX/CP/HTTP', 'INIT');
7
+
8
+ const installHandlers = (context, app) => {
9
+ const processCommand = createApiHandler(context);
10
+ app.post('/api/command', processCommand);
11
+
12
+ // an admin post route for /api/admin/<command>
13
+ app.post('/api/admin/:command', adminHandler(context));
14
+ };
15
+
16
+ export const express = (externalConfig) =>
17
+ runExpress({ log, installHandlers, ...externalConfig });
package/index.js ADDED
File without changes
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@lazyapps/express",
3
+ "version": "0.1.0",
4
+ "description": "Express HTTP bindings for LazyApps command receiver, read model queries, and change notification listener",
5
+ "main": "index.js",
6
+ "exports": {
7
+ ".": "./index.js",
8
+ "./command-receiver": "./command-receiver/index.js",
9
+ "./command-receiver/index.js": "./command-receiver/index.js",
10
+ "./readmodels": "./readmodels/index.js",
11
+ "./readmodels/index.js": "./readmodels/index.js"
12
+ },
13
+ "files": [
14
+ "*.js",
15
+ "command-receiver/",
16
+ "readmodels/"
17
+ ],
18
+ "keywords": [
19
+ "event-sourcing",
20
+ "cqrs",
21
+ "lazyapps",
22
+ "express",
23
+ "http"
24
+ ],
25
+ "author": "Oliver Sturm",
26
+ "license": "ISC",
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "git+https://github.com/oliversturm/lazyapps-libs.git",
30
+ "directory": "packages/express"
31
+ },
32
+ "bugs": {
33
+ "url": "https://github.com/oliversturm/lazyapps-libs/issues"
34
+ },
35
+ "homepage": "https://github.com/oliversturm/lazyapps-libs/tree/main/packages/express#readme",
36
+ "engines": {
37
+ "node": ">=18.20.3 || >=20.18.0"
38
+ },
39
+ "devDependencies": {
40
+ "eslint": "^8.46.0",
41
+ "vitest": "^4.0.18"
42
+ },
43
+ "dependencies": {
44
+ "body-parser": "^1.20.2",
45
+ "cookie-parser": "^1.4.6",
46
+ "cors": "^2.8.5",
47
+ "express": "^4.18.2",
48
+ "express-jwt": "^8.4.1",
49
+ "morgan": "^1.10.0",
50
+ "nanoid": "^5.0.7",
51
+ "@lazyapps/logger": "^0.1.0"
52
+ },
53
+ "type": "module",
54
+ "scripts": {
55
+ "test": "vitest"
56
+ }
57
+ }
@@ -0,0 +1,28 @@
1
+ import { getLogger } from '@lazyapps/logger';
2
+ import { createApiHandler } from './query.js';
3
+ import { runExpress } from '../runExpress.js';
4
+
5
+ const log = getLogger('EX/RM/HTTP', 'INIT');
6
+
7
+ const installHandlers = (context, app) => {
8
+ const executeQuery = createApiHandler(context);
9
+ for (const readModelName in context.readModels) {
10
+ const readModel = context.readModels[readModelName];
11
+ if (readModel.resolvers) {
12
+ for (const resolverName in readModel.resolvers) {
13
+ const resolver = readModel.resolvers[resolverName];
14
+ const handler = executeQuery(
15
+ readModelName,
16
+ readModel,
17
+ resolverName,
18
+ resolver,
19
+ );
20
+ app.post(`/query/${readModelName}/${resolverName}`, handler);
21
+ app.get(`/query/${readModelName}/${resolverName}`, handler);
22
+ }
23
+ }
24
+ }
25
+ };
26
+
27
+ export const express = (externalConfig) =>
28
+ runExpress({ log, installHandlers, ...externalConfig });
@@ -0,0 +1,33 @@
1
+ import { getLogger } from '@lazyapps/logger';
2
+
3
+ export const createApiHandler =
4
+ (context) =>
5
+ (readModelName, readModel, resolverName, resolver) =>
6
+ (req, res) => {
7
+ const log = getLogger('RM/Query', req.body.correlationId);
8
+
9
+ log.debug(
10
+ `Query received for ${readModelName}/${resolverName} with args ${JSON.stringify(
11
+ req.body,
12
+ )}`,
13
+ );
14
+ return Promise.resolve(
15
+ resolver(
16
+ context.storage.perRequest(req.body.correlationId),
17
+ req.body,
18
+ req.auth,
19
+ req.body.correlationId,
20
+ ),
21
+ )
22
+ .then((result) => {
23
+ res.status(200).json(result);
24
+ })
25
+ .catch((err) => {
26
+ log.error(
27
+ `An error occurred handling query for ${readModelName}/${resolverName} with args ${JSON.stringify(
28
+ req.body,
29
+ )}: ${err}`,
30
+ );
31
+ res.sendStatus(500);
32
+ });
33
+ };
package/runExpress.js ADDED
@@ -0,0 +1,120 @@
1
+ import expressApp from 'express';
2
+ import bodyParser from 'body-parser';
3
+ import morgan from 'morgan';
4
+ import cors from 'cors';
5
+ import cookieParser from 'cookie-parser';
6
+ import { expressjwt } from 'express-jwt';
7
+ import { getLogger, getStream } from '@lazyapps/logger';
8
+ import { nanoid } from 'nanoid';
9
+
10
+ const correlationId = (correlationConfig) => (req, res, next) => {
11
+ // check where a correlation Id might already exist
12
+ const existingId = req.body.correlationId || req.headers['x-correlation-id'];
13
+
14
+ // since we want to use it in code, make sure the body
15
+ // now has an id in any case
16
+ req.body.correlationId =
17
+ existingId || `${correlationConfig?.serviceId || 'UNK'}-${nanoid()}`;
18
+
19
+ // also in the result, not needed right now but can't hurt
20
+ // for debugging
21
+ res.setHeader('X-Correlation-ID', req.body.correlationId);
22
+ next();
23
+ };
24
+
25
+ morgan.token('correlation-id', function (req) {
26
+ return req.body.correlationId;
27
+ });
28
+
29
+ export const runExpress =
30
+ ({
31
+ log,
32
+ port,
33
+ interfaceIp,
34
+ installHandlers,
35
+ jwtSecret,
36
+ authCookieName,
37
+ credentialsRequired,
38
+ customizeExpress = () => {},
39
+ }) =>
40
+ (context) => {
41
+ return new Promise((resolve, reject) => {
42
+ const app = expressApp();
43
+ app.use(cors());
44
+ app.use(bodyParser.json());
45
+ app.use(correlationId(context.correlationConfig));
46
+ app.use(
47
+ morgan(
48
+ '[:correlation-id] :method :url :status :response-time ms - :res[content-length]',
49
+ { stream: getStream(log.debugBare) },
50
+ ),
51
+ );
52
+ app.use(cookieParser());
53
+
54
+ if (jwtSecret) {
55
+ app.use(
56
+ expressjwt({
57
+ secret: jwtSecret,
58
+ algorithms: ['HS256'],
59
+ credentialsRequired: credentialsRequired || false,
60
+ getToken: (req) => {
61
+ const tokenLog = getLogger('Tokens/GetT', req.body.correlationId);
62
+ if (
63
+ req.headers.authorization &&
64
+ req.headers.authorization.split(' ')[0] === 'Bearer'
65
+ ) {
66
+ tokenLog.debug('Using Authorization header');
67
+ return req.headers.authorization.split(' ')[1];
68
+ }
69
+ if (authCookieName) {
70
+ const token = req.cookies[authCookieName || 'access_token'];
71
+ if (token) {
72
+ tokenLog.debug('Using cookie');
73
+ return token;
74
+ }
75
+ }
76
+ tokenLog.debug('No token found');
77
+ return null;
78
+ },
79
+ }),
80
+ );
81
+ }
82
+
83
+ installHandlers(context, app);
84
+
85
+ customizeExpress(context, app);
86
+
87
+ // Handle JWT authentication errors
88
+ app.use((err, req, res, next) => {
89
+ if (err.name === 'UnauthorizedError') {
90
+ res.clearCookie(authCookieName || 'access_token', {
91
+ httpOnly: true,
92
+ sameSite: 'strict',
93
+ });
94
+ res.status(401).json({
95
+ error: 'Token expired or invalid',
96
+ code: 'token_expired',
97
+ });
98
+ } else {
99
+ next(err);
100
+ }
101
+ });
102
+
103
+ const server = app.listen(port, interfaceIp || '0.0.0.0');
104
+
105
+ server.on('error', (err) => {
106
+ log.error(`Server error: ${err}`);
107
+ reject(err);
108
+ });
109
+
110
+ server.on('listening', () => {
111
+ const addr = server.address();
112
+ log.info(
113
+ `Server listening on ${addr.address}:${addr.port}, ${
114
+ jwtSecret ? 'with JWT' : 'without JWT'
115
+ }`,
116
+ );
117
+ resolve(server);
118
+ });
119
+ });
120
+ };