elseware-nodejs 1.4.0 → 1.5.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.
package/dist/index.d.cts CHANGED
@@ -1,8 +1,9 @@
1
1
  import * as express from 'express';
2
2
  import { Request, Response, NextFunction } from 'express';
3
- import { Model, PopulateOptions, Query, UpdateQuery } from 'mongoose';
3
+ import { Model, PopulateOptions, Query } from 'mongoose';
4
4
  import Joi, { Schema } from 'joi';
5
5
  import { CorsOptions } from 'cors';
6
+ import { SignOptions, JwtPayload } from 'jsonwebtoken';
6
7
 
7
8
  /**
8
9
  * Options for API factory methods
@@ -1859,27 +1860,30 @@ declare const GlobalErrorHandler: (isProd?: boolean) => (err: unknown, _req: Req
1859
1860
 
1860
1861
  declare const validate: (schema: Schema) => (req: Request, _res: Response, next: NextFunction) => void;
1861
1862
 
1862
- /**
1863
- * Generic Base Service
1864
- * Provides default CRUD operations
1865
- */
1866
- declare abstract class BaseService<T> {
1867
- protected model: Model<T>;
1868
- protected resourceName: string;
1869
- constructor(model: Model<T>, resourceName: string);
1870
- create(data: Partial<T>): Promise<T>;
1871
- findAll(): Promise<T[]>;
1872
- findById(id: string): Promise<T>;
1873
- updateById(id: string, data: UpdateQuery<T>): Promise<T>;
1874
- deleteById(id: string): Promise<T>;
1875
- }
1876
-
1877
- interface CrudService<T> {
1878
- create(data: Partial<T>): Promise<T>;
1879
- findAll(): Promise<T[]>;
1880
- findById(id: string): Promise<T>;
1881
- updateById(id: string, data: UpdateQuery<T>): Promise<T>;
1882
- deleteById(id: string): Promise<T>;
1863
+ interface JWTServiceOptions {
1864
+ accessSecret: string;
1865
+ refreshSecret: string;
1866
+ accessExpires?: SignOptions["expiresIn"];
1867
+ refreshExpires?: SignOptions["expiresIn"];
1868
+ nodeEnv?: string;
1869
+ refreshCookieName?: string;
1870
+ }
1871
+ declare class JWTService {
1872
+ private accessSecret;
1873
+ private refreshSecret;
1874
+ private accessExpires;
1875
+ private refreshExpires;
1876
+ private nodeEnv;
1877
+ private refreshCookieName;
1878
+ constructor(options: JWTServiceOptions);
1879
+ createAccessToken(payload: object): string;
1880
+ createRefreshToken(payload: object): string;
1881
+ verifyAccessToken<T extends JwtPayload = JwtPayload>(token: string): T | null;
1882
+ verifyRefreshToken<T extends JwtPayload = JwtPayload>(token: string): T | null;
1883
+ extractToken(req: Request): string | null;
1884
+ setRefreshTokenCookie(res: Response, refreshToken: string): void;
1885
+ clearRefreshTokenCookie(res: Response): void;
1886
+ sendAuthTokens(res: Response, payload: object): string;
1883
1887
  }
1884
1888
 
1885
1889
  declare function errorToString(error: unknown): string;
@@ -1894,4 +1898,4 @@ declare function toMinutes(ms: number): number;
1894
1898
  declare function toHours(ms: number): number;
1895
1899
  declare function sleep(ms: number): Promise<void>;
1896
1900
 
1897
- export { APIFactory, APIFeatures, APIResponse, AVLTree, AdjacencyList, AdjacencyMatrix, type AdjacentEdge, type AllowedOriginsOptions, AppError, type AzureBlobConfig, AzureBlobService, BPlusTree, BTree, BaseService, BinaryHeap, BinarySearchTree, BinaryTree, BloomFilter, CircularArray, CircularLinkedList, CircularQueue, type CloudinaryConfig, CloudinaryService, ConsistentHash, CountMinSketch, type CrudService, type DatabaseConfig, Deque, type DirectedEdge, DirectedGraph, DisjointSetUnion, DoublyLinkedList, DynamicArray, type Edge, FenwickTree, FibNode, FibonacciHeap, GlobalErrorHandler, Graph, HashMap, HashSet, HyperLogLog, type Interval, IntervalTree, KDTree, LFUCache, LRUCache, type LoggerOptions, MaxHeap, MaxStack, MinHeap, MinStack, MultiSet, Node, OrderedSet, PairingHeap, PairingNode, type Point, type Point2D, PriorityQueue, type ProgressCallback, QuadTree, Queue, RadixTree, type Rect, RedBlackTree, SegmentTree, Set, SinglyLinkedList, SparseTable, SplayTree, Stack, StaticArray, SuffixArray, SuffixTree, TernarySearchTree, TreeNode, Trie, type UploadOptions, asyncHandler, authMiddleware, connectMongoDB, createAllowedOrigins, createCorsOptions, days, errorToString, hours, loadEnv, logger, milliseconds, minutes, pickFields, seconds, sleep, toHours, toMinutes, toSeconds, validate };
1901
+ export { APIFactory, APIFeatures, APIResponse, AVLTree, AdjacencyList, AdjacencyMatrix, type AdjacentEdge, type AllowedOriginsOptions, AppError, type AzureBlobConfig, AzureBlobService, BPlusTree, BTree, BinaryHeap, BinarySearchTree, BinaryTree, BloomFilter, CircularArray, CircularLinkedList, CircularQueue, type CloudinaryConfig, CloudinaryService, ConsistentHash, CountMinSketch, type DatabaseConfig, Deque, type DirectedEdge, DirectedGraph, DisjointSetUnion, DoublyLinkedList, DynamicArray, type Edge, FenwickTree, FibNode, FibonacciHeap, GlobalErrorHandler, Graph, HashMap, HashSet, HyperLogLog, type Interval, IntervalTree, JWTService, type JWTServiceOptions, KDTree, LFUCache, LRUCache, type LoggerOptions, MaxHeap, MaxStack, MinHeap, MinStack, MultiSet, Node, OrderedSet, PairingHeap, PairingNode, type Point, type Point2D, PriorityQueue, type ProgressCallback, QuadTree, Queue, RadixTree, type Rect, RedBlackTree, SegmentTree, Set, SinglyLinkedList, SparseTable, SplayTree, Stack, StaticArray, SuffixArray, SuffixTree, TernarySearchTree, TreeNode, Trie, type UploadOptions, asyncHandler, authMiddleware, connectMongoDB, createAllowedOrigins, createCorsOptions, days, errorToString, hours, loadEnv, logger, milliseconds, minutes, pickFields, seconds, sleep, toHours, toMinutes, toSeconds, validate };
package/dist/index.d.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  import * as express from 'express';
2
2
  import { Request, Response, NextFunction } from 'express';
3
- import { Model, PopulateOptions, Query, UpdateQuery } from 'mongoose';
3
+ import { Model, PopulateOptions, Query } from 'mongoose';
4
4
  import Joi, { Schema } from 'joi';
5
5
  import { CorsOptions } from 'cors';
6
+ import { SignOptions, JwtPayload } from 'jsonwebtoken';
6
7
 
7
8
  /**
8
9
  * Options for API factory methods
@@ -1859,27 +1860,30 @@ declare const GlobalErrorHandler: (isProd?: boolean) => (err: unknown, _req: Req
1859
1860
 
1860
1861
  declare const validate: (schema: Schema) => (req: Request, _res: Response, next: NextFunction) => void;
1861
1862
 
1862
- /**
1863
- * Generic Base Service
1864
- * Provides default CRUD operations
1865
- */
1866
- declare abstract class BaseService<T> {
1867
- protected model: Model<T>;
1868
- protected resourceName: string;
1869
- constructor(model: Model<T>, resourceName: string);
1870
- create(data: Partial<T>): Promise<T>;
1871
- findAll(): Promise<T[]>;
1872
- findById(id: string): Promise<T>;
1873
- updateById(id: string, data: UpdateQuery<T>): Promise<T>;
1874
- deleteById(id: string): Promise<T>;
1875
- }
1876
-
1877
- interface CrudService<T> {
1878
- create(data: Partial<T>): Promise<T>;
1879
- findAll(): Promise<T[]>;
1880
- findById(id: string): Promise<T>;
1881
- updateById(id: string, data: UpdateQuery<T>): Promise<T>;
1882
- deleteById(id: string): Promise<T>;
1863
+ interface JWTServiceOptions {
1864
+ accessSecret: string;
1865
+ refreshSecret: string;
1866
+ accessExpires?: SignOptions["expiresIn"];
1867
+ refreshExpires?: SignOptions["expiresIn"];
1868
+ nodeEnv?: string;
1869
+ refreshCookieName?: string;
1870
+ }
1871
+ declare class JWTService {
1872
+ private accessSecret;
1873
+ private refreshSecret;
1874
+ private accessExpires;
1875
+ private refreshExpires;
1876
+ private nodeEnv;
1877
+ private refreshCookieName;
1878
+ constructor(options: JWTServiceOptions);
1879
+ createAccessToken(payload: object): string;
1880
+ createRefreshToken(payload: object): string;
1881
+ verifyAccessToken<T extends JwtPayload = JwtPayload>(token: string): T | null;
1882
+ verifyRefreshToken<T extends JwtPayload = JwtPayload>(token: string): T | null;
1883
+ extractToken(req: Request): string | null;
1884
+ setRefreshTokenCookie(res: Response, refreshToken: string): void;
1885
+ clearRefreshTokenCookie(res: Response): void;
1886
+ sendAuthTokens(res: Response, payload: object): string;
1883
1887
  }
1884
1888
 
1885
1889
  declare function errorToString(error: unknown): string;
@@ -1894,4 +1898,4 @@ declare function toMinutes(ms: number): number;
1894
1898
  declare function toHours(ms: number): number;
1895
1899
  declare function sleep(ms: number): Promise<void>;
1896
1900
 
1897
- export { APIFactory, APIFeatures, APIResponse, AVLTree, AdjacencyList, AdjacencyMatrix, type AdjacentEdge, type AllowedOriginsOptions, AppError, type AzureBlobConfig, AzureBlobService, BPlusTree, BTree, BaseService, BinaryHeap, BinarySearchTree, BinaryTree, BloomFilter, CircularArray, CircularLinkedList, CircularQueue, type CloudinaryConfig, CloudinaryService, ConsistentHash, CountMinSketch, type CrudService, type DatabaseConfig, Deque, type DirectedEdge, DirectedGraph, DisjointSetUnion, DoublyLinkedList, DynamicArray, type Edge, FenwickTree, FibNode, FibonacciHeap, GlobalErrorHandler, Graph, HashMap, HashSet, HyperLogLog, type Interval, IntervalTree, KDTree, LFUCache, LRUCache, type LoggerOptions, MaxHeap, MaxStack, MinHeap, MinStack, MultiSet, Node, OrderedSet, PairingHeap, PairingNode, type Point, type Point2D, PriorityQueue, type ProgressCallback, QuadTree, Queue, RadixTree, type Rect, RedBlackTree, SegmentTree, Set, SinglyLinkedList, SparseTable, SplayTree, Stack, StaticArray, SuffixArray, SuffixTree, TernarySearchTree, TreeNode, Trie, type UploadOptions, asyncHandler, authMiddleware, connectMongoDB, createAllowedOrigins, createCorsOptions, days, errorToString, hours, loadEnv, logger, milliseconds, minutes, pickFields, seconds, sleep, toHours, toMinutes, toSeconds, validate };
1901
+ export { APIFactory, APIFeatures, APIResponse, AVLTree, AdjacencyList, AdjacencyMatrix, type AdjacentEdge, type AllowedOriginsOptions, AppError, type AzureBlobConfig, AzureBlobService, BPlusTree, BTree, BinaryHeap, BinarySearchTree, BinaryTree, BloomFilter, CircularArray, CircularLinkedList, CircularQueue, type CloudinaryConfig, CloudinaryService, ConsistentHash, CountMinSketch, type DatabaseConfig, Deque, type DirectedEdge, DirectedGraph, DisjointSetUnion, DoublyLinkedList, DynamicArray, type Edge, FenwickTree, FibNode, FibonacciHeap, GlobalErrorHandler, Graph, HashMap, HashSet, HyperLogLog, type Interval, IntervalTree, JWTService, type JWTServiceOptions, KDTree, LFUCache, LRUCache, type LoggerOptions, MaxHeap, MaxStack, MinHeap, MinStack, MultiSet, Node, OrderedSet, PairingHeap, PairingNode, type Point, type Point2D, PriorityQueue, type ProgressCallback, QuadTree, Queue, RadixTree, type Rect, RedBlackTree, SegmentTree, Set, SinglyLinkedList, SparseTable, SplayTree, Stack, StaticArray, SuffixArray, SuffixTree, TernarySearchTree, TreeNode, Trie, type UploadOptions, asyncHandler, authMiddleware, connectMongoDB, createAllowedOrigins, createCorsOptions, days, errorToString, hours, loadEnv, logger, milliseconds, minutes, pickFields, seconds, sleep, toHours, toMinutes, toSeconds, validate };
package/dist/index.js CHANGED
@@ -3,6 +3,7 @@ import fs from 'fs';
3
3
  import cloudinaryModule from 'cloudinary';
4
4
  import mongoose from 'mongoose';
5
5
  import dotenv from 'dotenv';
6
+ import jwt from 'jsonwebtoken';
6
7
 
7
8
  // src/errors/appError.ts
8
9
  var AppError = class extends Error {
@@ -5286,51 +5287,96 @@ var validate = (schema) => (req, _res, next) => {
5286
5287
  }
5287
5288
  next();
5288
5289
  };
5289
-
5290
- // src/services/base.service.ts
5291
- var BaseService = class {
5292
- model;
5293
- resourceName;
5294
- constructor(model, resourceName) {
5295
- this.model = model;
5296
- this.resourceName = resourceName;
5297
- }
5298
- async create(data) {
5299
- const doc = await this.model.create(data);
5300
- return doc;
5301
- }
5302
- async findAll() {
5303
- return this.model.find();
5304
- }
5305
- async findById(id) {
5306
- const doc = await this.model.findById(id);
5307
- if (!doc) {
5308
- throw new AppError(`${this.resourceName} not found`, 404, {
5309
- code: `${this.resourceName.toUpperCase()}_NOT_FOUND`
5310
- });
5311
- }
5312
- return doc;
5290
+ var JWTService = class {
5291
+ accessSecret;
5292
+ refreshSecret;
5293
+ accessExpires;
5294
+ refreshExpires;
5295
+ nodeEnv;
5296
+ refreshCookieName;
5297
+ constructor(options) {
5298
+ this.accessSecret = options.accessSecret;
5299
+ this.refreshSecret = options.refreshSecret;
5300
+ this.accessExpires = options.accessExpires || "15m";
5301
+ this.refreshExpires = options.refreshExpires || "30d";
5302
+ this.nodeEnv = options.nodeEnv || "development";
5303
+ this.refreshCookieName = options.refreshCookieName || "refreshJwt";
5304
+ }
5305
+ // ---------------------------------
5306
+ // Access and Refresh Token Creation
5307
+ // ---------------------------------
5308
+ createAccessToken(payload) {
5309
+ return jwt.sign(payload, this.accessSecret, {
5310
+ expiresIn: this.accessExpires
5311
+ });
5313
5312
  }
5314
- async updateById(id, data) {
5315
- const doc = await this.model.findByIdAndUpdate(id, data, {
5316
- new: true,
5317
- runValidators: true
5313
+ createRefreshToken(payload) {
5314
+ return jwt.sign(payload, this.refreshSecret, {
5315
+ expiresIn: this.refreshExpires
5318
5316
  });
5319
- if (!doc) {
5320
- throw new AppError(`${this.resourceName} not found`, 404, {
5321
- code: `${this.resourceName.toUpperCase()}_NOT_FOUND`
5322
- });
5317
+ }
5318
+ // ---------------------------------
5319
+ // Token Verification
5320
+ // ---------------------------------
5321
+ verifyAccessToken(token) {
5322
+ try {
5323
+ return jwt.verify(token, this.accessSecret);
5324
+ } catch (err) {
5325
+ console.error("Access token verification failed:", err.message);
5326
+ return null;
5323
5327
  }
5324
- return doc;
5325
5328
  }
5326
- async deleteById(id) {
5327
- const doc = await this.model.findByIdAndDelete(id);
5328
- if (!doc) {
5329
- throw new AppError(`${this.resourceName} not found`, 404, {
5330
- code: `${this.resourceName.toUpperCase()}_NOT_FOUND`
5331
- });
5329
+ verifyRefreshToken(token) {
5330
+ try {
5331
+ return jwt.verify(token, this.refreshSecret);
5332
+ } catch (err) {
5333
+ console.error("Refresh token verification failed:", err.message);
5334
+ return null;
5332
5335
  }
5333
- return doc;
5336
+ }
5337
+ // ---------------------------------
5338
+ // Token Extraction
5339
+ // ---------------------------------
5340
+ extractToken(req) {
5341
+ if (req.headers.authorization?.startsWith("Bearer ")) {
5342
+ return req.headers.authorization.split(" ")[1];
5343
+ }
5344
+ if (req.cookies?.[this.refreshCookieName]) {
5345
+ return req.cookies[this.refreshCookieName];
5346
+ }
5347
+ if (req.cookies?.jwt) {
5348
+ return req.cookies.jwt;
5349
+ }
5350
+ return null;
5351
+ }
5352
+ // ---------------------------------
5353
+ // Cookie Helpers
5354
+ // ---------------------------------
5355
+ setRefreshTokenCookie(res, refreshToken) {
5356
+ res.cookie(this.refreshCookieName, refreshToken, {
5357
+ httpOnly: true,
5358
+ secure: this.nodeEnv === "production",
5359
+ sameSite: this.nodeEnv === "production" ? "none" : "lax",
5360
+ maxAge: 30 * 24 * 60 * 60 * 1e3,
5361
+ path: "/"
5362
+ });
5363
+ }
5364
+ clearRefreshTokenCookie(res) {
5365
+ res.clearCookie(this.refreshCookieName, {
5366
+ httpOnly: true,
5367
+ secure: this.nodeEnv === "production",
5368
+ sameSite: this.nodeEnv === "production" ? "none" : "lax",
5369
+ path: "/"
5370
+ });
5371
+ }
5372
+ // ---------------------------------
5373
+ // Login Helpers
5374
+ // ---------------------------------
5375
+ sendAuthTokens(res, payload) {
5376
+ const accessToken = this.createAccessToken(payload);
5377
+ const refreshToken = this.createRefreshToken(payload);
5378
+ this.setRefreshTokenCookie(res, refreshToken);
5379
+ return accessToken;
5334
5380
  }
5335
5381
  };
5336
5382
 
@@ -5363,6 +5409,6 @@ function sleep(ms) {
5363
5409
  return new Promise((resolve) => setTimeout(resolve, ms));
5364
5410
  }
5365
5411
 
5366
- export { APIFactory, apiFeatures_default as APIFeatures, APIResponse, AVLTree, AdjacencyList, AdjacencyMatrix, AppError, AzureBlobService, BPlusTree, BTree, BaseService, BinaryHeap, BinarySearchTree, BinaryTree, BloomFilter, CircularArray, CircularLinkedList, CircularQueue, CloudinaryService, ConsistentHash, CountMinSketch, Deque, DirectedGraph, DisjointSetUnion, DoublyLinkedList, DynamicArray, FenwickTree, FibNode, FibonacciHeap, GlobalErrorHandler, Graph, HashMap, HashSet, HyperLogLog, IntervalTree, KDTree, LFUCache, LRUCache, MaxHeap, MaxStack, MinHeap, MinStack, MultiSet, Node, OrderedSet, PairingHeap, PairingNode, PriorityQueue, QuadTree, Queue, RadixTree, RedBlackTree, SegmentTree, Set2 as Set, SinglyLinkedList, SparseTable, SplayTree, Stack, StaticArray, SuffixArray, SuffixTree, TernarySearchTree, TreeNode, Trie, asyncHandler, authMiddleware, connectMongoDB, createAllowedOrigins, createCorsOptions, days, errorToString, hours, loadEnv, logger, milliseconds, minutes, pickFields, seconds, sleep, toHours, toMinutes, toSeconds, validate };
5412
+ export { APIFactory, apiFeatures_default as APIFeatures, APIResponse, AVLTree, AdjacencyList, AdjacencyMatrix, AppError, AzureBlobService, BPlusTree, BTree, BinaryHeap, BinarySearchTree, BinaryTree, BloomFilter, CircularArray, CircularLinkedList, CircularQueue, CloudinaryService, ConsistentHash, CountMinSketch, Deque, DirectedGraph, DisjointSetUnion, DoublyLinkedList, DynamicArray, FenwickTree, FibNode, FibonacciHeap, GlobalErrorHandler, Graph, HashMap, HashSet, HyperLogLog, IntervalTree, JWTService, KDTree, LFUCache, LRUCache, MaxHeap, MaxStack, MinHeap, MinStack, MultiSet, Node, OrderedSet, PairingHeap, PairingNode, PriorityQueue, QuadTree, Queue, RadixTree, RedBlackTree, SegmentTree, Set2 as Set, SinglyLinkedList, SparseTable, SplayTree, Stack, StaticArray, SuffixArray, SuffixTree, TernarySearchTree, TreeNode, Trie, asyncHandler, authMiddleware, connectMongoDB, createAllowedOrigins, createCorsOptions, days, errorToString, hours, loadEnv, logger, milliseconds, minutes, pickFields, seconds, sleep, toHours, toMinutes, toSeconds, validate };
5367
5413
  //# sourceMappingURL=index.js.map
5368
5414
  //# sourceMappingURL=index.js.map