sspart-common-lib 0.0.2
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/common/common.d.ts +8 -0
- package/dist/common/common.js +50 -0
- package/dist/common/cookies.d.ts +1 -0
- package/dist/common/cookies.js +26 -0
- package/dist/common/knex.service.d.ts +2 -0
- package/dist/common/knex.service.js +12 -0
- package/dist/common/password.service.d.ts +2 -0
- package/dist/common/password.service.js +23 -0
- package/dist/common/postgres-service.d.ts +3 -0
- package/dist/common/postgres-service.js +57 -0
- package/dist/common/postgres.service.d.ts +3 -0
- package/dist/common/postgres.service.js +55 -0
- package/dist/common/response.service.d.ts +6 -0
- package/dist/common/response.service.js +42 -0
- package/dist/common/statuscode.d.ts +8 -0
- package/dist/common/statuscode.js +11 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +24 -0
- package/dist/models/base.model.d.ts +12 -0
- package/dist/models/base.model.js +157 -0
- package/dist/models/users.model.d.ts +14 -0
- package/dist/models/users.model.js +11 -0
- package/package.json +24 -0
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export declare const sleep: (ms: number) => Promise<void>;
|
|
2
|
+
export declare const isValidUsername: (username: string) => boolean;
|
|
3
|
+
export declare const validateStringIsValidEmail: (email: string) => boolean;
|
|
4
|
+
export declare const validateStringIsValidNumber: (num: string) => boolean;
|
|
5
|
+
export declare const genRandomString: (len: number) => string;
|
|
6
|
+
export declare const genRandomNumber: (len: number) => string;
|
|
7
|
+
export declare const format: (str: string, ...args: (string | number)[]) => string;
|
|
8
|
+
export declare const createUUID: () => string;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createUUID = exports.format = exports.genRandomNumber = exports.genRandomString = exports.validateStringIsValidNumber = exports.validateStringIsValidEmail = exports.isValidUsername = exports.sleep = void 0;
|
|
4
|
+
const crypto_1 = require("crypto");
|
|
5
|
+
const emailRegex = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/;
|
|
6
|
+
const usernameRegex = /^(?=.*[a-zA-Z])[a-zA-Z0-9]+$/;
|
|
7
|
+
const formatRegex = /{(\d+)}/g;
|
|
8
|
+
const charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
|
9
|
+
const charsetLen = charset.length;
|
|
10
|
+
const numset = "0123456789";
|
|
11
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
12
|
+
exports.sleep = sleep;
|
|
13
|
+
const isValidUsername = (username) => usernameRegex.test(username);
|
|
14
|
+
exports.isValidUsername = isValidUsername;
|
|
15
|
+
const validateStringIsValidEmail = (email) => emailRegex.test(email);
|
|
16
|
+
exports.validateStringIsValidEmail = validateStringIsValidEmail;
|
|
17
|
+
const validateStringIsValidNumber = (num) => {
|
|
18
|
+
if (num.length !== 10)
|
|
19
|
+
return false;
|
|
20
|
+
for (let i = 0; i < 10; i++) {
|
|
21
|
+
const code = num.charCodeAt(i);
|
|
22
|
+
if (code < 48 || code > 57)
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
return true;
|
|
26
|
+
};
|
|
27
|
+
exports.validateStringIsValidNumber = validateStringIsValidNumber;
|
|
28
|
+
const genRandomString = (len) => {
|
|
29
|
+
const bytes = (0, crypto_1.randomBytes)(len);
|
|
30
|
+
let result = "";
|
|
31
|
+
for (let i = 0; i < len; i++) {
|
|
32
|
+
result += charset[bytes[i] % charsetLen];
|
|
33
|
+
}
|
|
34
|
+
return result;
|
|
35
|
+
};
|
|
36
|
+
exports.genRandomString = genRandomString;
|
|
37
|
+
const genRandomNumber = (len) => {
|
|
38
|
+
const arr = new Uint8Array(len);
|
|
39
|
+
crypto_1.webcrypto.getRandomValues(arr);
|
|
40
|
+
let res = "";
|
|
41
|
+
for (let i = 0; i < len; i++) {
|
|
42
|
+
res += numset[arr[i] % 10];
|
|
43
|
+
}
|
|
44
|
+
return res;
|
|
45
|
+
};
|
|
46
|
+
exports.genRandomNumber = genRandomNumber;
|
|
47
|
+
const format = (str, ...args) => str.replace(formatRegex, (_, idx) => { var _a; return ((_a = args[idx]) !== null && _a !== void 0 ? _a : `{${idx}}`) + ""; });
|
|
48
|
+
exports.format = format;
|
|
49
|
+
const createUUID = () => (0, crypto_1.randomUUID)();
|
|
50
|
+
exports.createUUID = createUUID;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const getCookies: (cookieText: string) => Record<string, string>;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getCookies = void 0;
|
|
4
|
+
const getCookies = (cookieText) => {
|
|
5
|
+
if (typeof cookieText !== "string" || !cookieText)
|
|
6
|
+
return {};
|
|
7
|
+
const cookies = {};
|
|
8
|
+
const parts = cookieText.split(";");
|
|
9
|
+
for (let i = 0, len = parts.length; i < len; i++) {
|
|
10
|
+
const eqIdx = parts[i].indexOf("=");
|
|
11
|
+
if (eqIdx === -1)
|
|
12
|
+
continue;
|
|
13
|
+
const name = parts[i].slice(0, eqIdx).trim();
|
|
14
|
+
if (!name)
|
|
15
|
+
continue;
|
|
16
|
+
const value = parts[i].slice(eqIdx + 1).trim();
|
|
17
|
+
try {
|
|
18
|
+
cookies[name] = decodeURIComponent(value);
|
|
19
|
+
}
|
|
20
|
+
catch (_a) {
|
|
21
|
+
cookies[name] = value;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
return cookies;
|
|
25
|
+
};
|
|
26
|
+
exports.getCookies = getCookies;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createKnexClient = void 0;
|
|
4
|
+
const knex_1 = require("knex");
|
|
5
|
+
const createKnexClient = (config) => {
|
|
6
|
+
return (0, knex_1.default)({
|
|
7
|
+
client: 'pg',
|
|
8
|
+
connection: config,
|
|
9
|
+
pool: { min: 1, max: 10 }
|
|
10
|
+
});
|
|
11
|
+
};
|
|
12
|
+
exports.createKnexClient = createKnexClient;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
+
});
|
|
10
|
+
};
|
|
11
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
exports.validateHashedPassword = exports.generateHashedPassword = void 0;
|
|
13
|
+
const bcrypt_1 = require("bcrypt");
|
|
14
|
+
const saltRounds = 10;
|
|
15
|
+
const generateHashedPassword = (myPlaintextPassword) => __awaiter(void 0, void 0, void 0, function* () {
|
|
16
|
+
const salt = yield (0, bcrypt_1.genSalt)(saltRounds);
|
|
17
|
+
return yield (0, bcrypt_1.hash)(myPlaintextPassword, salt);
|
|
18
|
+
});
|
|
19
|
+
exports.generateHashedPassword = generateHashedPassword;
|
|
20
|
+
const validateHashedPassword = (plainTextPassword, hashedPasword) => __awaiter(void 0, void 0, void 0, function* () {
|
|
21
|
+
return yield (0, bcrypt_1.compare)(plainTextPassword, hashedPasword);
|
|
22
|
+
});
|
|
23
|
+
exports.validateHashedPassword = validateHashedPassword;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
+
});
|
|
10
|
+
};
|
|
11
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
exports.getPool = exports.connectWithRetry = void 0;
|
|
13
|
+
// src/common/postgres-service.ts
|
|
14
|
+
const pg_1 = require("pg");
|
|
15
|
+
const dotenv_1 = require("dotenv");
|
|
16
|
+
(0, dotenv_1.config)();
|
|
17
|
+
const dbConfig = {
|
|
18
|
+
host: process.env.PG_HOST || 'localhost',
|
|
19
|
+
user: process.env.PG_USER || 'postgres',
|
|
20
|
+
password: process.env.PG_PASSWORD || '',
|
|
21
|
+
database: process.env.PG_DATABASE || 'test',
|
|
22
|
+
port: Number(process.env.PG_PORT) || 5432,
|
|
23
|
+
max: 10, // connection pool size
|
|
24
|
+
idleTimeoutMillis: 30000,
|
|
25
|
+
};
|
|
26
|
+
let retryCount = 0;
|
|
27
|
+
let pool;
|
|
28
|
+
const connectWithRetry = () => __awaiter(void 0, void 0, void 0, function* () {
|
|
29
|
+
try {
|
|
30
|
+
pool = new pg_1.Pool(dbConfig);
|
|
31
|
+
const client = yield pool.connect();
|
|
32
|
+
yield client.query('SELECT 1');
|
|
33
|
+
client.release();
|
|
34
|
+
console.log(`✅ PostgreSQL connected successfully: ${dbConfig.database}`);
|
|
35
|
+
}
|
|
36
|
+
catch (error) {
|
|
37
|
+
retryCount++;
|
|
38
|
+
console.error(`❌ PostgreSQL connection failed (attempt ${retryCount}). Retrying in 5s...`, error.message);
|
|
39
|
+
setTimeout(exports.connectWithRetry, 5000);
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
exports.connectWithRetry = connectWithRetry;
|
|
43
|
+
process.on('SIGINT', () => __awaiter(void 0, void 0, void 0, function* () {
|
|
44
|
+
console.log('Closing PostgreSQL pool...');
|
|
45
|
+
if (pool)
|
|
46
|
+
yield pool.end();
|
|
47
|
+
console.log('PostgreSQL pool closed');
|
|
48
|
+
process.exit(0);
|
|
49
|
+
}));
|
|
50
|
+
const getPool = () => {
|
|
51
|
+
if (!pool)
|
|
52
|
+
throw new Error('PostgreSQL not connected yet');
|
|
53
|
+
return pool;
|
|
54
|
+
};
|
|
55
|
+
exports.getPool = getPool;
|
|
56
|
+
// Initialize connection
|
|
57
|
+
(0, exports.connectWithRetry)();
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
+
});
|
|
10
|
+
};
|
|
11
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
exports.getPool = exports.connectWithRetry = void 0;
|
|
13
|
+
const pg_1 = require("pg");
|
|
14
|
+
const dotenv_1 = require("dotenv");
|
|
15
|
+
(0, dotenv_1.config)();
|
|
16
|
+
const dbConfig = {
|
|
17
|
+
host: process.env.PG_HOST || 'localhost',
|
|
18
|
+
user: process.env.PG_USER || 'postgres',
|
|
19
|
+
password: process.env.PG_PASSWORD || '',
|
|
20
|
+
database: process.env.PG_DATABASE || 'test',
|
|
21
|
+
port: Number(process.env.PG_PORT) || 5432,
|
|
22
|
+
max: 10,
|
|
23
|
+
idleTimeoutMillis: 30000,
|
|
24
|
+
};
|
|
25
|
+
let retryCount = 0;
|
|
26
|
+
let pool;
|
|
27
|
+
const connectWithRetry = () => __awaiter(void 0, void 0, void 0, function* () {
|
|
28
|
+
try {
|
|
29
|
+
pool = new pg_1.Pool(dbConfig);
|
|
30
|
+
const client = yield pool.connect();
|
|
31
|
+
yield client.query('SELECT 1');
|
|
32
|
+
client.release();
|
|
33
|
+
console.log(`✅ PostgreSQL connected successfully: ${dbConfig.database}`);
|
|
34
|
+
}
|
|
35
|
+
catch (error) {
|
|
36
|
+
retryCount++;
|
|
37
|
+
console.error(`❌ PostgreSQL connection failed (attempt ${retryCount}). Retrying in 5s...`, error.message);
|
|
38
|
+
setTimeout(exports.connectWithRetry, 5000);
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
exports.connectWithRetry = connectWithRetry;
|
|
42
|
+
process.on('SIGINT', () => __awaiter(void 0, void 0, void 0, function* () {
|
|
43
|
+
console.log('Closing PostgreSQL pool...');
|
|
44
|
+
if (pool)
|
|
45
|
+
yield pool.end();
|
|
46
|
+
console.log('PostgreSQL pool closed');
|
|
47
|
+
process.exit(0);
|
|
48
|
+
}));
|
|
49
|
+
const getPool = () => {
|
|
50
|
+
if (!pool)
|
|
51
|
+
throw new Error('PostgreSQL not connected yet');
|
|
52
|
+
return pool;
|
|
53
|
+
};
|
|
54
|
+
exports.getPool = getPool;
|
|
55
|
+
(0, exports.connectWithRetry)();
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export declare const logFailure: (res: any, filename: string, method: string, err: any) => Promise<any>;
|
|
2
|
+
export declare const logFailureWithoutReturn: (filename: string, method: string, err: any) => Promise<void>;
|
|
3
|
+
export declare const sendFailureResponse: (res: any, code: string) => Promise<any>;
|
|
4
|
+
export declare const sendSuccessCode: (res: any, code: string) => Promise<any>;
|
|
5
|
+
export declare const sendSuccessResponse: (res: any, output: string) => Promise<any>;
|
|
6
|
+
export declare const sendSuccessCodeResponse: (res: any, code: string, output: string) => Promise<any>;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
+
});
|
|
10
|
+
};
|
|
11
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
exports.sendSuccessCodeResponse = exports.sendSuccessResponse = exports.sendSuccessCode = exports.sendFailureResponse = exports.logFailureWithoutReturn = exports.logFailure = void 0;
|
|
13
|
+
const statuscode_1 = require("./statuscode");
|
|
14
|
+
const logFailure = (res, filename, method, err) => __awaiter(void 0, void 0, void 0, function* () {
|
|
15
|
+
(0, exports.logFailureWithoutReturn)(filename, method, err);
|
|
16
|
+
return (0, exports.sendFailureResponse)(res, statuscode_1.STATUS_CODES.BAD_REQUEST);
|
|
17
|
+
});
|
|
18
|
+
exports.logFailure = logFailure;
|
|
19
|
+
const logFailureWithoutReturn = (filename, method, err) => __awaiter(void 0, void 0, void 0, function* () {
|
|
20
|
+
console.log(`Error at ${filename}.js>${method}, Error Stack: ${err.stack}, Error Message: ${err.message}`);
|
|
21
|
+
});
|
|
22
|
+
exports.logFailureWithoutReturn = logFailureWithoutReturn;
|
|
23
|
+
const sendFailureResponse = (res, code) => __awaiter(void 0, void 0, void 0, function* () {
|
|
24
|
+
return res.status(200).send({ status: statuscode_1.STATUSES.FAILURE, code });
|
|
25
|
+
});
|
|
26
|
+
exports.sendFailureResponse = sendFailureResponse;
|
|
27
|
+
const sendSuccessCode = (res, code) => __awaiter(void 0, void 0, void 0, function* () {
|
|
28
|
+
return res.status(200).send({ status: statuscode_1.STATUSES.SUCCESS, code });
|
|
29
|
+
});
|
|
30
|
+
exports.sendSuccessCode = sendSuccessCode;
|
|
31
|
+
const sendSuccessResponse = (res, output) => __awaiter(void 0, void 0, void 0, function* () {
|
|
32
|
+
return (0, exports.sendSuccessCodeResponse)(res, statuscode_1.STATUS_CODES.OK, output);
|
|
33
|
+
});
|
|
34
|
+
exports.sendSuccessResponse = sendSuccessResponse;
|
|
35
|
+
const sendSuccessCodeResponse = (res, code, output) => __awaiter(void 0, void 0, void 0, function* () {
|
|
36
|
+
return res.status(200).send({
|
|
37
|
+
status: statuscode_1.STATUSES.SUCCESS,
|
|
38
|
+
code: code,
|
|
39
|
+
output: output
|
|
40
|
+
});
|
|
41
|
+
});
|
|
42
|
+
exports.sendSuccessCodeResponse = sendSuccessCodeResponse;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.STATUSES = exports.STATUS_CODES = void 0;
|
|
4
|
+
exports.STATUS_CODES = {
|
|
5
|
+
OK: "ok",
|
|
6
|
+
BAD_REQUEST: "Something went wrong, please try again later"
|
|
7
|
+
};
|
|
8
|
+
exports.STATUSES = {
|
|
9
|
+
SUCCESS: 'Success',
|
|
10
|
+
FAILURE: 'Failure',
|
|
11
|
+
};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { logFailure, logFailureWithoutReturn, sendFailureResponse, sendSuccessCode, sendSuccessResponse, sendSuccessCodeResponse } from "./common/response.service";
|
|
2
|
+
export { sleep, isValidUsername, validateStringIsValidEmail, validateStringIsValidNumber, genRandomString, genRandomNumber, format, createUUID } from './common/common';
|
|
3
|
+
export { getCookies } from './common/cookies';
|
|
4
|
+
export { generateHashedPassword, validateHashedPassword } from './common/password.service';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.validateHashedPassword = exports.generateHashedPassword = exports.getCookies = exports.createUUID = exports.format = exports.genRandomNumber = exports.genRandomString = exports.validateStringIsValidNumber = exports.validateStringIsValidEmail = exports.isValidUsername = exports.sleep = exports.sendSuccessCodeResponse = exports.sendSuccessResponse = exports.sendSuccessCode = exports.sendFailureResponse = exports.logFailureWithoutReturn = exports.logFailure = void 0;
|
|
4
|
+
var response_service_1 = require("./common/response.service");
|
|
5
|
+
Object.defineProperty(exports, "logFailure", { enumerable: true, get: function () { return response_service_1.logFailure; } });
|
|
6
|
+
Object.defineProperty(exports, "logFailureWithoutReturn", { enumerable: true, get: function () { return response_service_1.logFailureWithoutReturn; } });
|
|
7
|
+
Object.defineProperty(exports, "sendFailureResponse", { enumerable: true, get: function () { return response_service_1.sendFailureResponse; } });
|
|
8
|
+
Object.defineProperty(exports, "sendSuccessCode", { enumerable: true, get: function () { return response_service_1.sendSuccessCode; } });
|
|
9
|
+
Object.defineProperty(exports, "sendSuccessResponse", { enumerable: true, get: function () { return response_service_1.sendSuccessResponse; } });
|
|
10
|
+
Object.defineProperty(exports, "sendSuccessCodeResponse", { enumerable: true, get: function () { return response_service_1.sendSuccessCodeResponse; } });
|
|
11
|
+
var common_1 = require("./common/common");
|
|
12
|
+
Object.defineProperty(exports, "sleep", { enumerable: true, get: function () { return common_1.sleep; } });
|
|
13
|
+
Object.defineProperty(exports, "isValidUsername", { enumerable: true, get: function () { return common_1.isValidUsername; } });
|
|
14
|
+
Object.defineProperty(exports, "validateStringIsValidEmail", { enumerable: true, get: function () { return common_1.validateStringIsValidEmail; } });
|
|
15
|
+
Object.defineProperty(exports, "validateStringIsValidNumber", { enumerable: true, get: function () { return common_1.validateStringIsValidNumber; } });
|
|
16
|
+
Object.defineProperty(exports, "genRandomString", { enumerable: true, get: function () { return common_1.genRandomString; } });
|
|
17
|
+
Object.defineProperty(exports, "genRandomNumber", { enumerable: true, get: function () { return common_1.genRandomNumber; } });
|
|
18
|
+
Object.defineProperty(exports, "format", { enumerable: true, get: function () { return common_1.format; } });
|
|
19
|
+
Object.defineProperty(exports, "createUUID", { enumerable: true, get: function () { return common_1.createUUID; } });
|
|
20
|
+
var cookies_1 = require("./common/cookies");
|
|
21
|
+
Object.defineProperty(exports, "getCookies", { enumerable: true, get: function () { return cookies_1.getCookies; } });
|
|
22
|
+
var password_service_1 = require("./common/password.service");
|
|
23
|
+
Object.defineProperty(exports, "generateHashedPassword", { enumerable: true, get: function () { return password_service_1.generateHashedPassword; } });
|
|
24
|
+
Object.defineProperty(exports, "validateHashedPassword", { enumerable: true, get: function () { return password_service_1.validateHashedPassword; } });
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { QueryResult, QueryResultRow } from 'pg';
|
|
2
|
+
export declare abstract class BaseModel<T extends object> {
|
|
3
|
+
protected tableName: string;
|
|
4
|
+
constructor(tableName: string);
|
|
5
|
+
protected query<R extends QueryResultRow = any>(sql: string, params?: any[]): Promise<QueryResult<R>>;
|
|
6
|
+
insertOne(data: Partial<T>, projection?: string): Promise<T | null>;
|
|
7
|
+
insertMany(data: Partial<T>[], projection?: string): Promise<T[]>;
|
|
8
|
+
find(query?: Partial<T>, columns?: string): Promise<T[]>;
|
|
9
|
+
count(query?: Partial<T>): Promise<number>;
|
|
10
|
+
update(query: Partial<T>, data: Partial<T>, projection?: string): Promise<T[]>;
|
|
11
|
+
delete(query: Partial<T>): Promise<number>;
|
|
12
|
+
}
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
+
});
|
|
10
|
+
};
|
|
11
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
exports.BaseModel = void 0;
|
|
13
|
+
const postgres_service_1 = require("../common/postgres.service");
|
|
14
|
+
class BaseModel {
|
|
15
|
+
constructor(tableName) {
|
|
16
|
+
this.tableName = tableName;
|
|
17
|
+
}
|
|
18
|
+
query(sql_1) {
|
|
19
|
+
return __awaiter(this, arguments, void 0, function* (sql, params = []) {
|
|
20
|
+
const pool = (0, postgres_service_1.getPool)();
|
|
21
|
+
const client = yield pool.connect();
|
|
22
|
+
try {
|
|
23
|
+
return yield client.query(sql, params);
|
|
24
|
+
}
|
|
25
|
+
catch (error) {
|
|
26
|
+
console.error(`${this.tableName} :: Query Failed ::`, error.message, sql, params);
|
|
27
|
+
return { rows: [], rowCount: 0, command: 'ERROR',
|
|
28
|
+
oid: 0, fields: [] };
|
|
29
|
+
}
|
|
30
|
+
finally {
|
|
31
|
+
client.release();
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
insertOne(data_1) {
|
|
36
|
+
return __awaiter(this, arguments, void 0, function* (data, projection = '*') {
|
|
37
|
+
const keys = [];
|
|
38
|
+
const values = [];
|
|
39
|
+
for (const [key, value] of Object.entries(data)) {
|
|
40
|
+
keys.push(key);
|
|
41
|
+
values.push(value);
|
|
42
|
+
}
|
|
43
|
+
const placeholders = keys.map((_, i) => `$${i + 1}`).join(', ');
|
|
44
|
+
const sql = `INSERT INTO ${this.tableName} (${keys.join(', ')})
|
|
45
|
+
VALUES (${placeholders}) RETURNING ${projection}`;
|
|
46
|
+
const result = yield this.query(sql, values);
|
|
47
|
+
return result.rows[0] || null;
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
insertMany(data_1) {
|
|
51
|
+
return __awaiter(this, arguments, void 0, function* (data, projection = '*') {
|
|
52
|
+
if (!data.length)
|
|
53
|
+
return [];
|
|
54
|
+
const keys = Object.keys(data[0]);
|
|
55
|
+
const len = data.length;
|
|
56
|
+
const keyLen = keys.length;
|
|
57
|
+
const values = new Array(len * keyLen);
|
|
58
|
+
const columns = keys.map(k => `"${k}"`).join(', ');
|
|
59
|
+
const placeholderParts = new Array(len);
|
|
60
|
+
let paramIndex = 1;
|
|
61
|
+
let valueIndex = 0;
|
|
62
|
+
for (let i = 0; i < len; i++) {
|
|
63
|
+
const row = data[i];
|
|
64
|
+
const rowParts = new Array(keyLen);
|
|
65
|
+
for (let j = 0; j < keyLen; j++) {
|
|
66
|
+
const val = row[keys[j]];
|
|
67
|
+
values[valueIndex++] = val;
|
|
68
|
+
rowParts[j] = `$${paramIndex++}`;
|
|
69
|
+
}
|
|
70
|
+
placeholderParts[i] = `(${rowParts.join(',')})`;
|
|
71
|
+
}
|
|
72
|
+
const sql = `INSERT INTO ${this.tableName} (${columns}) VALUES ${placeholderParts.join(', ')} RETURNING ${projection};`;
|
|
73
|
+
const res = yield this.query(sql, values);
|
|
74
|
+
return res.rows;
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
find() {
|
|
78
|
+
return __awaiter(this, arguments, void 0, function* (query = {}, columns = '*') {
|
|
79
|
+
const values = [];
|
|
80
|
+
const whereParts = [];
|
|
81
|
+
const entries = Object.entries(query);
|
|
82
|
+
for (let i = 0; i < entries.length; i++) {
|
|
83
|
+
const [key, val] = entries[i];
|
|
84
|
+
whereParts.push(`"${key}" = $${i + 1}`);
|
|
85
|
+
values.push(val);
|
|
86
|
+
}
|
|
87
|
+
const sql = `SELECT ${columns} FROM ${this.tableName}` +
|
|
88
|
+
(whereParts.length ? ' WHERE ' + whereParts.join(' AND ') : '');
|
|
89
|
+
const result = yield this.query(sql, values);
|
|
90
|
+
return result.rows;
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
count() {
|
|
94
|
+
return __awaiter(this, arguments, void 0, function* (query = {}) {
|
|
95
|
+
var _a;
|
|
96
|
+
const values = [];
|
|
97
|
+
const whereParts = [];
|
|
98
|
+
const entries = Object.entries(query);
|
|
99
|
+
for (let i = 0; i < entries.length; i++) {
|
|
100
|
+
const [key, val] = entries[i];
|
|
101
|
+
whereParts.push(`"${key}" = $${i + 1}`);
|
|
102
|
+
values.push(val);
|
|
103
|
+
}
|
|
104
|
+
const sql = `SELECT COUNT(*) AS count FROM ${this.tableName}` +
|
|
105
|
+
(whereParts.length ? ' WHERE ' + whereParts.join(' AND ') : '');
|
|
106
|
+
const result = yield this.query(sql, values);
|
|
107
|
+
return parseInt(((_a = result.rows[0]) === null || _a === void 0 ? void 0 : _a.count) || '0', 10);
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
update(query_1, data_1) {
|
|
111
|
+
return __awaiter(this, arguments, void 0, function* (query, data, projection = '*') {
|
|
112
|
+
const dataKeys = Object.keys(data);
|
|
113
|
+
const queryKeys = Object.keys(query);
|
|
114
|
+
const setLen = dataKeys.length;
|
|
115
|
+
const whereLen = queryKeys.length;
|
|
116
|
+
if (setLen === 0)
|
|
117
|
+
return [];
|
|
118
|
+
const values = new Array(setLen + whereLen);
|
|
119
|
+
const setParts = new Array(setLen);
|
|
120
|
+
const whereParts = whereLen > 0 ? new Array(whereLen) : [];
|
|
121
|
+
for (let i = 0; i < setLen; i++) {
|
|
122
|
+
const key = dataKeys[i];
|
|
123
|
+
setParts[i] = `"${key}" = $${i + 1}`;
|
|
124
|
+
values[i] = data[key];
|
|
125
|
+
}
|
|
126
|
+
const setClause = setParts.join(',');
|
|
127
|
+
if (whereLen > 0) {
|
|
128
|
+
for (let i = 0; i < whereLen; i++) {
|
|
129
|
+
const key = queryKeys[i];
|
|
130
|
+
whereParts[i] = `"${key}" = $${setLen + i + 1}`;
|
|
131
|
+
values[setLen + i] = query[key];
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
const whereClause = whereLen > 0 ? ' WHERE ' + whereParts.join(' AND ') : '';
|
|
135
|
+
const sql = `UPDATE ${this.tableName} SET ${setClause}${whereClause} RETURNING ${projection};`;
|
|
136
|
+
const result = yield this.query(sql, values);
|
|
137
|
+
return result.rows;
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
delete(query) {
|
|
141
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
142
|
+
const values = [];
|
|
143
|
+
const whereParts = [];
|
|
144
|
+
const entries = Object.entries(query);
|
|
145
|
+
for (let i = 0; i < entries.length; i++) {
|
|
146
|
+
const [key, val] = entries[i];
|
|
147
|
+
whereParts.push(`"${key}" = $${i + 1}`);
|
|
148
|
+
values.push(val);
|
|
149
|
+
}
|
|
150
|
+
const sql = `DELETE FROM ${this.tableName}` +
|
|
151
|
+
(whereParts.length ? ' WHERE ' + whereParts.join(' AND ') : '');
|
|
152
|
+
const result = yield this.query(sql, values);
|
|
153
|
+
return result.rowCount || 0;
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
exports.BaseModel = BaseModel;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { BaseModel } from './base.model';
|
|
2
|
+
export interface IUser {
|
|
3
|
+
id?: number;
|
|
4
|
+
username: string;
|
|
5
|
+
name: string;
|
|
6
|
+
status: string;
|
|
7
|
+
subject: string;
|
|
8
|
+
text: string;
|
|
9
|
+
created_at?: Date;
|
|
10
|
+
last_modified?: Date;
|
|
11
|
+
}
|
|
12
|
+
export declare class UserModel extends BaseModel<IUser> {
|
|
13
|
+
constructor();
|
|
14
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.UserModel = void 0;
|
|
4
|
+
// src/models/user.model.ts
|
|
5
|
+
const base_model_1 = require("./base.model");
|
|
6
|
+
class UserModel extends base_model_1.BaseModel {
|
|
7
|
+
constructor() {
|
|
8
|
+
super('users');
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
exports.UserModel = UserModel;
|
package/package.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "sspart-common-lib",
|
|
3
|
+
"version": "0.0.2",
|
|
4
|
+
"description": "",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"type": "commonjs",
|
|
7
|
+
"files": [
|
|
8
|
+
"dist",
|
|
9
|
+
"README.md"
|
|
10
|
+
],
|
|
11
|
+
"scripts": {
|
|
12
|
+
"build": "tsc"
|
|
13
|
+
},
|
|
14
|
+
"author": "",
|
|
15
|
+
"license": "ISC",
|
|
16
|
+
"dependencies": {
|
|
17
|
+
"@types/bcrypt": "^5.0.2",
|
|
18
|
+
"bcrypt": "^5.1.1",
|
|
19
|
+
"dotenv": "^17.2.3"
|
|
20
|
+
},
|
|
21
|
+
"devDependencies": {
|
|
22
|
+
"typescript": "^5.7.2"
|
|
23
|
+
}
|
|
24
|
+
}
|