streamby-core 0.20.1 → 0.21.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.
Files changed (42) hide show
  1. package/dist/adapters/database/connectionManager.d.ts +5 -1
  2. package/dist/adapters/database/connectionManager.js +66 -10
  3. package/dist/adapters/database/nosql.d.ts +1 -0
  4. package/dist/adapters/database/nosql.js +15 -1
  5. package/dist/adapters/database/sql.js +7 -3
  6. package/dist/middleware/createRouter.js +23 -12
  7. package/dist/models/Model.js +167 -36
  8. package/package.json +1 -1
  9. package/dist/adapters/database/nosqlAdapter.d.ts +0 -8
  10. package/dist/adapters/database/nosqlAdapter.js +0 -30
  11. package/dist/adapters/database/sqlAdapter.d.ts +0 -8
  12. package/dist/adapters/database/sqlAdapter.js +0 -42
  13. package/dist/adapters/gcs.d.ts +0 -0
  14. package/dist/adapters/gcs.js +0 -1
  15. package/dist/adapters/local.d.ts +0 -0
  16. package/dist/adapters/local.js +0 -1
  17. package/dist/adapters/s3.d.ts +0 -11
  18. package/dist/adapters/s3.js +0 -65
  19. package/dist/database/Model.d.ts +0 -11
  20. package/dist/database/Model.js +0 -95
  21. package/dist/database/connectionManager.d.ts +0 -5
  22. package/dist/database/connectionManager.js +0 -32
  23. package/dist/database/index.d.ts +0 -3
  24. package/dist/database/index.js +0 -19
  25. package/dist/database/model.d.ts +0 -20
  26. package/dist/database/model.js +0 -2
  27. package/dist/database/modelManager.d.ts +0 -8
  28. package/dist/database/modelManager.js +0 -38
  29. package/dist/database/modelRegistry.d.ts +0 -3
  30. package/dist/database/modelRegistry.js +0 -17
  31. package/dist/database/mongoAdapter.d.ts +0 -11
  32. package/dist/database/mongoAdapter.js +0 -42
  33. package/dist/database/sqlAdapter.d.ts +0 -12
  34. package/dist/database/sqlAdapter.js +0 -68
  35. package/dist/models/modelManager.d.ts +0 -2
  36. package/dist/models/modelManager.js +0 -7
  37. package/dist/models/modelRegistry.d.ts +0 -3
  38. package/dist/models/modelRegistry.js +0 -17
  39. package/dist/models/registerModel.d.ts +0 -1
  40. package/dist/models/registerModel.js +0 -8
  41. package/dist/providers/createStorageProvider.d.ts +0 -2
  42. package/dist/providers/createStorageProvider.js +0 -12
@@ -2,5 +2,9 @@ import { Pool } from 'pg';
2
2
  import { MongoClient } from 'mongodb';
3
3
  import { DatabaseCredential } from '../../types';
4
4
  export declare const initConnections: (configs: DatabaseCredential[]) => Promise<void>;
5
- export declare const getConnection: (id: string) => Pool | MongoClient;
5
+ export declare const getConnection: (id: string) => {
6
+ id: string;
7
+ type: "sql" | "nosql";
8
+ client: Pool | MongoClient;
9
+ };
6
10
  export declare const getConnectedIds: () => string[];
@@ -3,8 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getConnectedIds = exports.getConnection = exports.initConnections = void 0;
4
4
  const pg_1 = require("pg");
5
5
  const mongodb_1 = require("mongodb");
6
- const clients = {};
7
- const connectedIds = [];
6
+ const nosql_1 = require("./nosql");
7
+ const connectedClients = [];
8
8
  const initConnections = async (configs) => {
9
9
  for (const config of configs) {
10
10
  if (!config.connectionString) {
@@ -15,16 +15,16 @@ const initConnections = async (configs) => {
15
15
  if (config.type === 'sql') {
16
16
  const pool = new pg_1.Pool({ connectionString: config.connectionString });
17
17
  await pool.connect();
18
- clients[config.id] = pool;
19
- connectedIds.push(config.id);
18
+ connectedClients.push({ id: config.id, type: 'sql', client: pool });
20
19
  console.log(`🟢 PostgreSQL connection established for ID: ${config.id}`);
20
+ await ensureTablesExist(pool);
21
21
  }
22
22
  else if (config.type === 'nosql') {
23
23
  const client = new mongodb_1.MongoClient(config.connectionString);
24
24
  await client.connect();
25
- clients[config.id] = client;
26
- connectedIds.push(config.id);
25
+ connectedClients.push({ id: config.id, type: 'nosql', client: client });
27
26
  console.log(`🟢 MongoDB connection established for ID: ${config.id}`);
27
+ await (0, nosql_1.ensureCollectionsExist)(client);
28
28
  }
29
29
  }
30
30
  catch (error) {
@@ -34,14 +34,70 @@ const initConnections = async (configs) => {
34
34
  };
35
35
  exports.initConnections = initConnections;
36
36
  const getConnection = (id) => {
37
- const client = clients[id];
38
- if (!client) {
37
+ const clientEntry = connectedClients.find(c => c.id === id);
38
+ if (!clientEntry) {
39
39
  throw new Error(`Connection with id ${id} not found.`);
40
40
  }
41
- return client;
41
+ return clientEntry;
42
42
  };
43
43
  exports.getConnection = getConnection;
44
+ const ensureTablesExist = async (pool) => {
45
+ try {
46
+ await pool.query(`
47
+ CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
48
+ CREATE TABLE IF NOT EXISTS projects (
49
+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
50
+ name VARCHAR(255) NOT NULL,
51
+ description TEXT,
52
+ "createdAt" TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
53
+ "updatedAt" TIMESTAMP WITH TIME ZONE DEFAULT NOW()
54
+ );
55
+ `);
56
+ console.log('✅ "projects" table ensured to exist.');
57
+ // Ensure dbType column exists and is correctly configured
58
+ await pool.query(`
59
+ ALTER TABLE projects ADD COLUMN IF NOT EXISTS "dbType" VARCHAR(50);
60
+ `);
61
+ await pool.query(`
62
+ UPDATE projects SET "dbType" = 'nosql' WHERE "dbType" IS NULL;
63
+ `);
64
+ await pool.query(`
65
+ ALTER TABLE projects ALTER COLUMN "dbType" SET NOT NULL;
66
+ `);
67
+ await pool.query(`
68
+ ALTER TABLE projects ALTER COLUMN "dbType" SET DEFAULT 'nosql';
69
+ `);
70
+ await pool.query(`
71
+ CREATE TABLE IF NOT EXISTS exports (
72
+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
73
+ "projectId" UUID NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
74
+ status VARCHAR(50) NOT NULL DEFAULT 'pending',
75
+ "filePath" TEXT,
76
+ "createdAt" TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
77
+ "updatedAt" TIMESTAMP WITH TIME ZONE DEFAULT NOW()
78
+ );
79
+ `);
80
+ console.log('✅ "exports" table ensured to exist.');
81
+ await pool.query(`
82
+ CREATE TABLE IF NOT EXISTS project_members (
83
+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
84
+ "projectId" UUID NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
85
+ "userId" VARCHAR(255) NOT NULL,
86
+ archived BOOLEAN NOT NULL DEFAULT FALSE,
87
+ "archivedBy" VARCHAR(255),
88
+ "archivedAt" TIMESTAMP WITH TIME ZONE,
89
+ "createdAt" TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
90
+ "updatedAt" TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
91
+ UNIQUE ("projectId", "userId")
92
+ );
93
+ `);
94
+ console.log('✅ "project_members" table ensured to exist.');
95
+ }
96
+ catch (error) {
97
+ console.error('❌ Error ensuring tables exist:', error);
98
+ }
99
+ };
44
100
  const getConnectedIds = () => {
45
- return connectedIds;
101
+ return connectedClients.map(c => c.id);
46
102
  };
47
103
  exports.getConnectedIds = getConnectedIds;
@@ -1,4 +1,5 @@
1
1
  import { MongoClient, Document } from 'mongodb';
2
+ export declare const ensureCollectionsExist: (client: MongoClient) => Promise<void>;
2
3
  export declare const nosqlAdapter: {
3
4
  find: (connection: MongoClient, tableName: string, filter: any) => Promise<Document[]>;
4
5
  findOne: (connection: MongoClient, tableName: string, filter: any) => Promise<Document | null>;
@@ -1,7 +1,21 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.nosqlAdapter = void 0;
3
+ exports.nosqlAdapter = exports.ensureCollectionsExist = void 0;
4
4
  const mongodb_1 = require("mongodb");
5
+ const ensureCollectionsExist = async (client) => {
6
+ const db = client.db();
7
+ // Ensure 'projects' collection exists and define its schema implicitly
8
+ // Schema: { _id: ObjectId, name: string, description: string, dbType: string, createdAt: Date, updatedAt: Date, members: [{ userId: string, archived: boolean }] }
9
+ const projectsCollection = db.collection('projects');
10
+ await projectsCollection.findOne({}); // Attempt to find one to ensure collection is created if it doesn't exist
11
+ console.log('✅ "projects" collection ensured to exist.');
12
+ // Ensure 'exports' collection exists and define its schema implicitly
13
+ // Schema: { _id: ObjectId, projectId: ObjectId, status: string, filePath: string, createdAt: Date, updatedAt: Date }
14
+ const exportsCollection = db.collection('exports');
15
+ await exportsCollection.findOne({}); // Attempt to find one to ensure collection is created if it doesn't exist
16
+ console.log('✅ "exports" collection ensured to exist.');
17
+ };
18
+ exports.ensureCollectionsExist = ensureCollectionsExist;
5
19
  exports.nosqlAdapter = {
6
20
  find: async (connection, tableName, filter) => {
7
21
  const db = connection.db();
@@ -5,8 +5,12 @@ exports.sqlAdapter = {
5
5
  find: async (connection, tableName, filter) => {
6
6
  const keys = Object.keys(filter);
7
7
  const values = Object.values(filter);
8
- const where = keys.map((key, i) => `"${key}" = $${i + 1}`).join(' AND ');
9
- const result = await connection.query(`SELECT * FROM "${tableName}" WHERE ${where}`, values);
8
+ let query = `SELECT * FROM "${tableName}"`;
9
+ if (keys.length > 0) {
10
+ const where = keys.map((key, i) => `"${key}" = $${i + 1}`).join(' AND ');
11
+ query += ` WHERE ${where}`;
12
+ }
13
+ const result = await connection.query(query, values);
10
14
  return result.rows;
11
15
  },
12
16
  findOne: async (connection, tableName, filter) => {
@@ -17,7 +21,7 @@ exports.sqlAdapter = {
17
21
  return result.rows[0] || null;
18
22
  },
19
23
  create: async (connection, tableName, data) => {
20
- const keys = Object.keys(data).join(', ');
24
+ const keys = Object.keys(data).map(key => `"${key}"`).join(', ');
21
25
  const values = Object.values(data);
22
26
  const placeholders = values.map((_, i) => `$${i + 1}`).join(', ');
23
27
  const result = await connection.query(`INSERT INTO "${tableName}" (${keys}) VALUES (${placeholders}) RETURNING *`, values);
@@ -10,6 +10,7 @@ const presign_1 = require("../services/presign");
10
10
  const manager_1 = require("../models/manager");
11
11
  const storage_1 = require("../providers/storage");
12
12
  const connectionManager_1 = require("../adapters/database/connectionManager");
13
+ const auth_1 = require("../services/auth");
13
14
  function isProjectMember(project, userId) {
14
15
  return project.members?.some((m) => m.userId?.toString() === userId?.toString());
15
16
  }
@@ -18,18 +19,15 @@ function createStreamByRouter(config) {
18
19
  (0, connectionManager_1.initConnections)(config.databases || []);
19
20
  const adapter = config.adapter || (0, storage_1.createStorageProvider)(config.storageProviders);
20
21
  if (config.databases) {
21
- for (const db of config.databases) {
22
- if (db.type === 'sql') {
23
- (0, manager_1.registerModel)('Project', [db.id], 'projects');
24
- (0, manager_1.registerModel)('Export', [db.id], 'exports');
25
- }
26
- }
22
+ const allDbIds = config.databases.map(db => db.id);
23
+ (0, manager_1.registerModel)('projects', allDbIds, 'projects');
24
+ (0, manager_1.registerModel)('exports', allDbIds, 'exports');
27
25
  }
28
- const Project = (0, manager_1.getModel)('Project');
29
- const Export = (0, manager_1.getModel)('Export');
26
+ const Project = (0, manager_1.getModel)('projects');
27
+ const Export = (0, manager_1.getModel)('exports');
30
28
  router.get('/auth', async (req, res) => {
31
29
  try {
32
- const auth = await config.authProvider(req);
30
+ const auth = await (0, auth_1.resolveAuth)(config, req);
33
31
  res.status(200).json({ logged: true, ...auth });
34
32
  }
35
33
  catch (err) {
@@ -104,8 +102,21 @@ function createStreamByRouter(config) {
104
102
  router.get('/projects', async (req, res) => {
105
103
  try {
106
104
  const auth = await config.authProvider(req);
107
- const archived = req.query.archived ? String(req.query.archived).toLowerCase() === 'true' : undefined;
108
- const projects = (await Project.find({ members: { $elemMatch: { userId: auth.userId } }, archived })).map(project => {
105
+ const archivedQuery = req.query.archived;
106
+ const filterArchived = archivedQuery !== undefined ? String(archivedQuery).toLowerCase() === 'true' : undefined;
107
+ const allProjects = await Project.find({}); // Fetch all projects
108
+ const projects = allProjects
109
+ .filter(project => {
110
+ const isMember = project.members?.some((m) => m.userId?.toString() === auth.userId?.toString());
111
+ if (!isMember)
112
+ return false;
113
+ if (filterArchived !== undefined) {
114
+ const currentUserMember = project.members?.find((member) => member.userId === auth.userId);
115
+ return currentUserMember ? (currentUserMember.archived || false) === filterArchived : false;
116
+ }
117
+ return true;
118
+ })
119
+ .map(project => {
109
120
  const currentUserMember = project.members?.find((member) => member.userId === auth.userId);
110
121
  return {
111
122
  id: project._id || project.id,
@@ -118,6 +129,7 @@ function createStreamByRouter(config) {
118
129
  res.json({ projects });
119
130
  }
120
131
  catch (err) {
132
+ console.error('Error in /projects endpoint:', err);
121
133
  res.status(500).json({ error: 'Failed to list projects', details: err });
122
134
  }
123
135
  });
@@ -296,7 +308,6 @@ function createStreamByRouter(config) {
296
308
  collectionName,
297
309
  projectId
298
310
  });
299
- await Project.update({ _id: projectId }, { $push: { exports: newExport._id } });
300
311
  res.status(201).json({ data: { ...newExport, id: newExport._id || newExport.id, _id: undefined } });
301
312
  }
302
313
  catch (err) {
@@ -2,7 +2,6 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Model = void 0;
4
4
  const connectionManager_1 = require("../adapters/database/connectionManager");
5
- const pg_1 = require("pg");
6
5
  const mongodb_1 = require("mongodb");
7
6
  const sql_1 = require("../adapters/database/sql");
8
7
  const nosql_1 = require("../adapters/database/nosql");
@@ -15,15 +14,55 @@ class Model {
15
14
  const allResults = [];
16
15
  const activeConnectionIds = this.connectionIds.filter(id => (0, connectionManager_1.getConnectedIds)().includes(id));
17
16
  for (const connectionId of activeConnectionIds) {
18
- const connection = (0, connectionManager_1.getConnection)(connectionId);
19
- if (connection instanceof pg_1.Pool) {
20
- const sqlResults = await sql_1.sqlAdapter.find(connection, this.tableName, filter);
17
+ const clientEntry = (0, connectionManager_1.getConnection)(connectionId);
18
+ const connection = clientEntry.client;
19
+ const dbType = clientEntry.type;
20
+ let processedFilter = { ...filter };
21
+ if (dbType === 'sql') {
22
+ if (processedFilter._id) {
23
+ processedFilter.id = processedFilter._id;
24
+ delete processedFilter._id;
25
+ }
26
+ let sqlResults = [];
27
+ if (this.tableName === 'projects' && processedFilter.members && processedFilter.members.$elemMatch) {
28
+ // Handle members filter for SQL projects
29
+ const userId = processedFilter.members.$elemMatch.userId;
30
+ const query = `
31
+ SELECT p.*, pm."userId" as memberUserId, pm.archived as memberArchived
32
+ FROM "projects" p
33
+ JOIN "project_members" pm ON p.id = pm."projectId"
34
+ WHERE pm."userId" = $1
35
+ `;
36
+ const result = await connection.query(query, [userId]);
37
+ sqlResults = result.rows.map(row => ({
38
+ ...row,
39
+ members: [{
40
+ userId: row.memberUserId,
41
+ archived: row.memberArchived,
42
+ // Add other member fields if necessary
43
+ }]
44
+ }));
45
+ }
46
+ else {
47
+ // General SQL find
48
+ sqlResults = await sql_1.sqlAdapter.find(connection, this.tableName, processedFilter);
49
+ }
21
50
  for (const item of sqlResults) {
22
- allResults.push(this.transformResult(item));
51
+ const transformedItem = this.transformResult(item);
52
+ if (this.tableName === 'projects' && !transformedItem.members) {
53
+ // For projects, if members not already populated by join, fetch from project_members table
54
+ const projectMembers = await sql_1.sqlAdapter.find(connection, 'project_members', { projectId: transformedItem.id });
55
+ transformedItem.members = projectMembers.map((member) => ({
56
+ userId: member.userId,
57
+ role: member.role, // Assuming role is also stored in project_members
58
+ archived: member.archived,
59
+ }));
60
+ }
61
+ allResults.push(transformedItem);
23
62
  }
24
63
  }
25
- else if (connection instanceof mongodb_1.MongoClient) {
26
- const nosqlResults = await nosql_1.nosqlAdapter.find(connection, this.tableName, filter);
64
+ else if (dbType === 'nosql') {
65
+ const nosqlResults = await nosql_1.nosqlAdapter.find(connection, this.tableName, processedFilter);
27
66
  for (const item of nosqlResults) {
28
67
  allResults.push(this.transformResult(item));
29
68
  }
@@ -41,18 +80,41 @@ class Model {
41
80
  async findOne(filter) {
42
81
  const activeConnectionIds = this.connectionIds.filter(id => (0, connectionManager_1.getConnectedIds)().includes(id));
43
82
  for (const connectionId of activeConnectionIds) {
44
- const connection = (0, connectionManager_1.getConnection)(connectionId);
83
+ const clientEntry = (0, connectionManager_1.getConnection)(connectionId);
84
+ const connection = clientEntry.client;
85
+ const dbType = clientEntry.type;
45
86
  let processedFilter = { ...filter };
46
- if (connection instanceof pg_1.Pool) {
87
+ if (dbType === 'sql') {
47
88
  if (processedFilter._id) {
48
89
  processedFilter.id = processedFilter._id;
49
90
  delete processedFilter._id;
50
91
  }
51
92
  const result = await sql_1.sqlAdapter.findOne(connection, this.tableName, processedFilter);
52
- if (result)
53
- return result;
93
+ if (result) {
94
+ const transformedResult = this.transformResult(result);
95
+ if (this.tableName === 'projects') {
96
+ // For projects, fetch members from project_members table
97
+ const projectMembers = await sql_1.sqlAdapter.find(connection, 'project_members', { projectId: transformedResult.id });
98
+ transformedResult.members = projectMembers.map((member) => ({
99
+ userId: member.userId,
100
+ role: member.role, // Assuming role is also stored in project_members
101
+ archived: member.archived,
102
+ }));
103
+ }
104
+ return transformedResult;
105
+ }
54
106
  }
55
- else if (connection instanceof mongodb_1.MongoClient) {
107
+ else if (dbType === 'nosql') {
108
+ if (processedFilter._id && typeof processedFilter._id === 'string') {
109
+ try {
110
+ processedFilter._id = new mongodb_1.ObjectId(processedFilter._id);
111
+ }
112
+ catch (e) {
113
+ // If it's not a valid ObjectId string, it might be a UUID from a SQL project.
114
+ // In this case, this NoSQL connection won't find it, so we can just continue.
115
+ continue;
116
+ }
117
+ }
56
118
  const result = await nosql_1.nosqlAdapter.findOne(connection, this.tableName, processedFilter);
57
119
  if (result)
58
120
  return result;
@@ -62,12 +124,45 @@ class Model {
62
124
  }
63
125
  async create(data) {
64
126
  const activeConnectionIds = this.connectionIds.filter(id => (0, connectionManager_1.getConnectedIds)().includes(id));
65
- const connection = (0, connectionManager_1.getConnection)(activeConnectionIds[0]); // Use the first active connection for creation
66
- if (connection instanceof pg_1.Pool) {
67
- const created = await sql_1.sqlAdapter.create(connection, this.tableName, data);
127
+ // Determine the target database type from the data payload
128
+ const targetDbType = data.dbType || 'nosql'; // Default to nosql if not specified
129
+ const allClientEntries = activeConnectionIds.map(id => (0, connectionManager_1.getConnection)(id));
130
+ // Find the connection that matches the targetDbType
131
+ const clientEntry = allClientEntries.find(entry => entry.type === targetDbType);
132
+ if (!clientEntry) {
133
+ throw new Error(`No active connection found for database type: ${targetDbType}`);
134
+ }
135
+ const connection = clientEntry.client;
136
+ const dbType = clientEntry.type;
137
+ if (dbType === 'sql') {
138
+ const dataToInsert = {};
139
+ let membersToInsert = [];
140
+ // Iterate over the keys of the incoming data
141
+ for (const key in data) {
142
+ if (this.tableName === 'projects' && key === 'members') {
143
+ membersToInsert = data[key];
144
+ }
145
+ else if (this.tableName === 'projects' && key.toLowerCase() === 'dbtype') {
146
+ dataToInsert["dbType"] = data[key];
147
+ }
148
+ else {
149
+ dataToInsert[key] = data[key];
150
+ }
151
+ }
152
+ const created = await sql_1.sqlAdapter.create(connection, this.tableName, dataToInsert);
153
+ // Insert members into project_members table for SQL
154
+ if (this.tableName === 'projects' && membersToInsert.length > 0) {
155
+ for (const member of membersToInsert) {
156
+ await sql_1.sqlAdapter.create(connection, 'project_members', {
157
+ projectId: created.id,
158
+ userId: member.userId,
159
+ archived: member.archived || false,
160
+ });
161
+ }
162
+ }
68
163
  return created;
69
164
  }
70
- else if (connection instanceof mongodb_1.MongoClient) {
165
+ else if (dbType === 'nosql') {
71
166
  const created = await nosql_1.nosqlAdapter.create(connection, this.tableName, data);
72
167
  return created;
73
168
  }
@@ -76,7 +171,9 @@ class Model {
76
171
  async update(filter, data) {
77
172
  const activeConnectionIds = this.connectionIds.filter(id => (0, connectionManager_1.getConnectedIds)().includes(id));
78
173
  for (const connectionId of activeConnectionIds) {
79
- const connection = (0, connectionManager_1.getConnection)(connectionId);
174
+ const clientEntry = (0, connectionManager_1.getConnection)(connectionId);
175
+ const connection = clientEntry.client;
176
+ const dbType = clientEntry.type;
80
177
  let processedFilter = { ...filter };
81
178
  // Handle specific member archiving/unarchiving
82
179
  if (data["members.$.archived"] !== undefined && processedFilter["_id"] && processedFilter["members.userId"]) {
@@ -85,25 +182,45 @@ class Model {
85
182
  const newArchivedStatus = data["members.$.archived"];
86
183
  const archivedBy = data["members.$.archivedBy"];
87
184
  const archivedAt = data["members.$.archivedAt"];
88
- // Fetch the project to modify its members array
89
- const projectToUpdate = await this.findOne({ _id: projectId });
90
- if (!projectToUpdate || !projectToUpdate.members) {
91
- continue; // Project not found or has no members, try next connection
92
- }
93
- const updatedMembers = projectToUpdate.members.map((member) => {
94
- if (member.userId === userIdToUpdate) {
95
- return { ...member, archived: newArchivedStatus, archivedBy: archivedBy, archivedAt: archivedAt };
185
+ if (dbType === 'sql') {
186
+ // For SQL, directly update the project_members table
187
+ const memberUpdateResult = await sql_1.sqlAdapter.update(connection, 'project_members', { projectId: projectId, userId: userIdToUpdate }, { archived: newArchivedStatus, archivedBy: archivedBy, archivedAt: archivedAt });
188
+ // After updating the member, fetch the full project to return
189
+ if (memberUpdateResult) {
190
+ const updatedProject = await this.findOne({ _id: projectId });
191
+ return updatedProject;
96
192
  }
97
- return member;
98
- });
99
- // Update the project with the modified members array
100
- const result = await (connection instanceof pg_1.Pool ? sql_1.sqlAdapter.update(connection, this.tableName, { id: projectId }, { members: updatedMembers }) : nosql_1.nosqlAdapter.update(connection, this.tableName, { _id: new mongodb_1.ObjectId(projectId) }, { members: updatedMembers }));
101
- if (result)
102
- return result;
193
+ }
194
+ else if (dbType === 'nosql') {
195
+ // For NoSQL, fetch the project to modify its members array
196
+ const projectToUpdate = await this.findOne({ _id: projectId });
197
+ if (!projectToUpdate || !projectToUpdate.members) {
198
+ continue; // Project not found or has no members, try next connection
199
+ }
200
+ const updatedMembers = projectToUpdate.members.map((member) => {
201
+ if (member.userId === userIdToUpdate) {
202
+ return { ...member, archived: newArchivedStatus, archivedBy: archivedBy, archivedAt: archivedAt };
203
+ }
204
+ return member;
205
+ });
206
+ let objectIdProjectId;
207
+ try {
208
+ objectIdProjectId = new mongodb_1.ObjectId(projectId);
209
+ }
210
+ catch (e) {
211
+ // If it's not a valid ObjectId string, it might be a UUID from a SQL project.
212
+ // In this case, this NoSQL connection won't find it, so we can just continue.
213
+ continue;
214
+ }
215
+ // Update the project with the modified members array
216
+ const result = await nosql_1.nosqlAdapter.update(connection, this.tableName, { _id: objectIdProjectId }, { members: updatedMembers });
217
+ if (result)
218
+ return result;
219
+ }
103
220
  }
104
221
  else {
105
222
  // General update logic
106
- if (connection instanceof pg_1.Pool) {
223
+ if (dbType === 'sql') {
107
224
  if (processedFilter._id) {
108
225
  processedFilter.id = processedFilter._id;
109
226
  delete processedFilter._id;
@@ -112,7 +229,7 @@ class Model {
112
229
  if (result)
113
230
  return result;
114
231
  }
115
- else if (connection instanceof mongodb_1.MongoClient) {
232
+ else if (dbType === 'nosql') {
116
233
  const result = await nosql_1.nosqlAdapter.update(connection, this.tableName, processedFilter, data);
117
234
  if (result)
118
235
  return result;
@@ -125,17 +242,31 @@ class Model {
125
242
  let deletedCount = 0;
126
243
  const activeConnectionIds = this.connectionIds.filter(id => (0, connectionManager_1.getConnectedIds)().includes(id));
127
244
  for (const connectionId of activeConnectionIds) {
128
- const connection = (0, connectionManager_1.getConnection)(connectionId);
245
+ const clientEntry = (0, connectionManager_1.getConnection)(connectionId);
246
+ const connection = clientEntry.client;
247
+ const dbType = clientEntry.type;
129
248
  let processedFilter = { ...filter };
130
- if (connection instanceof pg_1.Pool) {
249
+ if (dbType === 'sql') {
131
250
  if (processedFilter._id) {
132
251
  processedFilter.id = processedFilter._id;
133
252
  delete processedFilter._id;
134
253
  }
254
+ console.log(`SQL: Deleting from ${this.tableName} with filter:`, processedFilter);
135
255
  const count = await sql_1.sqlAdapter.delete(connection, this.tableName, processedFilter);
256
+ console.log(`SQL: Deleted ${count} rows from ${this.tableName}`);
136
257
  deletedCount += count;
137
258
  }
138
- else if (connection instanceof mongodb_1.MongoClient) {
259
+ else if (dbType === 'nosql') {
260
+ if (processedFilter._id && typeof processedFilter._id === 'string') {
261
+ try {
262
+ processedFilter._id = new mongodb_1.ObjectId(processedFilter._id);
263
+ }
264
+ catch (e) {
265
+ // If it's not a valid ObjectId string, it might be a UUID from a SQL project.
266
+ // In this case, this NoSQL connection won't find it, so we can just continue.
267
+ continue;
268
+ }
269
+ }
139
270
  const count = await nosql_1.nosqlAdapter.delete(connection, this.tableName, processedFilter);
140
271
  deletedCount += count;
141
272
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "streamby-core",
3
- "version": "0.20.1",
3
+ "version": "0.21.0",
4
4
  "description": "StreamBy middleware framework for media storage management",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -1,8 +0,0 @@
1
- import { MongoClient, Document } from 'mongodb';
2
- export declare const nosqlAdapter: {
3
- find: <T extends Document>(connection: MongoClient, tableName: string, filter: any) => Promise<T[]>;
4
- findOne: <T extends Document>(connection: MongoClient, tableName: string, filter: any) => Promise<T | null>;
5
- create: <T extends Document>(connection: MongoClient, tableName: string, data: T) => Promise<T>;
6
- update: <T extends Document>(connection: MongoClient, tableName: string, filter: any, data: Partial<T>) => Promise<number>;
7
- delete: <T extends Document>(connection: MongoClient, tableName: string, filter: any) => Promise<number>;
8
- };
@@ -1,30 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.nosqlAdapter = void 0;
4
- exports.nosqlAdapter = {
5
- find: async (connection, tableName, filter) => {
6
- const db = connection.db();
7
- const result = await db.collection(tableName).find(filter).toArray();
8
- return result;
9
- },
10
- findOne: async (connection, tableName, filter) => {
11
- const db = connection.db();
12
- const result = await db.collection(tableName).findOne(filter);
13
- return result;
14
- },
15
- create: async (connection, tableName, data) => {
16
- const db = connection.db();
17
- const result = await db.collection(tableName).insertOne(data);
18
- return { ...data, _id: result.insertedId };
19
- },
20
- update: async (connection, tableName, filter, data) => {
21
- const db = connection.db();
22
- const result = await db.collection(tableName).updateMany(filter, { $set: data });
23
- return result.modifiedCount;
24
- },
25
- delete: async (connection, tableName, filter) => {
26
- const db = connection.db();
27
- const result = await db.collection(tableName).deleteMany(filter);
28
- return result.deletedCount;
29
- },
30
- };
@@ -1,8 +0,0 @@
1
- import { Pool } from 'pg';
2
- export declare const sqlAdapter: {
3
- find: <T>(connection: Pool, tableName: string, filter: any) => Promise<T[]>;
4
- findOne: <T>(connection: Pool, tableName: string, filter: any) => Promise<T | null>;
5
- create: <T>(connection: Pool, tableName: string, data: T) => Promise<T>;
6
- update: <T>(connection: Pool, tableName: string, filter: any, data: Partial<T>) => Promise<number>;
7
- delete: (connection: Pool, tableName: string, filter: any) => Promise<number>;
8
- };
@@ -1,42 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.sqlAdapter = void 0;
4
- exports.sqlAdapter = {
5
- find: async (connection, tableName, filter) => {
6
- const keys = Object.keys(filter);
7
- const values = Object.values(filter);
8
- const where = keys.map((key, i) => `"${key}" = $${i + 1}`).join(' AND ');
9
- const result = await connection.query(`SELECT * FROM "${tableName}" WHERE ${where}`, values);
10
- return result.rows;
11
- },
12
- findOne: async (connection, tableName, filter) => {
13
- const keys = Object.keys(filter);
14
- const values = Object.values(filter);
15
- const where = keys.map((key, i) => `"${key}" = $${i + 1}`).join(' AND ');
16
- const result = await connection.query(`SELECT * FROM "${tableName}" WHERE ${where} LIMIT 1`, values);
17
- return result.rows[0] || null;
18
- },
19
- create: async (connection, tableName, data) => {
20
- const keys = Object.keys(data).join(', ');
21
- const values = Object.values(data);
22
- const placeholders = values.map((_, i) => `$${i + 1}`).join(', ');
23
- const result = await connection.query(`INSERT INTO "${tableName}" (${keys}) VALUES (${placeholders}) RETURNING *`, values);
24
- return result.rows[0];
25
- },
26
- update: async (connection, tableName, filter, data) => {
27
- const dataKeys = Object.keys(data);
28
- const filterKeys = Object.keys(filter);
29
- const values = [...Object.values(data), ...Object.values(filter)];
30
- const setClause = dataKeys.map((key, i) => `"${key}" = $${i + 1}`).join(', ');
31
- const whereClause = filterKeys.map((key, i) => `"${key}" = $${dataKeys.length + i + 1}`).join(' AND ');
32
- const result = await connection.query(`UPDATE "${tableName}" SET ${setClause} WHERE ${whereClause}`, values);
33
- return result.rowCount || 0;
34
- },
35
- delete: async (connection, tableName, filter) => {
36
- const keys = Object.keys(filter);
37
- const values = Object.values(filter);
38
- const where = keys.map((key, i) => `"${key}" = $${i + 1}`).join(' AND ');
39
- const result = await connection.query(`DELETE FROM "${tableName}" WHERE ${where}`, values);
40
- return result.rowCount || 0;
41
- },
42
- };
File without changes
@@ -1 +0,0 @@
1
- "use strict";
File without changes
@@ -1 +0,0 @@
1
- "use strict";
@@ -1,11 +0,0 @@
1
- import { S3Config, StorageAdapter } from '../types';
2
- export declare class S3Adapter implements StorageAdapter {
3
- private s3;
4
- private bucket;
5
- constructor(config: S3Config);
6
- listFiles(projectId: string): Promise<any[]>;
7
- deleteProjectImage(projectId: string): Promise<any>;
8
- deleteProjectDirectory(projectId: string): Promise<any>;
9
- getPresignedUrl(contentType: string, projectId: string): Promise<any>;
10
- getPresignedProjectImageUrl(projectId: string): Promise<any>;
11
- }
@@ -1,65 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.S3Adapter = void 0;
4
- const client_s3_1 = require("@aws-sdk/client-s3");
5
- const s3_request_presigner_1 = require("@aws-sdk/s3-request-presigner");
6
- class S3Adapter {
7
- constructor(config) {
8
- this.s3 = new client_s3_1.S3Client({
9
- region: config.region,
10
- credentials: {
11
- accessKeyId: config.accessKeyId,
12
- secretAccessKey: config.secretAccessKey,
13
- },
14
- });
15
- this.bucket = config.bucket;
16
- }
17
- async listFiles(projectId) {
18
- const command = new client_s3_1.ListObjectsV2Command({
19
- Bucket: this.bucket,
20
- Prefix: `${projectId}/`,
21
- });
22
- const result = await this.s3.send(command);
23
- return result.Contents || [];
24
- }
25
- async deleteProjectImage(projectId) {
26
- const command = new client_s3_1.DeleteObjectCommand({
27
- Bucket: this.bucket,
28
- Key: `${projectId}/project-image`,
29
- });
30
- return await this.s3.send(command);
31
- }
32
- async deleteProjectDirectory(projectId) {
33
- const listCommand = new client_s3_1.ListObjectsV2Command({
34
- Bucket: this.bucket,
35
- Prefix: `${projectId}/`,
36
- });
37
- const listedObjects = await this.s3.send(listCommand);
38
- if (!listedObjects.Contents || listedObjects.Contents.length === 0) {
39
- return;
40
- }
41
- const deleteParams = {
42
- Bucket: this.bucket,
43
- Delete: { Objects: listedObjects.Contents.map(({ Key }) => ({ Key })) },
44
- };
45
- const deleteCommand = new client_s3_1.DeleteObjectCommand(deleteParams);
46
- return await this.s3.send(deleteCommand);
47
- }
48
- async getPresignedUrl(contentType, projectId) {
49
- const command = new client_s3_1.PutObjectCommand({
50
- Bucket: this.bucket,
51
- Key: `${projectId}/${Date.now()}`,
52
- ContentType: contentType,
53
- });
54
- return await (0, s3_request_presigner_1.getSignedUrl)(this.s3, command, { expiresIn: 3600 });
55
- }
56
- async getPresignedProjectImageUrl(projectId) {
57
- const command = new client_s3_1.PutObjectCommand({
58
- Bucket: this.bucket,
59
- Key: `${projectId}/project-image`,
60
- ContentType: 'image/jpeg',
61
- });
62
- return await (0, s3_request_presigner_1.getSignedUrl)(this.s3, command, { expiresIn: 3600 });
63
- }
64
- }
65
- exports.S3Adapter = S3Adapter;
@@ -1,11 +0,0 @@
1
- import { Document } from 'mongodb';
2
- export declare class Model<T extends Document> {
3
- private connectionId;
4
- private tableName;
5
- constructor(connectionId: string, tableName: string);
6
- find(filter: any): Promise<T[]>;
7
- findOne(filter: any): Promise<T | null>;
8
- create(data: T): Promise<T>;
9
- update(filter: any, data: Partial<T>): Promise<number>;
10
- delete(filter: any): Promise<number>;
11
- }
@@ -1,95 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Model = void 0;
4
- const connectionManager_1 = require("./connectionManager");
5
- const pg_1 = require("pg");
6
- const mongodb_1 = require("mongodb");
7
- class Model {
8
- constructor(connectionId, tableName) {
9
- this.connectionId = connectionId;
10
- this.tableName = tableName;
11
- }
12
- async find(filter) {
13
- const connection = (0, connectionManager_1.getConnection)(this.connectionId);
14
- if (connection instanceof pg_1.Pool) {
15
- const keys = Object.keys(filter);
16
- const values = Object.values(filter);
17
- const where = keys.map((key, i) => `"${key}" = $${i + 1}`).join(' AND ');
18
- const result = await connection.query(`SELECT * FROM "${this.tableName}" WHERE ${where}`, values);
19
- return result.rows;
20
- }
21
- else if (connection instanceof mongodb_1.MongoClient) {
22
- const db = connection.db();
23
- const result = await db.collection(this.tableName).find(filter).toArray();
24
- return result;
25
- }
26
- return [];
27
- }
28
- async findOne(filter) {
29
- const connection = (0, connectionManager_1.getConnection)(this.connectionId);
30
- if (connection instanceof pg_1.Pool) {
31
- const keys = Object.keys(filter);
32
- const values = Object.values(filter);
33
- const where = keys.map((key, i) => `"${key}" = $${i + 1}`).join(' AND ');
34
- const result = await connection.query(`SELECT * FROM "${this.tableName}" WHERE ${where} LIMIT 1`, values);
35
- return result.rows[0] || null;
36
- }
37
- else if (connection instanceof mongodb_1.MongoClient) {
38
- const db = connection.db();
39
- const result = await db.collection(this.tableName).findOne(filter);
40
- return result;
41
- }
42
- return null;
43
- }
44
- async create(data) {
45
- const connection = (0, connectionManager_1.getConnection)(this.connectionId);
46
- if (connection instanceof pg_1.Pool) {
47
- const keys = Object.keys(data).join(', ');
48
- const values = Object.values(data);
49
- const placeholders = values.map((_, i) => `$${i + 1}`).join(', ');
50
- const result = await connection.query(`INSERT INTO "${this.tableName}" (${keys}) VALUES (${placeholders}) RETURNING *`, values);
51
- return result.rows[0];
52
- }
53
- else if (connection instanceof mongodb_1.MongoClient) {
54
- const db = connection.db();
55
- const result = await db.collection(this.tableName).insertOne(data);
56
- return { ...data, _id: result.insertedId };
57
- }
58
- return data;
59
- }
60
- async update(filter, data) {
61
- const connection = (0, connectionManager_1.getConnection)(this.connectionId);
62
- if (connection instanceof pg_1.Pool) {
63
- const dataKeys = Object.keys(data);
64
- const filterKeys = Object.keys(filter);
65
- const values = [...Object.values(data), ...Object.values(filter)];
66
- const setClause = dataKeys.map((key, i) => `"${key}" = $${i + 1}`).join(', ');
67
- const whereClause = filterKeys.map((key, i) => `"${key}" = $${dataKeys.length + i + 1}`).join(' AND ');
68
- const result = await connection.query(`UPDATE "${this.tableName}" SET ${setClause} WHERE ${whereClause}`, values);
69
- return result.rowCount || 0;
70
- }
71
- else if (connection instanceof mongodb_1.MongoClient) {
72
- const db = connection.db();
73
- const result = await db.collection(this.tableName).updateMany(filter, { $set: data });
74
- return result.modifiedCount;
75
- }
76
- return 0;
77
- }
78
- async delete(filter) {
79
- const connection = (0, connectionManager_1.getConnection)(this.connectionId);
80
- if (connection instanceof pg_1.Pool) {
81
- const keys = Object.keys(filter);
82
- const values = Object.values(filter);
83
- const where = keys.map((key, i) => `"${key}" = $${i + 1}`).join(' AND ');
84
- const result = await connection.query(`DELETE FROM "${this.tableName}" WHERE ${where}`, values);
85
- return result.rowCount || 0;
86
- }
87
- else if (connection instanceof mongodb_1.MongoClient) {
88
- const db = connection.db();
89
- const result = await db.collection(this.tableName).deleteMany(filter);
90
- return result.deletedCount;
91
- }
92
- return 0;
93
- }
94
- }
95
- exports.Model = Model;
@@ -1,5 +0,0 @@
1
- import { Pool } from 'pg';
2
- import { MongoClient } from 'mongodb';
3
- import { DatabaseCredential } from '../types';
4
- export declare const initConnections: (configs: DatabaseCredential[]) => Promise<void>;
5
- export declare const getConnection: (id: string) => Pool | MongoClient;
@@ -1,32 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getConnection = exports.initConnections = void 0;
4
- const pg_1 = require("pg");
5
- const mongodb_1 = require("mongodb");
6
- const clients = {};
7
- const initConnections = async (configs) => {
8
- for (const config of configs) {
9
- if (!config.connectionString) {
10
- throw new Error(`Connection string not provided for database config with id ${config.id}`);
11
- }
12
- if (config.type === 'sql') {
13
- const pool = new pg_1.Pool({ connectionString: config.connectionString });
14
- await pool.connect();
15
- clients[config.id] = pool;
16
- }
17
- else if (config.type === 'nosql') {
18
- const client = new mongodb_1.MongoClient(config.connectionString);
19
- await client.connect();
20
- clients[config.id] = client;
21
- }
22
- }
23
- };
24
- exports.initConnections = initConnections;
25
- const getConnection = (id) => {
26
- const client = clients[id];
27
- if (!client) {
28
- throw new Error(`Connection with id ${id} not found.`);
29
- }
30
- return client;
31
- };
32
- exports.getConnection = getConnection;
@@ -1,3 +0,0 @@
1
- export * from './connectionManager';
2
- export * from './Model';
3
- export * from './modelRegistry';
@@ -1,19 +0,0 @@
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("./connectionManager"), exports);
18
- __exportStar(require("./Model"), exports);
19
- __exportStar(require("./modelRegistry"), exports);
@@ -1,20 +0,0 @@
1
- export interface BaseModel {
2
- id?: string;
3
- }
4
- export interface ModelDefinition<T extends BaseModel> {
5
- name: string;
6
- connectionName: string;
7
- }
8
- export interface QueryOptions {
9
- filter?: Record<string, any>;
10
- limit?: number;
11
- offset?: number;
12
- sort?: Record<string, 1 | -1>;
13
- }
14
- export interface ModelOperations<T extends BaseModel> {
15
- find(options?: QueryOptions): Promise<T[]>;
16
- findById(id: string): Promise<T | null>;
17
- create(data: Omit<T, 'id'>): Promise<T>;
18
- update(id: string, data: Partial<Omit<T, 'id'>>): Promise<T | null>;
19
- delete(id: string): Promise<boolean>;
20
- }
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,8 +0,0 @@
1
- import { BaseModel, ModelDefinition, ModelOperations } from './model';
2
- declare class ModelManager {
3
- private models;
4
- registerModel<T extends BaseModel>(definition: ModelDefinition<T>): void;
5
- getModel<T extends BaseModel>(name: string): ModelOperations<T>;
6
- }
7
- export declare const modelManager: ModelManager;
8
- export {};
@@ -1,38 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.modelManager = void 0;
4
- const connectionManager_1 = require("./connectionManager");
5
- const sqlAdapter_1 = require("./sqlAdapter");
6
- const mongoAdapter_1 = require("./mongoAdapter");
7
- const mongodb_1 = require("mongodb");
8
- class ModelManager {
9
- constructor() {
10
- this.models = new Map();
11
- }
12
- registerModel(definition) {
13
- const client = connectionManager_1.connectionManager.getClient(definition.connectionName);
14
- if (!client) {
15
- throw new Error(`Connection '${definition.connectionName}' not found for model '${definition.name}'`);
16
- }
17
- let adapter;
18
- if (client instanceof mongodb_1.Pool) {
19
- adapter = new sqlAdapter_1.SqlAdapter(client, definition.name.toLowerCase() + 's'); // Assuming table name is plural of model name
20
- }
21
- else if (client instanceof mongodb_1.MongoClient) {
22
- adapter = new mongoAdapter_1.MongoAdapter(client, definition.name.toLowerCase() + 's'); // Assuming collection name is plural of model name
23
- }
24
- else {
25
- throw new Error(`Unsupported client type for connection '${definition.connectionName}'`);
26
- }
27
- this.models.set(definition.name, adapter);
28
- console.log(`Model '${definition.name}' registered with connection '${definition.connectionName}'`);
29
- }
30
- getModel(name) {
31
- const model = this.models.get(name);
32
- if (!model) {
33
- throw new Error(`Model '${name}' not found. Make sure it is registered.`);
34
- }
35
- return model;
36
- }
37
- }
38
- exports.modelManager = new ModelManager();
@@ -1,3 +0,0 @@
1
- import { Model } from './Model';
2
- export declare const defineModel: (name: string, connectionId: string, tableName: string) => void;
3
- export declare const getModel: (name: string) => Model<any>;
@@ -1,17 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getModel = exports.defineModel = void 0;
4
- const Model_1 = require("./Model");
5
- const models = {};
6
- const defineModel = (name, connectionId, tableName) => {
7
- models[name] = new Model_1.Model(connectionId, tableName);
8
- };
9
- exports.defineModel = defineModel;
10
- const getModel = (name) => {
11
- const model = models[name];
12
- if (!model) {
13
- throw new Error(`Model ${name} not defined.`);
14
- }
15
- return model;
16
- };
17
- exports.getModel = getModel;
@@ -1,11 +0,0 @@
1
- import { MongoClient } from 'mongodb';
2
- import { BaseModel, ModelOperations, QueryOptions } from './model';
3
- export declare class MongoAdapter<T extends BaseModel> implements ModelOperations<T> {
4
- private collection;
5
- constructor(client: MongoClient, collectionName: string);
6
- find(options?: QueryOptions): Promise<T[]>;
7
- findById(id: string): Promise<T | null>;
8
- create(data: Omit<T, 'id'>): Promise<T>;
9
- update(id: string, data: Partial<Omit<T, 'id'>>): Promise<T | null>;
10
- delete(id: string): Promise<boolean>;
11
- }
@@ -1,42 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MongoAdapter = void 0;
4
- const mongodb_1 = require("mongodb");
5
- class MongoAdapter {
6
- constructor(client, collectionName) {
7
- // Assuming a default database name for now, or it could be passed in config
8
- const db = client.db();
9
- this.collection = db.collection(collectionName);
10
- }
11
- async find(options) {
12
- let cursor = this.collection.find(options?.filter || {});
13
- if (options?.sort) {
14
- cursor = cursor.sort(options.sort);
15
- }
16
- if (options?.limit) {
17
- cursor = cursor.limit(options.limit);
18
- }
19
- if (options?.offset) {
20
- cursor = cursor.skip(options.offset);
21
- }
22
- const result = await cursor.toArray();
23
- return result.map(doc => ({ ...doc, id: doc._id?.toString() }));
24
- }
25
- async findById(id) {
26
- const doc = await this.collection.findOne({ _id: new mongodb_1.ObjectId(id) });
27
- return doc ? { ...doc, id: doc._id?.toString() } : null;
28
- }
29
- async create(data) {
30
- const result = await this.collection.insertOne(data);
31
- return { ...data, id: result.insertedId.toString() };
32
- }
33
- async update(id, data) {
34
- const result = await this.collection.findOneAndUpdate({ _id: new mongodb_1.ObjectId(id) }, { $set: data }, { returnDocument: 'after' });
35
- return result.value ? { ...result.value, id: result.value._id?.toString() } : null;
36
- }
37
- async delete(id) {
38
- const result = await this.collection.deleteOne({ _id: new mongodb_1.ObjectId(id) });
39
- return result.deletedCount > 0;
40
- }
41
- }
42
- exports.MongoAdapter = MongoAdapter;
@@ -1,12 +0,0 @@
1
- import { Pool } from 'pg';
2
- import { BaseModel, ModelOperations, QueryOptions } from './model';
3
- export declare class SqlAdapter<T extends BaseModel> implements ModelOperations<T> {
4
- private client;
5
- private tableName;
6
- constructor(client: Pool, tableName: string);
7
- find(options?: QueryOptions): Promise<T[]>;
8
- findById(id: string): Promise<T | null>;
9
- create(data: Omit<T, 'id'>): Promise<T>;
10
- update(id: string, data: Partial<Omit<T, 'id'>>): Promise<T | null>;
11
- delete(id: string): Promise<boolean>;
12
- }
@@ -1,68 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SqlAdapter = void 0;
4
- class SqlAdapter {
5
- constructor(client, tableName) {
6
- this.client = client;
7
- this.tableName = tableName;
8
- }
9
- async find(options) {
10
- let query = `SELECT * FROM ${this.tableName}`;
11
- const values = [];
12
- const conditions = [];
13
- let paramIndex = 1;
14
- if (options?.filter) {
15
- for (const key in options.filter) {
16
- conditions.push(`${key} = $${paramIndex++}`);
17
- values.push(options.filter[key]);
18
- }
19
- }
20
- if (conditions.length > 0) {
21
- query += ` WHERE ${conditions.join(' AND ')}`;
22
- }
23
- if (options?.sort) {
24
- const sortKeys = Object.keys(options.sort);
25
- if (sortKeys.length > 0) {
26
- const orderBy = sortKeys.map(key => `${key} ${options.sort[key] === 1 ? 'ASC' : 'DESC'}`).join(', ');
27
- query += ` ORDER BY ${orderBy}`;
28
- }
29
- }
30
- if (options?.limit) {
31
- query += ` LIMIT $${paramIndex++}`;
32
- values.push(options.limit);
33
- }
34
- if (options?.offset) {
35
- query += ` OFFSET $${paramIndex++}`;
36
- values.push(options.offset);
37
- }
38
- const result = await this.client.query(query, values);
39
- return result.rows;
40
- }
41
- async findById(id) {
42
- const query = `SELECT * FROM ${this.tableName} WHERE id = $1`;
43
- const result = await this.client.query(query, [id]);
44
- return result.rows[0] || null;
45
- }
46
- async create(data) {
47
- const keys = Object.keys(data);
48
- const values = Object.values(data);
49
- const placeholders = keys.map((_, i) => `$${i + 1}`).join(', ');
50
- const query = `INSERT INTO ${this.tableName} (${keys.join(', ')}) VALUES (${placeholders}) RETURNING *`;
51
- const result = await this.client.query(query, values);
52
- return result.rows[0];
53
- }
54
- async update(id, data) {
55
- const keys = Object.keys(data);
56
- const values = Object.values(data);
57
- const setClauses = keys.map((key, i) => `${key} = $${i + 1}`).join(', ');
58
- const query = `UPDATE ${this.tableName} SET ${setClauses} WHERE id = $${keys.length + 1} RETURNING *`;
59
- const result = await this.client.query(query, [...values, id]);
60
- return result.rows[0] || null;
61
- }
62
- async delete(id) {
63
- const query = `DELETE FROM ${this.tableName} WHERE id = $1`;
64
- const result = await this.client.query(query, [id]);
65
- return result.rowCount > 0;
66
- }
67
- }
68
- exports.SqlAdapter = SqlAdapter;
@@ -1,2 +0,0 @@
1
- export { registerModel } from './registerModel';
2
- export { getModel } from './modelRegistry';
@@ -1,7 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getModel = exports.registerModel = void 0;
4
- var registerModel_1 = require("./registerModel");
5
- Object.defineProperty(exports, "registerModel", { enumerable: true, get: function () { return registerModel_1.registerModel; } });
6
- var modelRegistry_1 = require("./modelRegistry");
7
- Object.defineProperty(exports, "getModel", { enumerable: true, get: function () { return modelRegistry_1.getModel; } });
@@ -1,3 +0,0 @@
1
- import { Model } from './Model';
2
- export declare const defineModel: (name: string, connectionId: string, tableName: string) => void;
3
- export declare const getModel: (name: string) => Model<any>;
@@ -1,17 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getModel = exports.defineModel = void 0;
4
- const Model_1 = require("./Model");
5
- const models = {};
6
- const defineModel = (name, connectionId, tableName) => {
7
- models[name] = new Model_1.Model(connectionId, tableName);
8
- };
9
- exports.defineModel = defineModel;
10
- const getModel = (name) => {
11
- const model = models[name];
12
- if (!model) {
13
- throw new Error(`Model ${name} not defined.`);
14
- }
15
- return model;
16
- };
17
- exports.getModel = getModel;
@@ -1 +0,0 @@
1
- export declare const registerModel: (name: string, connectionId: string, tableName: string) => void;
@@ -1,8 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.registerModel = void 0;
4
- const modelRegistry_1 = require("./modelRegistry");
5
- const registerModel = (name, connectionId, tableName) => {
6
- (0, modelRegistry_1.defineModel)(name, connectionId, tableName);
7
- };
8
- exports.registerModel = registerModel;
@@ -1,2 +0,0 @@
1
- import { StorageAdapter, StorageProvider } from '../types';
2
- export declare const createStorageProvider: (providers: StorageProvider[]) => StorageAdapter;
@@ -1,12 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createStorageProvider = void 0;
4
- const s3_1 = require("../adapters/storage/s3");
5
- const createStorageProvider = (providers) => {
6
- const s3Provider = providers.find(p => p.type === 's3');
7
- if (s3Provider) {
8
- return new s3_1.S3Adapter(s3Provider.config);
9
- }
10
- throw new Error('No storage provider configured.');
11
- };
12
- exports.createStorageProvider = createStorageProvider;