streamby-core 0.21.2 β†’ 0.21.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.
package/README.md CHANGED
@@ -1,206 +1,206 @@
1
- # @streamby/core
2
-
3
- Middleware framework for building storage-agnostic media APIs.
4
- Part of the [StreamBy](https://streamby.nhexa.cl) ecosystem by TerminalCore Labs.
5
-
6
- ---
7
-
8
- ## πŸš€ What is it?
9
-
10
- `@streamby/core` is a plug-and-play middleware for Express (or compatible frameworks) that enables file uploads, listings and **multi-project access** over services like:
11
-
12
- - βœ… AWS S3
13
- - βœ… Google Cloud Storage (soon)
14
- - βœ… Cloudflare R2 (soon)
15
- - βœ… Local/Personal servers (soon)
16
-
17
- It's designed to be installed inside your existing API as a library β€” **no need to run a separate backend**.
18
-
19
- ---
20
-
21
- ## πŸ“¦ Installation
22
-
23
- ```bash
24
- npm install @streamby/core
25
- ```
26
-
27
- ---
28
-
29
- ## 🧱 Basic usage
30
-
31
- ```ts
32
- import express from 'express';
33
- import { createStreamByRouter } from '@streamby/core';
34
-
35
- const app = express();
36
-
37
- app.use('/streamby', createStreamByRouter({
38
- storageProvider: {
39
- type: 's3',
40
- config: {
41
- bucket: 'your-bucket-name',
42
- region: 'your-region',
43
- accessKeyId: 'YOUR_AWS_KEY',
44
- secretAccessKey: 'YOUR_AWS_SECRET'
45
- }
46
- },
47
- authProvider: async (req) => {
48
- // extract token/cookie and validate
49
- return {
50
- userId: 'demo',
51
- projects: ['demo-project'],
52
- role: 'admin',
53
- };
54
- },
55
- projectProvider: async (projectId) => {
56
- // fetch project from your DB
57
- return {
58
- id: projectId,
59
- name: 'Demo Project',
60
- description: 'Demo for StreamBy integration',
61
- rootFolders: [],
62
- settings: { allowUpload: true }
63
- };
64
- }
65
- }));
66
-
67
- app.listen(3000);
68
- ```
69
-
70
- ---
71
-
72
- ## πŸ§ͺ Testing
73
-
74
- ```bash
75
- npm run test
76
- ```
77
-
78
- Unit tests use [Vitest](https://vitest.dev) and [Supertest](https://www.npmjs.com/package/supertest).
79
-
80
- ---
81
-
82
- ## πŸ“ Features
83
-
84
- - πŸ“‚ Multi-project access control
85
- - πŸ” Project-aware file uploads & listings
86
- - 🧹 Modular adapters per storage provider
87
- - 🧰 Built-in testability with mock auth & storage
88
- - ✨ Simple to extend for custom business logic
89
-
90
- ---
91
-
92
- ## πŸ—ΊοΈ API Endpoints
93
-
94
- Here's a summary of the key API endpoints provided by `@streamby/core`:
95
-
96
- ### `GET /streamby/projects`
97
-
98
- Lists all projects accessible by the authenticated user.
99
-
100
- **Query Parameters:**
101
- - `archived`: (Optional) Filter projects by their archived status.
102
- - `true`: Returns only archived projects.
103
- - `false`: Returns only unarchived projects.
104
- - (Omitted): Returns all projects (both archived and unarchived).
105
-
106
- **Example Response:**
107
- ```json
108
- {
109
- "projects": [
110
- {
111
- "id": "project1_id",
112
- "dbType": "nosql",
113
- "name": "My NoSQL Project",
114
- "image": "url_to_image",
115
- "archived": false
116
- },
117
- {
118
- "id": "project2_id",
119
- "dbType": "sql",
120
- "name": "My SQL Project",
121
- "image": "url_to_image",
122
- "archived": true
123
- }
124
- ]
125
- }
126
- ```
127
-
128
- ### `PATCH /streamby/projects/:id/archive`
129
-
130
- Archives a specific project. After archiving, it returns the complete list of projects for the user, including the updated project.
131
-
132
- **Example Response:**
133
- ```json
134
- {
135
- "success": true,
136
- "projects": [
137
- {
138
- "id": "project1_id",
139
- "dbType": "nosql",
140
- "name": "My NoSQL Project",
141
- "image": "url_to_image",
142
- "archived": true
143
- },
144
- {
145
- "id": "project2_id",
146
- "dbType": "sql",
147
- "name": "My SQL Project",
148
- "image": "url_to_image",
149
- "archived": false
150
- }
151
- ]
152
- }
153
- ```
154
-
155
- ### `PATCH /streamby/projects/:id/unarchive`
156
-
157
- Unarchives a specific project. After unarchiving, it returns the complete list of projects for the user, including the updated project.
158
-
159
- **Example Response:**
160
- ```json
161
- {
162
- "success": true,
163
- "projects": [
164
- {
165
- "id": "project1_id",
166
- "dbType": "nosql",
167
- "name": "My NoSQL Project",
168
- "image": "url_to_image",
169
- "archived": false
170
- },
171
- {
172
- "id": "project2_id",
173
- "dbType": "sql",
174
- "name": "My SQL Project",
175
- "image": "url_to_image",
176
- "archived": false
177
- }
178
- ]
179
- }
180
- ```
181
-
182
- ---
183
-
184
- ## 🚣 Roadmap
185
-
186
- - [ ] Support for Google Cloud Storage
187
- - [ ] CLI tool for uploading files
188
- - [ ] Role-based access control middleware
189
- - [ ] Plugin system for extended routes
190
- - [ ] Streaming support (HLS, audio, etc.)
191
-
192
- ---
193
-
194
- ## πŸ§‘β€πŸ’» Maintained by
195
-
196
- **TerminalCore Labs** – part of [Nhexa Entertainment](https://nhexa.cl)
197
- Developed as open-source infrastructure for creative and media-oriented apps.
198
-
199
- Visit us [here](https://terminalcore.cl)
200
-
201
- ---
202
-
203
- ## πŸ“Ÿ License
204
-
205
- [MIT](./LICENSE)
206
-
1
+ # @streamby/core
2
+
3
+ Middleware framework for building storage-agnostic media APIs.
4
+ Part of the [StreamBy](https://streamby.nhexa.cl) ecosystem by TerminalCore Labs.
5
+
6
+ ---
7
+
8
+ ## πŸš€ What is it?
9
+
10
+ `@streamby/core` is a plug-and-play middleware for Express (or compatible frameworks) that enables file uploads, listings and **multi-project access** over services like:
11
+
12
+ - βœ… AWS S3
13
+ - βœ… Google Cloud Storage (soon)
14
+ - βœ… Cloudflare R2 (soon)
15
+ - βœ… Local/Personal servers (soon)
16
+
17
+ It's designed to be installed inside your existing API as a library β€” **no need to run a separate backend**.
18
+
19
+ ---
20
+
21
+ ## πŸ“¦ Installation
22
+
23
+ ```bash
24
+ npm install @streamby/core
25
+ ```
26
+
27
+ ---
28
+
29
+ ## 🧱 Basic usage
30
+
31
+ ```ts
32
+ import express from 'express';
33
+ import { createStreamByRouter } from '@streamby/core';
34
+
35
+ const app = express();
36
+
37
+ app.use('/streamby', createStreamByRouter({
38
+ storageProvider: {
39
+ type: 's3',
40
+ config: {
41
+ bucket: 'your-bucket-name',
42
+ region: 'your-region',
43
+ accessKeyId: 'YOUR_AWS_KEY',
44
+ secretAccessKey: 'YOUR_AWS_SECRET'
45
+ }
46
+ },
47
+ authProvider: async (req) => {
48
+ // extract token/cookie and validate
49
+ return {
50
+ userId: 'demo',
51
+ projects: ['demo-project'],
52
+ role: 'admin',
53
+ };
54
+ },
55
+ projectProvider: async (projectId) => {
56
+ // fetch project from your DB
57
+ return {
58
+ id: projectId,
59
+ name: 'Demo Project',
60
+ description: 'Demo for StreamBy integration',
61
+ rootFolders: [],
62
+ settings: { allowUpload: true }
63
+ };
64
+ }
65
+ }));
66
+
67
+ app.listen(3000);
68
+ ```
69
+
70
+ ---
71
+
72
+ ## πŸ§ͺ Testing
73
+
74
+ ```bash
75
+ npm run test
76
+ ```
77
+
78
+ Unit tests use [Vitest](https://vitest.dev) and [Supertest](https://www.npmjs.com/package/supertest).
79
+
80
+ ---
81
+
82
+ ## πŸ“ Features
83
+
84
+ - πŸ“‚ Multi-project access control
85
+ - πŸ” Project-aware file uploads & listings
86
+ - 🧹 Modular adapters per storage provider
87
+ - 🧰 Built-in testability with mock auth & storage
88
+ - ✨ Simple to extend for custom business logic
89
+
90
+ ---
91
+
92
+ ## πŸ—ΊοΈ API Endpoints
93
+
94
+ Here's a summary of the key API endpoints provided by `@streamby/core`:
95
+
96
+ ### `GET /streamby/projects`
97
+
98
+ Lists all projects accessible by the authenticated user.
99
+
100
+ **Query Parameters:**
101
+ - `archived`: (Optional) Filter projects by their archived status.
102
+ - `true`: Returns only archived projects.
103
+ - `false`: Returns only unarchived projects.
104
+ - (Omitted): Returns all projects (both archived and unarchived).
105
+
106
+ **Example Response:**
107
+ ```json
108
+ {
109
+ "projects": [
110
+ {
111
+ "id": "project1_id",
112
+ "dbType": "nosql",
113
+ "name": "My NoSQL Project",
114
+ "image": "url_to_image",
115
+ "archived": false
116
+ },
117
+ {
118
+ "id": "project2_id",
119
+ "dbType": "sql",
120
+ "name": "My SQL Project",
121
+ "image": "url_to_image",
122
+ "archived": true
123
+ }
124
+ ]
125
+ }
126
+ ```
127
+
128
+ ### `PATCH /streamby/projects/:id/archive`
129
+
130
+ Archives a specific project. After archiving, it returns the complete list of projects for the user, including the updated project.
131
+
132
+ **Example Response:**
133
+ ```json
134
+ {
135
+ "success": true,
136
+ "projects": [
137
+ {
138
+ "id": "project1_id",
139
+ "dbType": "nosql",
140
+ "name": "My NoSQL Project",
141
+ "image": "url_to_image",
142
+ "archived": true
143
+ },
144
+ {
145
+ "id": "project2_id",
146
+ "dbType": "sql",
147
+ "name": "My SQL Project",
148
+ "image": "url_to_image",
149
+ "archived": false
150
+ }
151
+ ]
152
+ }
153
+ ```
154
+
155
+ ### `PATCH /streamby/projects/:id/unarchive`
156
+
157
+ Unarchives a specific project. After unarchiving, it returns the complete list of projects for the user, including the updated project.
158
+
159
+ **Example Response:**
160
+ ```json
161
+ {
162
+ "success": true,
163
+ "projects": [
164
+ {
165
+ "id": "project1_id",
166
+ "dbType": "nosql",
167
+ "name": "My NoSQL Project",
168
+ "image": "url_to_image",
169
+ "archived": false
170
+ },
171
+ {
172
+ "id": "project2_id",
173
+ "dbType": "sql",
174
+ "name": "My SQL Project",
175
+ "image": "url_to_image",
176
+ "archived": false
177
+ }
178
+ ]
179
+ }
180
+ ```
181
+
182
+ ---
183
+
184
+ ## 🚣 Roadmap
185
+
186
+ - [ ] Support for Google Cloud Storage
187
+ - [ ] CLI tool for uploading files
188
+ - [ ] Role-based access control middleware
189
+ - [ ] Plugin system for extended routes
190
+ - [ ] Streaming support (HLS, audio, etc.)
191
+
192
+ ---
193
+
194
+ ## πŸ§‘β€πŸ’» Maintained by
195
+
196
+ **TerminalCore Labs** – part of [Nhexa Entertainment](https://nhexa.cl)
197
+ Developed as open-source infrastructure for creative and media-oriented apps.
198
+
199
+ Visit us [here](https://terminalcore.cl)
200
+
201
+ ---
202
+
203
+ ## πŸ“Ÿ License
204
+
205
+ [MIT](./LICENSE)
206
+
@@ -49,6 +49,7 @@ const ensureTablesExist = async (pool) => {
49
49
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
50
50
  name VARCHAR(255) NOT NULL,
51
51
  description TEXT,
52
+ image TEXT,
52
53
  "createdAt" TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
53
54
  "updatedAt" TIMESTAMP WITH TIME ZONE DEFAULT NOW()
54
55
  );
@@ -54,12 +54,15 @@ class S3Adapter {
54
54
  return await (0, s3_request_presigner_1.getSignedUrl)(this.s3, command, { expiresIn: 3600 });
55
55
  }
56
56
  async getPresignedProjectImageUrl(projectId) {
57
+ const key = `${projectId}/project-image`;
57
58
  const command = new client_s3_1.PutObjectCommand({
58
59
  Bucket: this.bucket,
59
- Key: `${projectId}/project-image`,
60
+ Key: key,
60
61
  ContentType: 'image/jpeg',
61
62
  });
62
- return await (0, s3_request_presigner_1.getSignedUrl)(this.s3, command, { expiresIn: 3600 });
63
+ const url = await (0, s3_request_presigner_1.getSignedUrl)(this.s3, command, { expiresIn: 3600 });
64
+ const publicUrl = `https://${this.bucket}.s3.amazonaws.com/${key}`;
65
+ return { url, publicUrl };
63
66
  }
64
67
  }
65
68
  exports.S3Adapter = S3Adapter;
@@ -21,6 +21,10 @@ function createStreamByRouter(config) {
21
21
  const allDbIds = config.databases.map(db => db.id);
22
22
  (0, manager_1.registerModel)('projects', allDbIds, 'projects');
23
23
  (0, manager_1.registerModel)('exports', allDbIds, 'exports');
24
+ const mainDb = config.databases.find(db => db.main);
25
+ if (mainDb) {
26
+ (0, manager_1.registerModel)('users', [mainDb.id], 'users');
27
+ }
24
28
  }
25
29
  router.use((0, auth_1.authRouter)(config));
26
30
  router.use((0, database_1.databaseRouter)(config));
@@ -25,8 +25,8 @@ function fileRouter(config) {
25
25
  if (!projectId) {
26
26
  return res.status(400).json({ error: 'Missing projectId' });
27
27
  }
28
- const url = await (0, presign_1.getPresignedProjectImageUrl)(adapter, projectId);
29
- res.json(url);
28
+ const response = await (0, presign_1.getPresignedProjectImageUrl)(adapter, projectId);
29
+ res.status(200).json(response);
30
30
  }
31
31
  catch (err) {
32
32
  res.status(500).json({ error: 'Failed to generate presigned URL', details: err.message });
@@ -58,12 +58,23 @@ function projectRouter(config) {
58
58
  if (auth.role !== 'admin' && auth.role !== 'editor') {
59
59
  return res.status(403).json({ error: 'Permission denied' });
60
60
  }
61
- const { name, description, dbType } = req.body;
61
+ const { name, description, dbType, image } = req.body;
62
+ const mainDb = config.databases?.find(db => db.main);
63
+ if (!mainDb) {
64
+ return res.status(500).json({ error: 'Main database not configured' });
65
+ }
66
+ const userDbType = mainDb.type;
67
+ const User = (0, manager_1.getModel)('users', userDbType);
68
+ const user = await User.findOne({ _id: auth.userId });
69
+ if (!user) {
70
+ return res.status(404).json({ error: 'User not found' });
71
+ }
62
72
  const newProject = await Project.create({
63
73
  dbType: dbType || 'nosql',
64
74
  name,
65
75
  description: description || '',
66
- members: [{ userId: auth.userId, role: "admin", archived: false }]
76
+ image: image || '',
77
+ members: [{ userId: auth.userId, username: user.username, role: "admin", archived: false }]
67
78
  });
68
79
  res.status(201).json({ project: { ...newProject, id: newProject._id || newProject.id, _id: undefined } });
69
80
  }
@@ -221,11 +232,59 @@ function projectRouter(config) {
221
232
  if (!(0, auth_1.isProjectMember)(project, auth.userId)) {
222
233
  return res.status(403).json({ error: 'Unauthorized project access' });
223
234
  }
224
- res.json({ members: project.members });
235
+ const mainDb = config.databases?.find(db => db.main);
236
+ if (!mainDb) {
237
+ return res.status(500).json({ error: 'Main database not configured' });
238
+ }
239
+ const userDbType = mainDb.type;
240
+ const User = (0, manager_1.getModel)('users', userDbType);
241
+ const membersWithUsernames = await Promise.all(project.members.map(async (member) => {
242
+ const user = await User.findOne({ _id: member.userId });
243
+ return {
244
+ userId: member.userId,
245
+ username: user ? user.username : 'Unknown',
246
+ role: member.role,
247
+ profilePic: user ? user.profilePic : ''
248
+ };
249
+ }));
250
+ res.json({ members: membersWithUsernames });
225
251
  }
226
252
  catch (err) {
227
253
  res.status(500).json({ error: 'Failed to fetch project members', details: err.message });
228
254
  }
229
255
  });
256
+ router.post('/projects/:id/image', async (req, res) => {
257
+ try {
258
+ const auth = await config.authProvider(req);
259
+ if (!auth ||
260
+ !auth.userId ||
261
+ !auth.role) {
262
+ return res.status(401).json({ error: 'Unauthorized' });
263
+ }
264
+ if (auth.role !== 'admin' && auth.role !== 'editor') {
265
+ return res.status(403).json({ error: 'Permission denied' });
266
+ }
267
+ const projectId = req.params.id;
268
+ const { imageUrl } = req.body;
269
+ if (!projectId || !imageUrl) {
270
+ return res.status(400).json({ error: 'Missing projectId or imageUrl' });
271
+ }
272
+ const project = await Project.findOne({ _id: projectId });
273
+ if (!project) {
274
+ return res.status(404).json({ error: 'Project not found' });
275
+ }
276
+ if (!(0, auth_1.isProjectMember)(project, auth.userId)) {
277
+ return res.status(403).json({ error: 'Unauthorized project access' });
278
+ }
279
+ const updatedProject = await Project.update({ _id: projectId }, { image: imageUrl });
280
+ if (!updatedProject) {
281
+ return res.status(404).json({ error: 'Project not found or not updated' });
282
+ }
283
+ res.status(200).json({ success: true, project: { ...updatedProject, id: updatedProject._id || updatedProject.id, _id: undefined } });
284
+ }
285
+ catch (err) {
286
+ res.status(500).json({ error: 'Failed to update project image', details: err.message });
287
+ }
288
+ });
230
289
  return router;
231
290
  }
@@ -3,6 +3,7 @@ export declare class Model<T extends Document> {
3
3
  private connectionIds;
4
4
  private tableName;
5
5
  constructor(connectionIds: string[], tableName: string);
6
+ useDbType(dbType: string): Model<T>;
6
7
  find(filter: any): Promise<T[]>;
7
8
  private transformResult;
8
9
  findOne(filter: any): Promise<T | null>;
@@ -10,6 +10,13 @@ class Model {
10
10
  this.connectionIds = connectionIds;
11
11
  this.tableName = tableName;
12
12
  }
13
+ useDbType(dbType) {
14
+ const filteredConnectionIds = this.connectionIds.filter(id => {
15
+ const connection = (0, connectionManager_1.getConnection)(id);
16
+ return connection.type === dbType;
17
+ });
18
+ return new Model(filteredConnectionIds, this.tableName);
19
+ }
13
20
  async find(filter) {
14
21
  const allResults = [];
15
22
  const activeConnectionIds = this.connectionIds.filter(id => (0, connectionManager_1.getConnectedIds)().includes(id));
@@ -156,6 +163,7 @@ class Model {
156
163
  await sql_1.sqlAdapter.create(connection, 'project_members', {
157
164
  projectId: created.id,
158
165
  userId: member.userId,
166
+ role: member.role,
159
167
  archived: member.archived || false,
160
168
  });
161
169
  }
@@ -169,71 +177,89 @@ class Model {
169
177
  return data;
170
178
  }
171
179
  async update(filter, data) {
172
- const activeConnectionIds = this.connectionIds.filter(id => (0, connectionManager_1.getConnectedIds)().includes(id));
173
- for (const connectionId of activeConnectionIds) {
174
- const clientEntry = (0, connectionManager_1.getConnection)(connectionId);
175
- const connection = clientEntry.client;
176
- const dbType = clientEntry.type;
177
- let processedFilter = { ...filter };
178
- // Handle specific member archiving/unarchiving
179
- if (data["members.$.archived"] !== undefined && processedFilter["_id"] && processedFilter["members.userId"]) {
180
- const projectId = processedFilter["_id"];
181
- const userIdToUpdate = processedFilter["members.userId"];
182
- const newArchivedStatus = data["members.$.archived"];
183
- const archivedBy = data["members.$.archivedBy"];
184
- const archivedAt = data["members.$.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;
192
- }
180
+ const existingProject = await this.findOne(filter); // Find the project first
181
+ if (!existingProject) {
182
+ return null; // Project not found
183
+ }
184
+ const targetDbType = existingProject.dbType; // Get the actual dbType of the project
185
+ // Find the connection that matches the targetDbType
186
+ const clientEntry = this.connectionIds
187
+ .map(id => (0, connectionManager_1.getConnection)(id))
188
+ .find(entry => entry.type === targetDbType);
189
+ if (!clientEntry) {
190
+ throw new Error(`No active connection found for database type: ${targetDbType}`);
191
+ }
192
+ const connection = clientEntry.client;
193
+ const dbType = clientEntry.type; // This will be the targetDbType
194
+ let updateFilter = {}; // Initialize updateFilter here
195
+ // Construct the updateFilter based on the actual dbType of the project
196
+ if (dbType === 'sql') {
197
+ updateFilter.id = existingProject.id; // Use the 'id' from the existingProject
198
+ }
199
+ else if (dbType === 'nosql') {
200
+ // Ensure _id is an ObjectId for NoSQL updates
201
+ if (existingProject._id && typeof existingProject._id === 'string') {
202
+ try {
203
+ updateFilter._id = new mongodb_1.ObjectId(existingProject._id);
193
204
  }
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;
205
+ catch (e) {
206
+ // If existingProject._id is not a valid ObjectId string, it's an error for NoSQL
207
+ return null; // Or throw a more specific error
219
208
  }
220
209
  }
221
210
  else {
222
- // General update logic
223
- if (dbType === 'sql') {
224
- if (processedFilter._id) {
225
- processedFilter.id = processedFilter._id;
226
- delete processedFilter._id;
211
+ updateFilter._id = existingProject._id; // Already an ObjectId or other valid type
212
+ }
213
+ }
214
+ // Handle specific member archiving/unarchiving
215
+ if (data["members.$.archived"] !== undefined && filter["_id"] && filter["members.userId"]) { // Use original filter for projectId and userIdToUpdate
216
+ const originalProjectId = filter["_id"]; // Use the original projectId from the request filter
217
+ const userIdToUpdate = filter["members.userId"];
218
+ const newArchivedStatus = data["members.$.archived"];
219
+ const archivedBy = data["members.$.archivedBy"];
220
+ const archivedAt = data["members.$.archivedAt"];
221
+ if (dbType === 'sql') {
222
+ // For SQL, directly update the project_members table
223
+ const memberUpdateResult = await sql_1.sqlAdapter.update(connection, 'project_members', { projectId: originalProjectId, userId: userIdToUpdate }, // originalProjectId is fine for SQL
224
+ { archived: newArchivedStatus, archivedBy: archivedBy, archivedAt: archivedAt });
225
+ // After updating the member, fetch the full project to return
226
+ if (memberUpdateResult) {
227
+ const updatedProject = await this.findOne({ _id: originalProjectId });
228
+ return updatedProject;
229
+ }
230
+ }
231
+ else if (dbType === 'nosql') {
232
+ const projectToUpdate = existingProject; // Already fetched
233
+ const updatedMembers = projectToUpdate.members.map((member) => {
234
+ if (member.userId === userIdToUpdate) {
235
+ return { ...member, archived: newArchivedStatus, archivedBy: archivedBy, archivedAt: archivedAt };
227
236
  }
228
- const result = await sql_1.sqlAdapter.update(connection, this.tableName, processedFilter, data);
229
- if (result)
230
- return result;
237
+ return member;
238
+ });
239
+ let objectIdOriginalProjectId;
240
+ try {
241
+ objectIdOriginalProjectId = new mongodb_1.ObjectId(originalProjectId); // Convert originalProjectId to ObjectId for NoSQL
231
242
  }
232
- else if (dbType === 'nosql') {
233
- const result = await nosql_1.nosqlAdapter.update(connection, this.tableName, processedFilter, data);
234
- if (result)
235
- return result;
243
+ catch (e) {
244
+ return null;
236
245
  }
246
+ const result = await nosql_1.nosqlAdapter.update(connection, this.tableName, { _id: objectIdOriginalProjectId }, { members: updatedMembers });
247
+ if (result)
248
+ return result;
249
+ }
250
+ }
251
+ else {
252
+ // General update logic
253
+ // Use the correctly constructed updateFilter
254
+ if (dbType === 'sql') {
255
+ const result = await sql_1.sqlAdapter.update(connection, this.tableName, updateFilter, data);
256
+ if (result)
257
+ return result;
258
+ }
259
+ else if (dbType === 'nosql') {
260
+ const result = await nosql_1.nosqlAdapter.update(connection, this.tableName, updateFilter, data);
261
+ if (result)
262
+ return result;
237
263
  }
238
264
  }
239
265
  return null;
@@ -1,3 +1,3 @@
1
1
  import { Model } from './Model';
2
2
  export declare const defineModel: (name: string, connectionIds: string[], tableName: string) => void;
3
- export declare const getModel: (name: string) => Model<any>;
3
+ export declare const getModel: (name: string, dbType?: string) => Model<any>;
@@ -7,11 +7,14 @@ const defineModel = (name, connectionIds, tableName) => {
7
7
  models[name] = new Model_1.Model(connectionIds, tableName);
8
8
  };
9
9
  exports.defineModel = defineModel;
10
- const getModel = (name) => {
10
+ const getModel = (name, dbType) => {
11
11
  const model = models[name];
12
12
  if (!model) {
13
13
  throw new Error(`Model ${name} not defined.`);
14
14
  }
15
+ if (dbType) {
16
+ return model.useDbType(dbType);
17
+ }
15
18
  return model;
16
19
  };
17
20
  exports.getModel = getModel;
@@ -50,6 +50,7 @@ export interface DatabaseCredential {
50
50
  id: string;
51
51
  type: DatabaseType;
52
52
  connectionString?: string;
53
+ main?: boolean;
53
54
  }
54
55
  export interface StreamByConfig {
55
56
  storageProviders: {
package/package.json CHANGED
@@ -1,60 +1,60 @@
1
- {
2
- "name": "streamby-core",
3
- "version": "0.21.2",
4
- "description": "StreamBy middleware framework for media storage management",
5
- "main": "dist/index.js",
6
- "types": "dist/index.d.ts",
7
- "files": [
8
- "dist"
9
- ],
10
- "scripts": {
11
- "build": "tsc",
12
- "test": "vitest",
13
- "dev": "ts-node-dev --respawn --clear dev.ts",
14
- "prepublishOnly": "npm run build"
15
- },
16
- "repository": {
17
- "type": "git",
18
- "url": "https://github.com/GwerhDev/StreamBy-Package.git"
19
- },
20
- "keywords": [
21
- "streamby",
22
- "middleware",
23
- "upload",
24
- "storage",
25
- "s3",
26
- "express",
27
- "typescript"
28
- ],
29
- "author": "TerminalCore Labs",
30
- "license": "MIT",
31
- "dependencies": {
32
- "@aws-sdk/client-s3": "^3.528.0",
33
- "@aws-sdk/s3-request-presigner": "^3.787.0",
34
- "@prisma/client": "^6.12.0",
35
- "bcrypt": "^5.1.1",
36
- "dotenv": "^16.5.0",
37
- "express": "^4.0.0",
38
- "mongodb": "^6.17.0",
39
- "mongoose": "^8.13.2",
40
- "pg": "^8.16.3",
41
- "prisma": "^6.12.0"
42
- },
43
- "devDependencies": {
44
- "@types/bcrypt": "^5.0.2",
45
- "@types/cors": "^2.8.18",
46
- "@types/express": "^4.17.17",
47
- "@types/mongodb": "^4.0.7",
48
- "@types/node": "^22.15.21",
49
- "@types/pg": "^8.15.4",
50
- "@types/supertest": "^6.0.3",
51
- "cors": "^2.8.5",
52
- "supertest": "^7.1.0",
53
- "ts-node-dev": "^2.0.0",
54
- "typescript": "^5.8.3",
55
- "vitest": "^3.1.1"
56
- },
57
- "peerDependencies": {
58
- "express": "^4.0.0"
59
- }
60
- }
1
+ {
2
+ "name": "streamby-core",
3
+ "version": "0.21.4",
4
+ "description": "StreamBy middleware framework for media storage management",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "files": [
8
+ "dist"
9
+ ],
10
+ "scripts": {
11
+ "build": "tsc",
12
+ "test": "vitest",
13
+ "dev": "ts-node-dev --respawn --clear dev.ts",
14
+ "prepublishOnly": "npm run build"
15
+ },
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "https://github.com/GwerhDev/StreamBy-Package.git"
19
+ },
20
+ "keywords": [
21
+ "streamby",
22
+ "middleware",
23
+ "upload",
24
+ "storage",
25
+ "s3",
26
+ "express",
27
+ "typescript"
28
+ ],
29
+ "author": "TerminalCore Labs",
30
+ "license": "MIT",
31
+ "dependencies": {
32
+ "@aws-sdk/client-s3": "^3.528.0",
33
+ "@aws-sdk/s3-request-presigner": "^3.787.0",
34
+ "@prisma/client": "^6.12.0",
35
+ "bcrypt": "^5.1.1",
36
+ "dotenv": "^16.5.0",
37
+ "express": "^4.0.0",
38
+ "mongodb": "^6.17.0",
39
+ "mongoose": "^8.13.2",
40
+ "pg": "^8.16.3",
41
+ "prisma": "^6.12.0"
42
+ },
43
+ "devDependencies": {
44
+ "@types/bcrypt": "^5.0.2",
45
+ "@types/cors": "^2.8.18",
46
+ "@types/express": "^4.17.17",
47
+ "@types/mongodb": "^4.0.7",
48
+ "@types/node": "^22.15.21",
49
+ "@types/pg": "^8.15.4",
50
+ "@types/supertest": "^6.0.3",
51
+ "cors": "^2.8.5",
52
+ "supertest": "^7.1.0",
53
+ "ts-node-dev": "^2.0.0",
54
+ "typescript": "^5.8.3",
55
+ "vitest": "^3.1.1"
56
+ },
57
+ "peerDependencies": {
58
+ "express": "^4.0.0"
59
+ }
60
+ }