powr-sdk-api 2.0.2 → 2.0.3

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.js CHANGED
@@ -14,23 +14,23 @@ const {
14
14
  const {
15
15
  notFoundHandler
16
16
  } = require("./middleware/notfound");
17
- const createSwaggerSpec = require("./swagger");
18
- const logger = require("./logger");
19
17
  const {
20
- createRoutes,
21
- createAdminRoutes,
22
- getAvailableRoutes
23
- } = require("./routes");
18
+ createSwaggerSpec
19
+ } = require("./swagger");
20
+ const {
21
+ cloudLogger
22
+ } = require("./logger");
23
+ const {
24
+ createAdminRoutes
25
+ } = require("./admin");
24
26
  module.exports = {
25
27
  errorCatcher,
26
28
  errorHandler,
27
29
  requestHandler,
28
- logger,
30
+ cloudLogger,
29
31
  createSwaggerSpec,
30
32
  generateToken,
31
33
  validateAuth,
32
34
  notFoundHandler,
33
- createRoutes,
34
- createAdminRoutes,
35
- getAvailableRoutes
35
+ createAdminRoutes
36
36
  };
@@ -3,10 +3,10 @@
3
3
  const winston = require("winston");
4
4
  const {
5
5
  S3Transport
6
- } = require("./s3");
6
+ } = require("../services/s3");
7
7
  const {
8
8
  GCSTransport
9
- } = require("./gcs");
9
+ } = require("../services/gcs");
10
10
 
11
11
  // Custom format for logs
12
12
  const logFormat = winston.format.combine(winston.format.timestamp(), winston.format.errors({
@@ -39,7 +39,7 @@ if (process.env.NODE_ENV === "production") {
39
39
  }
40
40
 
41
41
  // Create the logger
42
- const logger = winston.createLogger({
42
+ const cloudLogger = winston.createLogger({
43
43
  level: process.env.LOG_LEVEL || "info",
44
44
  format: logFormat,
45
45
  defaultMeta: {
@@ -47,4 +47,6 @@ const logger = winston.createLogger({
47
47
  },
48
48
  transports
49
49
  });
50
- module.exports = logger;
50
+ module.exports = {
51
+ cloudLogger
52
+ };
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+
3
+ const jwt = require('jsonwebtoken');
4
+ const {
5
+ config
6
+ } = require('../config');
7
+ const generateJWTToken = user => {
8
+ return jwt.sign({
9
+ userId: user._id,
10
+ username: user.username,
11
+ name: user.name
12
+ }, config.jwtToken, {
13
+ expiresIn: '24h'
14
+ });
15
+ };
16
+ module.exports = {
17
+ generateJWTToken
18
+ };
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+
3
+ const {
4
+ MongoClient
5
+ } = require('mongodb');
6
+
7
+ // Database service with lazy connection
8
+ let client = null;
9
+ let db = null;
10
+ const getDb = async () => {
11
+ // Return existing connection if available
12
+ if (db) {
13
+ return db;
14
+ }
15
+
16
+ // Connect only when first needed
17
+ try {
18
+ const config = require('../config').getConfig();
19
+ client = new MongoClient(config.mongoUri);
20
+ await client.connect();
21
+ db = client.db();
22
+ console.log('✅ Connected to MongoDB via SDK (lazy connection)');
23
+ return db;
24
+ } catch (error) {
25
+ console.error('❌ MongoDB connection error:', error);
26
+ throw error;
27
+ }
28
+ };
29
+ const closeConnection = async () => {
30
+ if (client) {
31
+ await client.close();
32
+ client = null;
33
+ db = null;
34
+ console.log('✅ MongoDB connection closed');
35
+ }
36
+ };
37
+ module.exports = {
38
+ getDb,
39
+ closeConnection
40
+ };
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+
3
+ const winston = require('winston');
4
+ const {
5
+ Storage
6
+ } = require('@google-cloud/storage');
7
+
8
+ // Create GCS client using environment variables for credentials
9
+ const storage = new Storage({
10
+ projectId: process.env.GCS_PROJECT_ID,
11
+ credentials: {
12
+ client_email: process.env.GCS_CLIENT_EMAIL,
13
+ private_key: process.env.GCS_PRIVATE_KEY ? process.env.GCS_PRIVATE_KEY.replace(/\\n/g, '\n') : undefined
14
+ }
15
+ });
16
+
17
+ /**
18
+ * Custom Winston transport for logging to Google Cloud Storage
19
+ */
20
+ class GCSTransport extends winston.Transport {
21
+ constructor(opts) {
22
+ super(opts);
23
+ this.bucket = opts.bucket;
24
+ this.prefix = opts.prefix || '';
25
+ this.buffer = [];
26
+ this.bufferSize = opts.bufferSize || 100;
27
+ this.flushInterval = opts.flushInterval || 5000;
28
+ this.setupFlushInterval();
29
+ }
30
+ setupFlushInterval() {
31
+ setInterval(() => {
32
+ this.flush();
33
+ }, this.flushInterval);
34
+ }
35
+ async flush() {
36
+ if (this.buffer.length === 0) return;
37
+ const logs = this.buffer.splice(0, this.buffer.length);
38
+ const date = new Date().toISOString().split('T')[0];
39
+ const filename = `${this.prefix}/${date}/${Date.now()}.json`;
40
+ try {
41
+ const bucket = storage.bucket(this.bucket);
42
+ const file = bucket.file(filename);
43
+ await file.save(JSON.stringify(logs), {
44
+ contentType: 'application/json',
45
+ metadata: {
46
+ contentType: 'application/json'
47
+ }
48
+ });
49
+ } catch (error) {
50
+ console.error('Failed to write logs to Google Cloud Storage:', {
51
+ error: error.message,
52
+ code: error.code,
53
+ bucket: this.bucket,
54
+ filename: filename,
55
+ projectId: process.env.GCS_PROJECT_ID,
56
+ stack: error.stack
57
+ });
58
+ // Put the logs back in the buffer
59
+ this.buffer.unshift(...logs);
60
+ }
61
+ }
62
+ log(info, callback) {
63
+ setImmediate(() => {
64
+ this.emit('logged', info);
65
+ });
66
+ this.buffer.push({
67
+ timestamp: new Date().toISOString(),
68
+ ...info
69
+ });
70
+ if (this.buffer.length >= this.bufferSize) {
71
+ this.flush();
72
+ }
73
+ callback();
74
+ }
75
+ }
76
+ module.exports = {
77
+ GCSTransport
78
+ };
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+
3
+ // Centralized database service for powr-sdk-api
4
+ // This provides a single connection point for all projects
5
+
6
+ const {
7
+ MongoClient
8
+ } = require('mongodb');
9
+ const {
10
+ config
11
+ } = require('../config');
12
+ let client = null;
13
+ let db = null;
14
+ const connectDB = async () => {
15
+ if (!config.mongoUri) {
16
+ throw new Error('MongoDB connection URL is required. Please provide mongoUrl in createAdminRoutes options.');
17
+ }
18
+ try {
19
+ client = new MongoClient(config.mongoUri);
20
+ await client.connect();
21
+ db = client.db();
22
+ console.log('Connected to MongoDB via SDK');
23
+ } catch (error) {
24
+ console.error('MongoDB connection error:', error);
25
+ throw error;
26
+ }
27
+ };
28
+ const getDb = async () => {
29
+ if (!db) {
30
+ await connectDB();
31
+ }
32
+ return db;
33
+ };
34
+ module.exports = {
35
+ getDb
36
+ };
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+
3
+ const winston = require('winston');
4
+ const {
5
+ S3Client,
6
+ PutObjectCommand
7
+ } = require('@aws-sdk/client-s3');
8
+
9
+ // Create S3 client
10
+ const s3Client = new S3Client({
11
+ region: process.env.AWS_REGION,
12
+ credentials: {
13
+ accessKeyId: process.env.AWS_ACCESS_KEY_ID,
14
+ secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
15
+ }
16
+ });
17
+
18
+ /**
19
+ * Custom Winston transport for logging to S3
20
+ */
21
+ class S3Transport extends winston.Transport {
22
+ constructor(opts) {
23
+ super(opts);
24
+ this.bucket = opts.bucket;
25
+ this.prefix = opts.prefix || '';
26
+ this.buffer = [];
27
+ this.bufferSize = opts.bufferSize || 100;
28
+ this.flushInterval = opts.flushInterval || 5000;
29
+ this.setupFlushInterval();
30
+ }
31
+ setupFlushInterval() {
32
+ setInterval(() => {
33
+ this.flush();
34
+ }, this.flushInterval);
35
+ }
36
+ async flush() {
37
+ if (this.buffer.length === 0) return;
38
+ const logs = this.buffer.splice(0, this.buffer.length);
39
+ const date = new Date().toISOString().split('T')[0];
40
+ const key = `${this.prefix}/${date}/${Date.now()}.json`;
41
+ try {
42
+ const command = new PutObjectCommand({
43
+ Bucket: this.bucket,
44
+ Key: key,
45
+ Body: JSON.stringify(logs),
46
+ ContentType: 'application/json'
47
+ });
48
+ await s3Client.send(command);
49
+ } catch (error) {
50
+ console.error('Failed to write logs to S3:', {
51
+ error: error.message,
52
+ code: error.code,
53
+ bucket: this.bucket,
54
+ key: key,
55
+ region: process.env.AWS_REGION,
56
+ stack: error.stack
57
+ });
58
+ // Put the logs back in the buffer
59
+ this.buffer.unshift(...logs);
60
+ }
61
+ }
62
+ log(info, callback) {
63
+ setImmediate(() => {
64
+ this.emit('logged', info);
65
+ });
66
+ this.buffer.push({
67
+ timestamp: new Date().toISOString(),
68
+ ...info
69
+ });
70
+ if (this.buffer.length >= this.bufferSize) {
71
+ this.flush();
72
+ }
73
+ callback();
74
+ }
75
+ }
76
+ module.exports = {
77
+ S3Transport
78
+ };
@@ -112,4 +112,6 @@ const createSwaggerSpec = (options = {}) => {
112
112
  }
113
113
  return swaggerSpec;
114
114
  };
115
- module.exports = createSwaggerSpec;
115
+ module.exports = {
116
+ createSwaggerSpec
117
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "powr-sdk-api",
3
- "version": "2.0.2",
3
+ "version": "2.0.3",
4
4
  "description": "Shared API core library for PowrStack projects",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",