@diamir/nestjs-maintenance 11.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 ADDED
@@ -0,0 +1,6 @@
1
+ Copyright 2025 WEB&SÖHNE<backend@diamir.io>
2
+
3
+ Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
4
+
5
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
6
+
package/README.md ADDED
@@ -0,0 +1,75 @@
1
+ <p align="center">
2
+ <a href="https://webundsoehne.com" target="blank">
3
+ <img src="https://webundsoehne.com/wp-content/uploads/webundsoehne-logo.png" width="320" alt="Web und Söhne - Logo" />
4
+ </a>
5
+ </p>
6
+ Web & Söhne is Austria's leading expert in programming and implementing complex and large web projects.
7
+
8
+ ---
9
+
10
+ # nestjs-maintenance
11
+
12
+ <!-- TOC -->
13
+ * [nestjs-maintenance](#nestjs-maintenance)
14
+ * [Description](#description)
15
+ * [Usage](#usage)
16
+ * [MaintenanceService](#maintenanceservice)
17
+ * [Decorator](#decorator)
18
+ * [Migration](#migration)
19
+ <!-- TOC -->
20
+
21
+ ## Description
22
+
23
+ The maintenance module gives you the possibility to generate and remove a lock file,
24
+ as well as checking if the lock file exists and throwing a preconfigured `ServiceUnavailableException` error.
25
+
26
+ You may use the maintenance module anywhere in your project, e.g. for database migrations. (But make sure to access the same lock-file in each module)
27
+
28
+ ## Usage
29
+
30
+ Set up the `MaintenanceModule` and `MaintenanceMiddleware` in the server/application module.
31
+
32
+ ```typescript
33
+ import { MiddlewareConsumer, Module, NestModule, RequestMethod } from '@nestjs/common'
34
+ import { MaintenanceMiddleware, MaintenanceModule } from '@diamir/nestjs-maintenance'
35
+
36
+ @Module({
37
+ imports: [
38
+ MaintenanceModule.forRoot({
39
+ application: ConfigService.get('url.basePath'), // default: Application
40
+ lockfilePath: ConfigService.get('misc.lockfile') // default: maintenance.lock
41
+ })
42
+ ]
43
+ })
44
+ class ServerModule implements NestModule {
45
+ async configure(consumer: MiddlewareConsumer): Promise<any> {
46
+ consumer.apply(MaintenanceMiddleware).forRoutes({ path: '*', method: RequestMethod.ALL })
47
+ }
48
+ }
49
+ ```
50
+
51
+ Now if a lockfile is present at the `lockfilePath`, the `ServiceUnavailableException` will be thrown.
52
+
53
+ ### MaintenanceService
54
+
55
+ To create and remove the lockfile, use the `MaintenanceService` in any module.
56
+
57
+ | Name | Return | Description |
58
+ |----------------|---------|---------------------------------------|
59
+ | enable | void | Create the configured lock file |
60
+ | disable | void | Remove the generated lock file |
61
+ | isEnabled | Boolean | Check if there is already a lock file |
62
+ | throwException | void | Throw the preconfigured exception |
63
+
64
+ ### Decorator
65
+
66
+ Apply the `@UseMaintenanceLocker()` decorator on a method to wrap the original function inside a maintenance-lock
67
+ 1. enable lock
68
+ 2. execute method
69
+ 3. disable lock
70
+
71
+ ## Migration
72
+
73
+ To migrate from the old `@webundsoehne/nestjs-util` to `@diamir/nestjs-maintenance`:
74
+ - replace the imports
75
+ - change the `MaintenanceModule` imports to use the `.forRoot` method
package/package.json ADDED
@@ -0,0 +1,23 @@
1
+ {
2
+ "name": "@diamir/nestjs-maintenance",
3
+ "version": "11.0.0",
4
+ "description": "",
5
+ "author": "Backend <backend@diamir.io>",
6
+ "repository": "https://github.com/tailoredmedia/backend-nx-skeleton",
7
+ "license": "ISC",
8
+ "publishConfig": {
9
+ "access": "public"
10
+ },
11
+ "keywords": [],
12
+ "main": "./src/index.js",
13
+ "dependencies": {},
14
+ "peerDependencies": {
15
+ "@nestjs/common": ">= 11.0.0"
16
+ },
17
+ "peerDependenciesMeta": {},
18
+ "engines": {
19
+ "node": ">= 20"
20
+ },
21
+ "types": "./src/index.d.ts",
22
+ "type": "commonjs"
23
+ }
@@ -0,0 +1,2 @@
1
+ export * from './inject.decorator';
2
+ export * from './locker.decorator';
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./inject.decorator"), exports);
18
+ __exportStar(require("./locker.decorator"), exports);
@@ -0,0 +1 @@
1
+ export declare function InjectMaintenanceService(): PropertyDecorator & ParameterDecorator;
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.InjectMaintenanceService = InjectMaintenanceService;
4
+ const common_1 = require("@nestjs/common");
5
+ const maintenance_service_1 = require("../maintenance.service");
6
+ function InjectMaintenanceService() {
7
+ return (0, common_1.Inject)(maintenance_service_1.MaintenanceService);
8
+ }
@@ -0,0 +1 @@
1
+ export declare function UseMaintenanceLocker(): MethodDecorator;
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.UseMaintenanceLocker = UseMaintenanceLocker;
4
+ const inject_decorator_1 = require("./inject.decorator");
5
+ function UseMaintenanceLocker() {
6
+ return (target, propertyKey, descriptor) => {
7
+ const originalFn = descriptor.value;
8
+ (0, inject_decorator_1.InjectMaintenanceService)()(target, 'LOCKER_MAINTENANCE_SERVICE');
9
+ descriptor.value = async function (...args) {
10
+ const service = this.LOCKER_MAINTENANCE_SERVICE;
11
+ await service.enable(propertyKey);
12
+ try {
13
+ const result = await originalFn.apply(this, args);
14
+ await service.disable(propertyKey);
15
+ return result;
16
+ }
17
+ catch (err) {
18
+ await service.disable(propertyKey);
19
+ throw err;
20
+ }
21
+ };
22
+ return descriptor;
23
+ };
24
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ export * from './decorators';
2
+ export * from './interface';
3
+ export * from './maintenance.middleware';
4
+ export * from './maintenance.module';
5
+ export * from './maintenance.service';
package/src/index.js ADDED
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./decorators"), exports);
18
+ __exportStar(require("./interface"), exports);
19
+ __exportStar(require("./maintenance.middleware"), exports);
20
+ __exportStar(require("./maintenance.module"), exports);
21
+ __exportStar(require("./maintenance.service"), exports);
@@ -0,0 +1 @@
1
+ export * from './maintenance-options.interface';
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./maintenance-options.interface"), exports);
@@ -0,0 +1,4 @@
1
+ export interface MaintenanceOptions {
2
+ application?: string;
3
+ lockfilePath?: string;
4
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,7 @@
1
+ import type { NestMiddleware } from '@nestjs/common';
2
+ import { MaintenanceService } from './maintenance.service';
3
+ export declare class MaintenanceMiddleware implements NestMiddleware {
4
+ private readonly service;
5
+ constructor(service: MaintenanceService);
6
+ use(_req: never, _res: never, next: (err?: any) => unknown): Promise<void>;
7
+ }
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.MaintenanceMiddleware = void 0;
16
+ const common_1 = require("@nestjs/common");
17
+ const maintenance_service_1 = require("./maintenance.service");
18
+ let MaintenanceMiddleware = class MaintenanceMiddleware {
19
+ service;
20
+ constructor(service) {
21
+ this.service = service;
22
+ }
23
+ async use(_req, _res, next) {
24
+ if (await this.service.isEnabled()) {
25
+ this.service.throwException();
26
+ }
27
+ next();
28
+ }
29
+ };
30
+ exports.MaintenanceMiddleware = MaintenanceMiddleware;
31
+ exports.MaintenanceMiddleware = MaintenanceMiddleware = __decorate([
32
+ __param(0, (0, common_1.Inject)(maintenance_service_1.MaintenanceService)),
33
+ __metadata("design:paramtypes", [maintenance_service_1.MaintenanceService])
34
+ ], MaintenanceMiddleware);
@@ -0,0 +1,5 @@
1
+ import { type DynamicModule } from '@nestjs/common';
2
+ import type { MaintenanceOptions } from './interface';
3
+ export declare class MaintenanceModule {
4
+ static forRoot(options?: MaintenanceOptions): DynamicModule;
5
+ }
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var MaintenanceModule_1;
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.MaintenanceModule = void 0;
11
+ const common_1 = require("@nestjs/common");
12
+ const maintenance_service_1 = require("./maintenance.service");
13
+ let MaintenanceModule = MaintenanceModule_1 = class MaintenanceModule {
14
+ static forRoot(options) {
15
+ return {
16
+ global: true,
17
+ module: MaintenanceModule_1,
18
+ providers: [
19
+ {
20
+ provide: maintenance_service_1.MaintenanceService,
21
+ useValue: new maintenance_service_1.MaintenanceService(options)
22
+ }
23
+ ],
24
+ exports: [maintenance_service_1.MaintenanceService]
25
+ };
26
+ }
27
+ };
28
+ exports.MaintenanceModule = MaintenanceModule;
29
+ exports.MaintenanceModule = MaintenanceModule = MaintenanceModule_1 = __decorate([
30
+ (0, common_1.Module)({})
31
+ ], MaintenanceModule);
@@ -0,0 +1,13 @@
1
+ import type { MaintenanceOptions } from './interface';
2
+ export declare class MaintenanceService {
3
+ static instance: MaintenanceService;
4
+ readonly message: string;
5
+ private readonly logger;
6
+ private readonly lockfile;
7
+ private readonly tasks;
8
+ constructor(options?: MaintenanceOptions);
9
+ enable(task?: string): Promise<void>;
10
+ disable(task?: string): Promise<void>;
11
+ isEnabled(): Promise<boolean>;
12
+ throwException(): void;
13
+ }
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ var MaintenanceService_1;
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.MaintenanceService = void 0;
17
+ const promises_1 = require("node:fs/promises");
18
+ const node_path_1 = require("node:path");
19
+ const common_1 = require("@nestjs/common");
20
+ let MaintenanceService = class MaintenanceService {
21
+ static { MaintenanceService_1 = this; }
22
+ static instance;
23
+ message;
24
+ logger = new common_1.Logger(this.constructor.name);
25
+ lockfile;
26
+ tasks = [];
27
+ constructor(options) {
28
+ if (!MaintenanceService_1.instance) {
29
+ this.message = `${options?.application ?? process.env.PACKAGE_NAME ?? 'Application'} is currently down for maintenance`;
30
+ this.lockfile = (0, node_path_1.resolve)(options?.lockfilePath ?? 'maintenance.lock');
31
+ MaintenanceService_1.instance = this;
32
+ }
33
+ }
34
+ async enable(task = 'unknown-task') {
35
+ this.tasks.push(task);
36
+ this.logger.debug(`Task added to maintenance queue: ${task}`);
37
+ if (!(await this.isEnabled())) {
38
+ this.logger.verbose(`Enabling maintenance mode (lockfile is ${this.lockfile})`);
39
+ await (0, promises_1.writeFile)(this.lockfile, '', { encoding: 'utf8' });
40
+ this.logger.log('◆◆◆ Maintenance mode enabled ◆◆◆');
41
+ return;
42
+ }
43
+ this.logger.verbose('Maintenance mode already enabled.');
44
+ }
45
+ async disable(task = 'unknown-task') {
46
+ this.tasks.splice(this.tasks.indexOf(task), 1);
47
+ if (this.tasks.length === 0) {
48
+ this.logger.verbose(`Disabling maintenance mode (lockfile is ${this.lockfile})`);
49
+ try {
50
+ await (0, promises_1.rm)(this.lockfile);
51
+ }
52
+ catch (_) {
53
+ this.logger.debug(`Lockfile was already missing: ${this.lockfile}`);
54
+ }
55
+ this.logger.log('◆◆◆ Maintenance mode disabled ◆◆◆');
56
+ return;
57
+ }
58
+ this.logger.verbose(`Not disabling maintenance mode still got running tasks: ${this.tasks.join(', ')}`);
59
+ }
60
+ async isEnabled() {
61
+ try {
62
+ await (0, promises_1.access)(this.lockfile);
63
+ }
64
+ catch (_error) {
65
+ return false;
66
+ }
67
+ return true;
68
+ }
69
+ throwException() {
70
+ throw new common_1.ServiceUnavailableException(this.message);
71
+ }
72
+ };
73
+ exports.MaintenanceService = MaintenanceService;
74
+ exports.MaintenanceService = MaintenanceService = MaintenanceService_1 = __decorate([
75
+ (0, common_1.Injectable)(),
76
+ __param(0, (0, common_1.Optional)()),
77
+ __metadata("design:paramtypes", [Object])
78
+ ], MaintenanceService);