streamby-core 0.21.8 → 0.23.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.
@@ -1,9 +1,18 @@
1
1
  import { MongoClient, Document } from 'mongodb';
2
+ import { FieldDefinition } from '../../types';
2
3
  export declare const ensureCollectionsExist: (client: MongoClient) => Promise<void>;
4
+ export declare const createNoSQLExportCollection: (connection: MongoClient, projectId: string, exportName: string, fields: FieldDefinition[]) => Promise<{
5
+ collectionName: string;
6
+ exportId: string;
7
+ }>;
8
+ export declare const createNoSQLRawExportCollection: (connection: MongoClient, projectId: string, exportName: string, jsonData: any, method: string) => Promise<{
9
+ collectionName: string;
10
+ exportId: string;
11
+ }>;
3
12
  export declare const nosqlAdapter: {
4
13
  find: (connection: MongoClient, tableName: string, filter: any) => Promise<Document[]>;
5
14
  findOne: (connection: MongoClient, tableName: string, filter: any) => Promise<Document | null>;
6
15
  create: <T extends Document>(connection: MongoClient, tableName: string, data: T) => Promise<T>;
7
- update: (connection: MongoClient, tableName: string, filter: any, data: Partial<Document>) => Promise<Document | null>;
16
+ update: (connection: MongoClient, tableName: string, filter: any, data: Document | Partial<Document>) => Promise<Document | null>;
8
17
  delete: (connection: MongoClient, tableName: string, filter: any) => Promise<number>;
9
18
  };
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.nosqlAdapter = exports.ensureCollectionsExist = void 0;
3
+ exports.nosqlAdapter = exports.createNoSQLRawExportCollection = exports.createNoSQLExportCollection = exports.ensureCollectionsExist = void 0;
4
4
  const mongodb_1 = require("mongodb");
5
5
  const ensureCollectionsExist = async (client) => {
6
6
  const db = client.db();
@@ -16,6 +16,33 @@ const ensureCollectionsExist = async (client) => {
16
16
  console.log('✅ "exports" collection ensured to exist.');
17
17
  };
18
18
  exports.ensureCollectionsExist = ensureCollectionsExist;
19
+ const createNoSQLExportCollection = async (connection, projectId, exportName, fields) => {
20
+ const db = connection.db();
21
+ const slug = exportName.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
22
+ const collectionName = `export_${projectId}_${slug}`;
23
+ // Create the collection implicitly by inserting the metadata document
24
+ const metadataDocument = {
25
+ __metadata: {
26
+ fields,
27
+ createdAt: new Date(),
28
+ updatedAt: new Date(),
29
+ },
30
+ };
31
+ await db.collection(collectionName).insertOne(metadataDocument);
32
+ console.log(`✅ Collection '${collectionName}' created with metadata.`);
33
+ return { collectionName, exportId: collectionName };
34
+ };
35
+ exports.createNoSQLExportCollection = createNoSQLExportCollection;
36
+ const createNoSQLRawExportCollection = async (connection, projectId, exportName, jsonData, method) => {
37
+ const db = connection.db();
38
+ const slug = exportName.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
39
+ const collectionName = `raw_export_${projectId}_${slug}`;
40
+ // Insert the raw JSON data directly into the new collection
41
+ const result = await db.collection(collectionName).insertOne({ json: jsonData, name: exportName, method, collectionName, createdAt: new Date(), updatedAt: new Date() });
42
+ console.log(`✅ Raw collection '${collectionName}' created with provided JSON data.`);
43
+ return { collectionName, exportId: result.insertedId.toHexString() };
44
+ };
45
+ exports.createNoSQLRawExportCollection = createNoSQLRawExportCollection;
19
46
  exports.nosqlAdapter = {
20
47
  find: async (connection, tableName, filter) => {
21
48
  const db = connection.db();
@@ -42,7 +69,10 @@ exports.nosqlAdapter = {
42
69
  if (processedFilter._id && typeof processedFilter._id === 'string') {
43
70
  processedFilter._id = new mongodb_1.ObjectId(processedFilter._id);
44
71
  }
45
- const result = await db.collection(tableName).findOneAndUpdate(processedFilter, { $set: data }, { returnDocument: 'after' });
72
+ // Check if the update data contains MongoDB update operators (e.g., $set, $push)
73
+ const isUpdateOperator = Object.keys(data).some(key => key.startsWith('$'));
74
+ const updateDocument = isUpdateOperator ? data : { $set: data };
75
+ const result = await db.collection(tableName).findOneAndUpdate(processedFilter, updateDocument, { returnDocument: 'after' });
46
76
  if (!result) {
47
77
  return null;
48
78
  }
@@ -1,4 +1,13 @@
1
1
  import { Pool } from 'pg';
2
+ import { FieldDefinition } from '../../types';
3
+ export declare const createSQLExportTable: (connection: Pool, projectId: string, exportName: string, fields: FieldDefinition[]) => Promise<{
4
+ collectionName: string;
5
+ exportId: string;
6
+ }>;
7
+ export declare const createSQLRawExportTable: (connection: Pool, projectId: string, exportName: string, jsonData: any) => Promise<{
8
+ collectionName: string;
9
+ exportId: string;
10
+ }>;
2
11
  export declare const sqlAdapter: {
3
12
  find: (connection: Pool, tableName: string, filter: any) => Promise<any[]>;
4
13
  findOne: (connection: Pool, tableName: string, filter: any) => Promise<any | null>;
@@ -1,6 +1,48 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.sqlAdapter = void 0;
3
+ exports.sqlAdapter = exports.createSQLRawExportTable = exports.createSQLExportTable = void 0;
4
+ const createSQLExportTable = async (connection, projectId, exportName, fields) => {
5
+ const slug = exportName.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
6
+ const tableName = `export_${projectId}_${slug}`;
7
+ const columns = fields.map(field => `"${field.name}" ${field.type}`).join(',');
8
+ const createTableQuery = `
9
+ CREATE TABLE IF NOT EXISTS "${tableName}" (
10
+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
11
+ "projectId" UUID NOT NULL,
12
+ __metadata JSONB NOT NULL,
13
+ ${columns ? `, ${columns}` : ''}
14
+ );
15
+ `;
16
+ await connection.query(createTableQuery);
17
+ console.log(`✅ Table '${tableName}' created with metadata.`);
18
+ const metadata = {
19
+ fields,
20
+ createdAt: new Date(),
21
+ updatedAt: new Date(),
22
+ };
23
+ // Insert metadata as the first row, or a dedicated metadata row
24
+ // For simplicity, we'll just create the table with the metadata column.
25
+ // Actual metadata insertion for validation would happen on data inserts.
26
+ return { collectionName: tableName, exportId: tableName };
27
+ };
28
+ exports.createSQLExportTable = createSQLExportTable;
29
+ const createSQLRawExportTable = async (connection, projectId, exportName, jsonData) => {
30
+ const slug = exportName.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
31
+ const tableName = `raw_export_${projectId}_${slug}`;
32
+ const createTableQuery = `
33
+ CREATE TABLE IF NOT EXISTS "${tableName}" (
34
+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
35
+ data JSONB NOT NULL
36
+ );
37
+ `;
38
+ await connection.query(createTableQuery);
39
+ console.log(`✅ Raw table '${tableName}' created.`);
40
+ // Insert the raw JSON data directly into the new table
41
+ await connection.query(`INSERT INTO "${tableName}" (data) VALUES ($1)`, [jsonData]);
42
+ console.log(`✅ Raw JSON data inserted into table '${tableName}'.`);
43
+ return { collectionName: tableName, exportId: tableName };
44
+ };
45
+ exports.createSQLRawExportTable = createSQLRawExportTable;
4
46
  exports.sqlAdapter = {
5
47
  find: async (connection, tableName, filter) => {
6
48
  const keys = Object.keys(filter);
@@ -10,7 +10,7 @@ const storage_1 = require("../providers/storage");
10
10
  const connectionManager_1 = require("../adapters/database/connectionManager");
11
11
  const auth_1 = require("./routes/auth");
12
12
  const database_1 = require("./routes/database");
13
- const file_1 = require("./routes/file");
13
+ const storage_2 = require("./routes/storage");
14
14
  const project_1 = require("./routes/project");
15
15
  const export_1 = require("./routes/export");
16
16
  function createStreamByRouter(config) {
@@ -28,7 +28,7 @@ function createStreamByRouter(config) {
28
28
  }
29
29
  router.use((0, auth_1.authRouter)(config));
30
30
  router.use((0, database_1.databaseRouter)(config));
31
- router.use((0, file_1.fileRouter)(config));
31
+ router.use((0, storage_2.storageRouter)(config));
32
32
  router.use((0, project_1.projectRouter)(config));
33
33
  router.use((0, export_1.exportRouter)(config));
34
34
  return router;
@@ -4,10 +4,12 @@ exports.exportRouter = exportRouter;
4
4
  const express_1 = require("express");
5
5
  const manager_1 = require("../../models/manager");
6
6
  const auth_1 = require("../../utils/auth");
7
+ const export_1 = require("../../services/export");
8
+ const connectionManager_1 = require("../../adapters/database/connectionManager");
9
+ const mongodb_1 = require("mongodb");
7
10
  function exportRouter(config) {
8
11
  const router = (0, express_1.Router)();
9
12
  const Project = (0, manager_1.getModel)('projects');
10
- const Export = (0, manager_1.getModel)('exports');
11
13
  router.get('/projects/:id/exports/:export_id', async (req, res) => {
12
14
  try {
13
15
  const auth = await config.authProvider(req);
@@ -25,8 +27,33 @@ function exportRouter(config) {
25
27
  if (!(0, auth_1.isProjectMember)(project, auth.userId)) {
26
28
  return res.status(403).json({ message: 'Unauthorized access' });
27
29
  }
28
- const data = await Export.findOne({ _id: exportId });
29
- res.json({ data: { ...data, id: data._id || data.id, _id: undefined }, message: 'Export data fetched successfully' });
30
+ const exportMetadata = project.exports.find((e) => e.id.toString() === exportId);
31
+ if (!exportMetadata) {
32
+ return res.status(404).json({ message: 'Export not found in this project' });
33
+ }
34
+ const targetDb = config.databases?.find(db => db.type === project.dbType);
35
+ if (!targetDb) {
36
+ return res.status(500).json({ message: `Database connection not found for type ${project.dbType}` });
37
+ }
38
+ const connection = (0, connectionManager_1.getConnection)(targetDb.id);
39
+ let data;
40
+ if (project.dbType === 'nosql') {
41
+ const db = connection.client.db();
42
+ if (exportMetadata.type === 'raw') {
43
+ const rawData = await db.collection(exportMetadata.collectionName).findOne({ _id: new mongodb_1.ObjectId(exportId) });
44
+ data = rawData ? { json: rawData.json, name: rawData.name, method: rawData.method, collectionName: rawData.collectionName, createdAt: rawData.createdAt, updatedAt: rawData.updatedAt, type: exportMetadata.type } : null;
45
+ }
46
+ else {
47
+ data = await db.collection(exportMetadata.collectionName).find({ __metadata: { $exists: false } }).toArray();
48
+ }
49
+ }
50
+ else if (project.dbType === 'sql') {
51
+ // ... SQL implementation needed
52
+ }
53
+ if (!data) {
54
+ return res.status(404).json({ message: 'Export data not found' });
55
+ }
56
+ res.json({ data, message: 'Export data fetched successfully' });
30
57
  }
31
58
  catch (err) {
32
59
  res.status(500).json({ message: 'Failed to fetch export data', details: err.message });
@@ -41,25 +68,84 @@ function exportRouter(config) {
41
68
  return res.status(401).json({ message: 'Unauthorized' });
42
69
  }
43
70
  const projectId = req.params.id;
44
- const { name, description, collectionName } = req.body;
45
- if (!name || !collectionName) {
46
- return res.status(400).json({ message: 'Missing export name or collectionName' });
71
+ const { name, description, collectionName, fields } = req.body;
72
+ if (!name || !collectionName || !fields) {
73
+ return res.status(400).json({ message: 'Missing export name, collectionName, or fields' });
47
74
  }
48
75
  const project = await Project.findOne({ _id: projectId });
49
76
  if (!project || !(0, auth_1.isProjectMember)(project, auth.userId)) {
50
77
  return res.status(403).json({ message: 'Unauthorized project access' });
51
78
  }
52
- const newExport = await Export.create({
53
- name,
54
- description,
55
- collectionName,
56
- projectId
57
- });
58
- res.status(201).json({ data: { ...newExport, id: newExport._id || newExport.id, _id: undefined }, message: 'Export created successfully' });
79
+ const result = await (0, export_1.createExport)(config, projectId, name, collectionName, fields, project.dbType);
80
+ res.status(201).json({ data: result, message: result.message });
59
81
  }
60
82
  catch (err) {
61
83
  res.status(500).json({ message: 'Failed to create export', details: err.message });
62
84
  }
63
85
  });
86
+ router.post('/projects/:id/exports/raw', async (req, res) => {
87
+ try {
88
+ const auth = await config.authProvider(req);
89
+ if (!auth ||
90
+ !auth.userId ||
91
+ !auth.role) {
92
+ return res.status(401).json({ message: 'Unauthorized' });
93
+ }
94
+ const projectId = req.params.id;
95
+ const { name, description, collectionName, jsonData } = req.body;
96
+ if (!name || !collectionName || !jsonData) {
97
+ return res.status(400).json({ message: 'Missing export name, collectionName, or jsonData' });
98
+ }
99
+ const project = await Project.findOne({ _id: projectId });
100
+ if (!project || !(0, auth_1.isProjectMember)(project, auth.userId)) {
101
+ return res.status(403).json({ message: 'Unauthorized project access' });
102
+ }
103
+ const result = await (0, export_1.createRawExport)(config, projectId, name, collectionName, jsonData, project.dbType);
104
+ res.status(201).json({ data: result, message: result.message });
105
+ }
106
+ catch (err) {
107
+ res.status(500).json({ message: 'Failed to create raw export', details: err.message });
108
+ }
109
+ });
110
+ router.get('/:projectId/public-export/:exportName', async (req, res) => {
111
+ try {
112
+ const { projectId, exportName } = req.params;
113
+ const project = await Project.findOne({ _id: projectId });
114
+ if (!project) {
115
+ return res.status(404).json({ message: 'Project not found' });
116
+ }
117
+ const exportMetadata = project.exports.find((e) => e.name === exportName);
118
+ if (!exportMetadata) {
119
+ return res.status(404).json({ message: 'Export not found in this project' });
120
+ }
121
+ const targetDb = config.databases?.find(db => db.type === project.dbType);
122
+ if (!targetDb) {
123
+ return res.status(500).json({ message: `Database connection not found for type ${project.dbType}` });
124
+ }
125
+ const connection = (0, connectionManager_1.getConnection)(targetDb.id);
126
+ let data;
127
+ if (project.dbType === 'nosql') {
128
+ const db = connection.client.db();
129
+ if (exportMetadata.type === 'raw') {
130
+ const rawData = await db.collection(exportMetadata.collectionName).findOne({ _id: new mongodb_1.ObjectId(exportMetadata.id) });
131
+ data = rawData ? rawData.json : null;
132
+ }
133
+ else {
134
+ data = await db.collection(exportMetadata.collectionName).find({ __metadata: { $exists: false } }).toArray();
135
+ }
136
+ }
137
+ else if (project.dbType === 'sql') {
138
+ // SQL implementation for public exports will go here
139
+ return res.status(501).json({ message: 'SQL public exports not yet implemented' });
140
+ }
141
+ if (!data) {
142
+ return res.status(404).json({ message: 'Export data not found' });
143
+ }
144
+ res.json(data); // Return the raw data directly
145
+ }
146
+ catch (err) {
147
+ res.status(500).json({ message: 'Failed to fetch public export data', details: err.message });
148
+ }
149
+ });
64
150
  return router;
65
151
  }
@@ -1,5 +1,5 @@
1
1
  import { Router } from 'express';
2
2
  import { StreamByConfig, StorageAdapter } from '../../types';
3
- export declare function fileRouter(config: StreamByConfig & {
3
+ export declare function storageRouter(config: StreamByConfig & {
4
4
  adapter?: StorageAdapter;
5
5
  }): Router;
@@ -1,12 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.fileRouter = fileRouter;
3
+ exports.storageRouter = storageRouter;
4
4
  const express_1 = require("express");
5
5
  const file_1 = require("../../services/file");
6
6
  const presign_1 = require("../../services/presign");
7
7
  const storage_1 = require("../../providers/storage");
8
8
  const manager_1 = require("../../models/manager");
9
- function fileRouter(config) {
9
+ function storageRouter(config) {
10
10
  const router = (0, express_1.Router)();
11
11
  const adapter = config.adapter || (0, storage_1.createStorageProvider)(config.storageProviders);
12
12
  const Project = (0, manager_1.getModel)('projects');
@@ -55,7 +55,7 @@ function fileRouter(config) {
55
55
  res.status(500).json({ message: 'Failed to delete image', details: err.message });
56
56
  }
57
57
  });
58
- router.get('/files', async (req, res) => {
58
+ router.get('/storages', async (req, res) => {
59
59
  try {
60
60
  const auth = await config.authProvider(req);
61
61
  if (!auth ||
@@ -0,0 +1,10 @@
1
+ import { FieldDefinition, DatabaseType } from '../types';
2
+ interface CreateExportResult {
3
+ exportId: string;
4
+ collectionName: string;
5
+ message: string;
6
+ }
7
+ import { StreamByConfig } from '../types';
8
+ export declare function createExport(config: StreamByConfig, projectId: string, exportName: string, collectionName: string, fields: FieldDefinition[], dbType: DatabaseType): Promise<CreateExportResult>;
9
+ export declare function createRawExport(config: StreamByConfig, projectId: string, exportName: string, collectionName: string, jsonData: any, dbType: DatabaseType): Promise<CreateExportResult>;
10
+ export {};
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createExport = createExport;
4
+ exports.createRawExport = createRawExport;
5
+ const manager_1 = require("../models/manager");
6
+ const mongodb_1 = require("mongodb");
7
+ const connectionManager_1 = require("../adapters/database/connectionManager");
8
+ const nosql_1 = require("../adapters/database/nosql");
9
+ const sql_1 = require("../adapters/database/sql");
10
+ async function createExport(config, projectId, exportName, collectionName, fields, dbType) {
11
+ const Project = (0, manager_1.getModel)('projects');
12
+ const project = await Project.findOne({ _id: projectId });
13
+ if (!project) {
14
+ throw new Error('Project not found');
15
+ }
16
+ const targetDb = config.databases?.find(db => db.type === dbType && db.main) ||
17
+ config.databases?.find(db => db.type === dbType);
18
+ if (!targetDb) {
19
+ throw new Error(`Database connection not found for type ${dbType}`);
20
+ }
21
+ const connection = (0, connectionManager_1.getConnection)(targetDb.id);
22
+ let result;
23
+ if (dbType === 'nosql') {
24
+ result = await (0, nosql_1.createNoSQLExportCollection)(connection.client, projectId, exportName, fields);
25
+ }
26
+ else if (dbType === 'sql') {
27
+ result = await (0, sql_1.createSQLExportTable)(connection.client, projectId, exportName, fields);
28
+ }
29
+ else {
30
+ throw new Error('Unsupported database type');
31
+ }
32
+ // Update the project with the new export reference
33
+ // Assuming project metadata is always in NoSQL (MongoDB)
34
+ const NoSQLProject = (0, manager_1.getModel)('projects', 'nosql');
35
+ await NoSQLProject.update({ _id: projectId }, { $push: { exports: { id: result.exportId, collectionName: result.collectionName, type: 'structured', fields, method: 'GET' } } });
36
+ return { ...result, message: 'Export created successfully' };
37
+ }
38
+ async function createRawExport(config, projectId, exportName, collectionName, jsonData, dbType) {
39
+ const targetDb = config.databases?.find(db => db.type === dbType && db.main) ||
40
+ config.databases?.find(db => db.type === dbType);
41
+ if (!targetDb) {
42
+ throw new Error(`Database connection not found for type ${dbType}`);
43
+ }
44
+ const connection = (0, connectionManager_1.getConnection)(targetDb.id);
45
+ let result;
46
+ if (dbType === 'nosql') {
47
+ result = await (0, nosql_1.createNoSQLRawExportCollection)(connection.client, projectId, exportName, jsonData, 'GET');
48
+ }
49
+ else if (dbType === 'sql') {
50
+ result = await (0, sql_1.createSQLRawExportTable)(connection.client, projectId, exportName, jsonData);
51
+ }
52
+ else {
53
+ throw new Error('Unsupported database type');
54
+ }
55
+ // Update the project with the new export reference
56
+ // Assuming project metadata is always in NoSQL (MongoDB)
57
+ const NoSQLProject = (0, manager_1.getModel)('projects', 'nosql');
58
+ await NoSQLProject.update({ _id: projectId }, { $push: { exports: { id: dbType === 'nosql' ? new mongodb_1.ObjectId(result.exportId) : result.exportId, name: exportName, collectionName: result.collectionName, type: 'raw', method: 'GET' } } });
59
+ return { ...result, message: 'Raw export created successfully' };
60
+ }
@@ -17,6 +17,12 @@ export interface StorageAdapter {
17
17
  getPresignedUrl?: (contentType: string, projectId: string) => Promise<any>;
18
18
  getPresignedProjectImageUrl?: (projectId: string) => Promise<any>;
19
19
  }
20
+ export interface FieldDefinition {
21
+ name: string;
22
+ type: string;
23
+ label: string;
24
+ required?: boolean;
25
+ }
20
26
  export interface ProjectInfo {
21
27
  _id?: string;
22
28
  id: string;
@@ -74,4 +80,7 @@ export interface Export {
74
80
  projectId: string;
75
81
  createdAt: Date;
76
82
  updatedAt: Date;
83
+ type: 'structured' | 'raw';
84
+ fields?: FieldDefinition[];
85
+ jsonData?: any;
77
86
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "streamby-core",
3
- "version": "0.21.8",
3
+ "version": "0.23.0",
4
4
  "description": "StreamBy middleware framework for media storage management",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",