opticedge-cloud-utils 1.0.2 → 1.0.4

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.
@@ -0,0 +1,3 @@
1
+ import { Collection, Document } from 'mongodb';
2
+ export declare function connectToMongo(projectId: string, uriSecret: string, dbName: string): Promise<void>;
3
+ export declare function getCollection<T extends Document = Document>(name: string): Collection<T>;
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.connectToMongo = connectToMongo;
4
+ exports.getCollection = getCollection;
5
+ const mongodb_1 = require("mongodb");
6
+ const secrets_1 = require("../utils/secrets"); // reuse your secret manager util
7
+ let client;
8
+ let db;
9
+ async function connectToMongo(projectId, uriSecret, dbName) {
10
+ if (client)
11
+ return;
12
+ const uri = await (0, secrets_1.getSecret)(projectId, uriSecret);
13
+ client = new mongodb_1.MongoClient(uri);
14
+ await client.connect();
15
+ db = client.db(dbName); // or pass DB name if needed
16
+ }
17
+ function getCollection(name) {
18
+ if (!db)
19
+ throw new Error('Mongo not initialized');
20
+ return db.collection(name);
21
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,72 @@
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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ const mongo_1 = require("./mongo");
37
+ const mongodb_1 = require("mongodb");
38
+ const secretsModule = __importStar(require("../utils/secrets"));
39
+ jest.mock('mongodb');
40
+ jest.mock('../utils/secrets');
41
+ const mockDb = {
42
+ collection: jest.fn(),
43
+ };
44
+ const mockConnect = jest.fn();
45
+ const mockClient = {
46
+ connect: mockConnect,
47
+ db: jest.fn().mockReturnValue(mockDb),
48
+ };
49
+ beforeEach(() => {
50
+ jest.clearAllMocks();
51
+ secretsModule.getSecret.mockResolvedValue('mongodb://mock-uri');
52
+ mongodb_1.MongoClient.mockImplementation(() => mockClient);
53
+ });
54
+ describe('Mongo Utils', () => {
55
+ it('should connect to MongoDB and store client/db', async () => {
56
+ await (0, mongo_1.connectToMongo)('test-project', 'mongo-uri-secret', 'test-db');
57
+ expect(secretsModule.getSecret).toHaveBeenCalledWith('test-project', 'mongo-uri-secret');
58
+ expect(mockConnect).toHaveBeenCalled();
59
+ expect(mockClient.db).toHaveBeenCalledWith('test-db');
60
+ });
61
+ it('should return a collection when db is initialized', async () => {
62
+ await (0, mongo_1.connectToMongo)('test-project', 'mongo-uri-secret', 'test-db');
63
+ (0, mongo_1.getCollection)('users');
64
+ expect(mockDb.collection).toHaveBeenCalledWith('users');
65
+ });
66
+ it('should throw error if db is not initialized', () => {
67
+ jest.isolateModules(() => {
68
+ const { getCollection } = require('./mongo');
69
+ expect(() => getCollection('users')).toThrow('Mongo not initialized');
70
+ });
71
+ });
72
+ });
package/dist/index.d.ts CHANGED
@@ -1 +1,3 @@
1
1
  export * from './auth/verify';
2
+ export * from './utils/secrets';
3
+ export * from './db/mongo';
package/dist/index.js CHANGED
@@ -15,3 +15,5 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./auth/verify"), exports);
18
+ __exportStar(require("./utils/secrets"), exports);
19
+ __exportStar(require("./db/mongo"), exports);
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Returns the latest value of a Secret Manager secret.
3
+ *
4
+ * @param projectId – GCP project that owns the secret.
5
+ * @param secretName – Secret name (without version).
6
+ * @returns – UTF-8 string value.
7
+ */
8
+ export declare function getSecret(projectId: string, secretName: string): Promise<string>;
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getSecret = getSecret;
4
+ const secret_manager_1 = require("@google-cloud/secret-manager");
5
+ /**
6
+ * Returns the latest value of a Secret Manager secret.
7
+ *
8
+ * @param projectId – GCP project that owns the secret.
9
+ * @param secretName – Secret name (without version).
10
+ * @returns – UTF-8 string value.
11
+ */
12
+ async function getSecret(projectId, secretName) {
13
+ if (!projectId)
14
+ throw new Error('projectId is required');
15
+ if (!secretName)
16
+ throw new Error('secretName is required');
17
+ const secretClient = new secret_manager_1.SecretManagerServiceClient();
18
+ const [version] = await secretClient.accessSecretVersion({
19
+ name: `projects/${projectId}/secrets/${secretName}/versions/latest`,
20
+ });
21
+ return version.payload?.data?.toString('utf-8') ?? '';
22
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const secrets_1 = require("./secrets");
4
+ const secret_manager_1 = require("@google-cloud/secret-manager");
5
+ jest.mock('@google-cloud/secret-manager');
6
+ // Mock implementation
7
+ const mockAccessSecretVersion = jest.fn();
8
+ secret_manager_1.SecretManagerServiceClient.mockImplementation(() => ({
9
+ accessSecretVersion: mockAccessSecretVersion,
10
+ }));
11
+ describe('getSecret', () => {
12
+ beforeEach(() => {
13
+ jest.clearAllMocks();
14
+ });
15
+ it('returns secret value as string', async () => {
16
+ mockAccessSecretVersion.mockResolvedValue([
17
+ {
18
+ payload: { data: Buffer.from('super-secret-value') },
19
+ },
20
+ ]);
21
+ const result = await (0, secrets_1.getSecret)('test-project', 'test-secret');
22
+ expect(result).toBe('super-secret-value');
23
+ expect(mockAccessSecretVersion).toHaveBeenCalledWith({
24
+ name: 'projects/test-project/secrets/test-secret/versions/latest',
25
+ });
26
+ });
27
+ it('throws if projectId is missing', async () => {
28
+ await expect((0, secrets_1.getSecret)('', 'secret')).rejects.toThrow('projectId is required');
29
+ });
30
+ it('throws if secretName is missing', async () => {
31
+ await expect((0, secrets_1.getSecret)('project', '')).rejects.toThrow('secretName is required');
32
+ });
33
+ it('returns empty string if payload or data is missing', async () => {
34
+ mockAccessSecretVersion.mockResolvedValue([{}]); // no payload
35
+ const result = await (0, secrets_1.getSecret)('project', 'secret');
36
+ expect(result).toBe('');
37
+ });
38
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opticedge-cloud-utils",
3
- "version": "1.0.2",
3
+ "version": "1.0.4",
4
4
  "description": "Common utilities for cloud functions",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -13,7 +13,9 @@
13
13
  "author": "Evans Musonda",
14
14
  "license": "MIT",
15
15
  "dependencies": {
16
- "google-auth-library": "^9.15.1"
16
+ "@google-cloud/secret-manager": "^6.0.1",
17
+ "google-auth-library": "^9.15.1",
18
+ "mongodb": "^6.16.0"
17
19
  },
18
20
  "devDependencies": {
19
21
  "@google-cloud/functions-framework": "^4.0.0",
@@ -0,0 +1,46 @@
1
+ import { connectToMongo, getCollection } from './mongo';
2
+ import { MongoClient, Db, Collection } from 'mongodb';
3
+ import * as secretsModule from '../utils/secrets';
4
+
5
+ jest.mock('mongodb');
6
+ jest.mock('../utils/secrets');
7
+
8
+ const mockDb = {
9
+ collection: jest.fn(),
10
+ } as unknown as Db;
11
+
12
+ const mockConnect = jest.fn();
13
+ const mockClient = {
14
+ connect: mockConnect,
15
+ db: jest.fn().mockReturnValue(mockDb),
16
+ } as unknown as MongoClient;
17
+
18
+ beforeEach(() => {
19
+ jest.clearAllMocks();
20
+ (secretsModule.getSecret as jest.Mock).mockResolvedValue('mongodb://mock-uri');
21
+ (MongoClient as unknown as jest.Mock).mockImplementation(() => mockClient);
22
+ });
23
+
24
+ describe('Mongo Utils', () => {
25
+ it('should connect to MongoDB and store client/db', async () => {
26
+ await connectToMongo('test-project', 'mongo-uri-secret', 'test-db');
27
+
28
+ expect(secretsModule.getSecret).toHaveBeenCalledWith('test-project', 'mongo-uri-secret');
29
+ expect(mockConnect).toHaveBeenCalled();
30
+ expect(mockClient.db).toHaveBeenCalledWith('test-db');
31
+ });
32
+
33
+ it('should return a collection when db is initialized', async () => {
34
+ await connectToMongo('test-project', 'mongo-uri-secret', 'test-db');
35
+ getCollection('users');
36
+
37
+ expect(mockDb.collection).toHaveBeenCalledWith('users');
38
+ });
39
+
40
+ it('should throw error if db is not initialized', () => {
41
+ jest.isolateModules(() => {
42
+ const { getCollection } = require('./mongo');
43
+ expect(() => getCollection('users')).toThrow('Mongo not initialized');
44
+ });
45
+ });
46
+ });
@@ -0,0 +1,19 @@
1
+ import { MongoClient, Db, Collection, Document } from 'mongodb';
2
+ import { getSecret } from '../utils/secrets'; // reuse your secret manager util
3
+
4
+ let client: MongoClient;
5
+ let db: Db;
6
+
7
+ export async function connectToMongo(projectId: string, uriSecret: string, dbName: string) {
8
+ if (client) return;
9
+
10
+ const uri = await getSecret(projectId, uriSecret);
11
+ client = new MongoClient(uri);
12
+ await client.connect();
13
+ db = client.db(dbName); // or pass DB name if needed
14
+ }
15
+
16
+ export function getCollection<T extends Document = Document>(name: string): Collection<T> {
17
+ if (!db) throw new Error('Mongo not initialized');
18
+ return db.collection<T>(name);
19
+ }
package/src/index.ts CHANGED
@@ -1 +1,3 @@
1
- export * from './auth/verify';
1
+ export * from './auth/verify';
2
+ export * from './utils/secrets';
3
+ export * from './db/mongo';
@@ -0,0 +1,44 @@
1
+ import { getSecret } from './secrets';
2
+ import { SecretManagerServiceClient } from '@google-cloud/secret-manager';
3
+
4
+ jest.mock('@google-cloud/secret-manager');
5
+
6
+ // Mock implementation
7
+ const mockAccessSecretVersion = jest.fn();
8
+ (SecretManagerServiceClient as unknown as jest.Mock).mockImplementation(() => ({
9
+ accessSecretVersion: mockAccessSecretVersion,
10
+ }));
11
+
12
+ describe('getSecret', () => {
13
+ beforeEach(() => {
14
+ jest.clearAllMocks();
15
+ });
16
+
17
+ it('returns secret value as string', async () => {
18
+ mockAccessSecretVersion.mockResolvedValue([
19
+ {
20
+ payload: { data: Buffer.from('super-secret-value') },
21
+ },
22
+ ]);
23
+
24
+ const result = await getSecret('test-project', 'test-secret');
25
+ expect(result).toBe('super-secret-value');
26
+ expect(mockAccessSecretVersion).toHaveBeenCalledWith({
27
+ name: 'projects/test-project/secrets/test-secret/versions/latest',
28
+ });
29
+ });
30
+
31
+ it('throws if projectId is missing', async () => {
32
+ await expect(getSecret('', 'secret')).rejects.toThrow('projectId is required');
33
+ });
34
+
35
+ it('throws if secretName is missing', async () => {
36
+ await expect(getSecret('project', '')).rejects.toThrow('secretName is required');
37
+ });
38
+
39
+ it('returns empty string if payload or data is missing', async () => {
40
+ mockAccessSecretVersion.mockResolvedValue([{}]); // no payload
41
+ const result = await getSecret('project', 'secret');
42
+ expect(result).toBe('');
43
+ });
44
+ });
@@ -0,0 +1,24 @@
1
+ import { SecretManagerServiceClient } from '@google-cloud/secret-manager';
2
+
3
+ /**
4
+ * Returns the latest value of a Secret Manager secret.
5
+ *
6
+ * @param projectId – GCP project that owns the secret.
7
+ * @param secretName – Secret name (without version).
8
+ * @returns – UTF-8 string value.
9
+ */
10
+ export async function getSecret(
11
+ projectId: string,
12
+ secretName: string
13
+ ): Promise<string> {
14
+ if (!projectId) throw new Error('projectId is required');
15
+ if (!secretName) throw new Error('secretName is required');
16
+
17
+ const secretClient = new SecretManagerServiceClient();
18
+
19
+ const [version] = await secretClient.accessSecretVersion({
20
+ name: `projects/${projectId}/secrets/${secretName}/versions/latest`,
21
+ });
22
+
23
+ return (version.payload?.data as Buffer)?.toString('utf-8') ?? '';
24
+ }