@medyll/idae-db 0.0.1

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 ADDED
@@ -0,0 +1,58 @@
1
+ # create-svelte
2
+
3
+ Everything you need to build a Svelte library, powered by [`create-svelte`](https://github.com/sveltejs/kit/tree/main/packages/create-svelte).
4
+
5
+ Read more about creating a library [in the docs](https://kit.svelte.dev/docs/packaging).
6
+
7
+ ## Creating a project
8
+
9
+ If you're seeing this, you've probably already done this step. Congrats!
10
+
11
+ ```bash
12
+ # create a new project in the current directory
13
+ npm create svelte@latest
14
+
15
+ # create a new project in my-app
16
+ npm create svelte@latest my-app
17
+ ```
18
+
19
+ ## Developing
20
+
21
+ Once you've created a project and installed dependencies with `npm install` (or `pnpm install` or `yarn`), start a development server:
22
+
23
+ ```bash
24
+ npm run dev
25
+
26
+ # or start the server and open the app in a new browser tab
27
+ npm run dev -- --open
28
+ ```
29
+
30
+ Everything inside `src/lib` is part of your library, everything inside `src/routes` can be used as a showcase or preview app.
31
+
32
+ ## Building
33
+
34
+ To build your library:
35
+
36
+ ```bash
37
+ npm run package
38
+ ```
39
+
40
+ To create a production version of your showcase app:
41
+
42
+ ```bash
43
+ npm run build
44
+ ```
45
+
46
+ You can preview the production build with `npm run preview`.
47
+
48
+ > To deploy your app, you may need to install an [adapter](https://kit.svelte.dev/docs/adapters) for your target environment.
49
+
50
+ ## Publishing
51
+
52
+ Go into the `package.json` and give your package the desired name through the `"name"` option. Also consider adding a `"license"` field and point it to a `LICENSE` file which you can create from a template (one popular option is the [MIT license](https://opensource.org/license/mit/)).
53
+
54
+ To publish your library to [npm](https://www.npmjs.com):
55
+
56
+ ```bash
57
+ npm publish
58
+ ```
@@ -0,0 +1,12 @@
1
+ import { Collection, Document } from "mongodb";
2
+ import { IdaeDbConnection } from "./IdaeDbConnection";
3
+ export declare class IdaeDBModel<T extends Document> {
4
+ private _collection;
5
+ private _autoIncrementField;
6
+ private _fieldId;
7
+ constructor(connection: IdaeDbConnection, collectionName: string, options?: {
8
+ autoIncrementFormat?: (collection: string) => string;
9
+ });
10
+ get collection(): Collection<T>;
11
+ get fieldId(): string | undefined;
12
+ }
@@ -0,0 +1,19 @@
1
+ // packages\idae-db\lib\IdaeDBModel.ts
2
+ import { Collection, Document } from "mongodb";
3
+ import { IdaeDbConnection } from "./IdaeDbConnection";
4
+ export class IdaeDBModel {
5
+ _collection;
6
+ _autoIncrementField = undefined;
7
+ _fieldId = "_id";
8
+ constructor(connection, collectionName, options) {
9
+ this._collection = connection.getDb().collection(collectionName);
10
+ this._autoIncrementField = options?.autoIncrementFormat?.(collectionName);
11
+ this._fieldId = this._autoIncrementField ?? "_id";
12
+ }
13
+ get collection() {
14
+ return this._collection;
15
+ }
16
+ get fieldId() {
17
+ return this._fieldId;
18
+ }
19
+ }
@@ -0,0 +1,16 @@
1
+ import { Db } from "mongodb";
2
+ import { Connection as MysqlConnection } from "mysql2/promise";
3
+ import { DbType } from "./types";
4
+ export declare class IdaeDbConnection {
5
+ private uri;
6
+ private dbName;
7
+ private dbType;
8
+ private mongoClient;
9
+ private mongoDb;
10
+ private mysqlConnection;
11
+ constructor(uri: string, dbName: string, dbType: DbType);
12
+ connect(): Promise<void>;
13
+ getDb(): Db | MysqlConnection;
14
+ close(): Promise<void>;
15
+ getDbType(): DbType;
16
+ }
@@ -0,0 +1,74 @@
1
+ // packages\idae-db\lib\IdaeDbConnection.ts
2
+ import { MongoClient, Db } from "mongodb";
3
+ import { Connection as MysqlConnection } from "mysql2/promise";
4
+ import { DbType } from "./types";
5
+ export class IdaeDbConnection {
6
+ uri;
7
+ dbName;
8
+ dbType;
9
+ mongoClient = null;
10
+ mongoDb = null;
11
+ mysqlConnection = null;
12
+ constructor(uri, dbName, dbType) {
13
+ this.uri = uri;
14
+ this.dbName = dbName;
15
+ this.dbType = dbType;
16
+ }
17
+ async connect() {
18
+ try {
19
+ switch (this.dbType) {
20
+ case DbType.MONGODB:
21
+ this.mongoClient = new MongoClient(this.uri);
22
+ await this.mongoClient.connect();
23
+ this.mongoDb = this.mongoClient.db(this.dbName);
24
+ console.log("Connected to MongoDB");
25
+ break;
26
+ case DbType.MYSQL:
27
+ // this.mysqlConnection = await mysql.createConnection(...);
28
+ console.log("Connected to MySQL");
29
+ break;
30
+ default:
31
+ throw new Error(`Unsupported database type: ${this.dbType}`);
32
+ }
33
+ }
34
+ catch (error) {
35
+ console.error(`Error connecting to ${this.dbType}:`, error);
36
+ throw error;
37
+ }
38
+ }
39
+ getDb() {
40
+ switch (this.dbType) {
41
+ case DbType.MONGODB:
42
+ if (!this.mongoDb) {
43
+ throw new Error("MongoDB not connected. Call connect() first.");
44
+ }
45
+ return this.mongoDb;
46
+ case DbType.MYSQL:
47
+ if (!this.mysqlConnection) {
48
+ throw new Error("MySQL not connected. Call connect() first.");
49
+ }
50
+ return this.mysqlConnection;
51
+ default:
52
+ throw new Error(`Unsupported database type: ${this.dbType}`);
53
+ }
54
+ }
55
+ async close() {
56
+ switch (this.dbType) {
57
+ case DbType.MONGODB:
58
+ if (this.mongoClient) {
59
+ await this.mongoClient.close();
60
+ console.log("Disconnected from MongoDB");
61
+ }
62
+ break;
63
+ case DbType.MYSQL:
64
+ if (this.mysqlConnection) {
65
+ await this.mysqlConnection.end();
66
+ console.log("Disconnected from MySQL");
67
+ }
68
+ break;
69
+ }
70
+ }
71
+ getDbType() {
72
+ return this.dbType;
73
+ }
74
+ }
@@ -0,0 +1,20 @@
1
+ import type { IdaeDbParams, IdaeDbAdapter } from "../types.js";
2
+ import { Document, type IndexSpecification, type CreateIndexesOptions } from "mongodb";
3
+ import { IdaeDbConnection } from "../IdaeDbConnection.js";
4
+ export declare class MongoDBAdapter<T extends Document> implements IdaeDbAdapter<T> {
5
+ private model;
6
+ private connection;
7
+ private fieldId;
8
+ constructor(collection: string, connection: IdaeDbConnection);
9
+ createIndex(fieldOrSpec: IndexSpecification, options?: CreateIndexesOptions): Promise<string>;
10
+ findById(id: string): Promise<import("mongodb").FindCursor<import("mongodb").WithId<T>>>;
11
+ find(params: IdaeDbParams<T>): Promise<import("mongodb").FindCursor<import("mongodb").WithId<T>>>;
12
+ findOne(params: IdaeDbParams<T>): Promise<import("mongodb").WithId<T> | null>;
13
+ update(id: string, updateData: Partial<T>): Promise<import("mongodb").UpdateResult<T>>;
14
+ updateWhere(params: IdaeDbParams<T>, updateData: Partial<T>): Promise<import("mongodb").UpdateResult<T>>;
15
+ deleteById(id: string): Promise<import("mongodb").DeleteResult>;
16
+ deleteWhere(params: IdaeDbParams<T>): Promise<{
17
+ deletedCount?: number;
18
+ }>;
19
+ private parseSortOptions;
20
+ }
@@ -0,0 +1,66 @@
1
+ // packages\idae-db\src\lib\adapters\MongoDBAdapter.ts
2
+ import dotenv from "dotenv";
3
+ import { Document, } from "mongodb";
4
+ import { IdaeDbConnection } from "../IdaeDbConnection.js";
5
+ import { IdaeDBModel } from "../IdaeDBModel.js";
6
+ // Load environment variables
7
+ dotenv.config();
8
+ // MongoDB Adapter
9
+ export class MongoDBAdapter {
10
+ model;
11
+ connection;
12
+ fieldId;
13
+ constructor(collection, connection) {
14
+ // just in case
15
+ collection = collection.split(".")[1] ?? collection.split(".")[0];
16
+ this.connection = connection;
17
+ this.model = this.connection.model(collection);
18
+ this.fieldId = this.model.fieldId;
19
+ }
20
+ async createIndex(fieldOrSpec, options) {
21
+ return this.model.collection.createIndex(fieldOrSpec, options);
22
+ }
23
+ async findById(id) {
24
+ return this.model.collection.find({ [this.fieldId]: id }, { hint: this.fieldId });
25
+ }
26
+ async find(params) {
27
+ const { query = {}, sortBy, limit, skip } = params;
28
+ const sortOptions = this.parseSortOptions(sortBy);
29
+ return await this.model.collection
30
+ .find(query)
31
+ .sort(sortOptions)
32
+ .limit(Number(limit) || 0)
33
+ .skip(Number(skip) || 0);
34
+ }
35
+ findOne(params) {
36
+ return this.model.collection.findOne(params.query);
37
+ }
38
+ async update(id, updateData) {
39
+ return this.model.collection.updateMany({ [this.fieldId]: id }, updateData, {
40
+ upsert: true,
41
+ });
42
+ }
43
+ async updateWhere(params, updateData) {
44
+ return this.model.collection.updateMany(params.query, updateData, {
45
+ upsert: true,
46
+ });
47
+ }
48
+ async deleteById(id) {
49
+ return this.model.collection.deleteMany({ _id: { $eq: id } });
50
+ }
51
+ async deleteWhere(params) {
52
+ const result = await this.model.collection.deleteMany(params.query);
53
+ return { deletedCount: result.deletedCount };
54
+ }
55
+ parseSortOptions(sortBy) {
56
+ const sortOptions = {};
57
+ if (sortBy) {
58
+ const sortFields = sortBy.split(",");
59
+ sortFields.forEach((field) => {
60
+ const [key, order] = field.split(":");
61
+ sortOptions[key] = order === "desc" ? -1 : 1;
62
+ });
63
+ }
64
+ return sortOptions;
65
+ }
66
+ }
@@ -0,0 +1,23 @@
1
+ import type { ApiServerRequestParams } from "../server/engine/types";
2
+ import { Model } from "sequelize";
3
+ import type { DatabaseAdapter } from "../types";
4
+ interface MySQLDocument extends Model {
5
+ id: number;
6
+ [key: string]: any;
7
+ }
8
+ export declare class MySQLAdapter<T extends MySQLDocument> implements DatabaseAdapter<T> {
9
+ private sequelize;
10
+ private model;
11
+ constructor(tableName: string);
12
+ create(document: Partial<T>): Promise<T>;
13
+ where(params: ApiServerRequestParams): Promise<T[]>;
14
+ findById(id: string): Promise<T | null>;
15
+ findOne(params: ApiServerRequestParams): Promise<T | null>;
16
+ update(id: string, updateData: Partial<T>): Promise<T | null>;
17
+ deleteById(id: string): Promise<T | null>;
18
+ deleteManyByQuery(params: ApiServerRequestParams): Promise<{
19
+ deletedCount?: number;
20
+ }>;
21
+ private parseSortOptions;
22
+ }
23
+ export {};
@@ -0,0 +1,80 @@
1
+ import { Sequelize, Model, DataTypes } from "sequelize";
2
+ import dotenv from "dotenv";
3
+ dotenv.config();
4
+ export class MySQLAdapter {
5
+ sequelize;
6
+ model;
7
+ constructor(tableName) {
8
+ this.sequelize = new Sequelize({
9
+ dialect: "mysql",
10
+ host: process.env.MYSQL_HOST || "localhost",
11
+ port: Number(process.env.MYSQL_PORT) || 3306,
12
+ database: process.env.MYSQL_DATABASE || "database",
13
+ username: process.env.MYSQL_USER || "root",
14
+ password: process.env.MYSQL_PASSWORD || "password",
15
+ });
16
+ this.model = this.sequelize.define(tableName, {
17
+ id: {
18
+ type: DataTypes.INTEGER.UNSIGNED,
19
+ autoIncrement: true,
20
+ primaryKey: true,
21
+ },
22
+ // Define other fields here as needed
23
+ }, {
24
+ timestamps: false,
25
+ tableName,
26
+ });
27
+ }
28
+ async create(document) {
29
+ const newDocument = await this.model.create(document);
30
+ return newDocument;
31
+ }
32
+ async where(params) {
33
+ const { query = {}, sortBy, limit, skip } = params;
34
+ const options = {
35
+ where: query,
36
+ order: this.parseSortOptions(sortBy),
37
+ limit: limit ? Number(limit) : undefined,
38
+ offset: skip ? Number(skip) : undefined,
39
+ };
40
+ const results = await this.model.findAll(options);
41
+ return results;
42
+ }
43
+ async findById(id) {
44
+ const result = await this.model.findByPk(id);
45
+ return result ? result : null;
46
+ }
47
+ async findOne(params) {
48
+ const { query = {} } = params;
49
+ const result = await this.model.findOne({ where: query });
50
+ return result ? result : null;
51
+ }
52
+ async update(id, updateData) {
53
+ const [affectedCount, affectedRows] = await this.model.update(updateData, {
54
+ where: { id },
55
+ returning: true,
56
+ });
57
+ return affectedCount > 0 ? affectedRows[0] : null;
58
+ }
59
+ async deleteById(id) {
60
+ const result = await this.model.findByPk(id);
61
+ if (result) {
62
+ await result.destroy();
63
+ return result;
64
+ }
65
+ return null;
66
+ }
67
+ async deleteManyByQuery(params) {
68
+ const { query = {} } = params;
69
+ const deletedCount = await this.model.destroy({ where: query });
70
+ return { deletedCount };
71
+ }
72
+ parseSortOptions(sortBy) {
73
+ if (!sortBy)
74
+ return [];
75
+ return sortBy.split(",").map((field) => {
76
+ const [key, order] = field.split(":");
77
+ return [key, order === "desc" ? "DESC" : "ASC"];
78
+ });
79
+ }
80
+ }
@@ -0,0 +1,17 @@
1
+ import { DbType } from "./types.js";
2
+ import { IdaeDbConnection } from "./IdaeDbConnection";
3
+ import { MongoDBAdapter } from "./adapters/MongoDBAdapter";
4
+ import { MySQLAdapter } from "./adapters/MysqlAdapter";
5
+ import type { Document } from "mongodb";
6
+ export declare class IdaeDb {
7
+ private static instances;
8
+ private connections;
9
+ private dbType;
10
+ private constructor();
11
+ static getOrCreateInstance(dbType: DbType): IdaeDb;
12
+ createConnection(connectionName: string, uri: string, dbName: string): Promise<IdaeDbConnection>;
13
+ getConnection(connectionName: string): IdaeDbConnection;
14
+ getAdapter<T extends Document>(connectionName: string, collectionName: string): MongoDBAdapter<T> | MySQLAdapter<T>;
15
+ closeConnection(connectionName: string): Promise<void>;
16
+ closeAllConnections(): Promise<void>;
17
+ }
package/dist/idaDb.js ADDED
@@ -0,0 +1,59 @@
1
+ // packages\idae-db\lib\idaDb.ts
2
+ import { DbType } from "./types.js";
3
+ import { IdaeDbConnection } from "./IdaeDbConnection";
4
+ import { MongoDBAdapter } from "./adapters/MongoDBAdapter";
5
+ import { MySQLAdapter } from "./adapters/MysqlAdapter";
6
+ export class IdaeDb {
7
+ static instances = new Map();
8
+ connections = new Map();
9
+ dbType;
10
+ constructor(dbType) {
11
+ this.dbType = dbType;
12
+ }
13
+ static getOrCreateInstance(dbType) {
14
+ if (!IdaeDb.instances.has(dbType)) {
15
+ IdaeDb.instances.set(dbType, new IdaeDb(dbType));
16
+ }
17
+ return IdaeDb.instances.get(dbType);
18
+ }
19
+ async createConnection(connectionName, uri, dbName) {
20
+ if (this.connections.has(connectionName)) {
21
+ throw new Error(`Connection '${connectionName}' already exists.`);
22
+ }
23
+ const connection = new IdaeDbConnection(uri, dbName, this.dbType);
24
+ await connection.connect();
25
+ this.connections.set(connectionName, connection);
26
+ return connection;
27
+ }
28
+ getConnection(connectionName) {
29
+ const connection = this.connections.get(connectionName);
30
+ if (!connection) {
31
+ throw new Error(`Connection '${connectionName}' not found.`);
32
+ }
33
+ return connection;
34
+ }
35
+ getAdapter(connectionName, collectionName) {
36
+ const connection = this.getConnection(connectionName);
37
+ switch (this.dbType) {
38
+ case DbType.MONGODB:
39
+ return new MongoDBAdapter(collectionName, connection);
40
+ case DbType.MYSQL:
41
+ return new MySQLAdapter(collectionName, connection);
42
+ default:
43
+ throw new Error(`Unsupported database type: ${this.dbType}`);
44
+ }
45
+ }
46
+ async closeConnection(connectionName) {
47
+ const connection = this.connections.get(connectionName);
48
+ if (connection) {
49
+ await connection.close();
50
+ this.connections.delete(connectionName);
51
+ }
52
+ }
53
+ async closeAllConnections() {
54
+ for (const [connectionName, connection] of this.connections) {
55
+ await connection.close();
56
+ }
57
+ this.connections.clear();
58
+ }
59
+ }
@@ -0,0 +1,6 @@
1
+ export * from './types.js';
2
+ export * from './idaDb.js';
3
+ export * from './IdaeDbConnection.js';
4
+ export * from './IdaeDBModel.js';
5
+ export * from './adapters/MySQLAdapter.js';
6
+ export * from './adapters/MongoDBAdapter.js';
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ // auto exports of entry components
2
+ export * from './types.js';
3
+ export * from './idaDb.js';
4
+ export * from './IdaeDbConnection.js';
5
+ export * from './IdaeDBModel.js';
6
+ export * from './adapters/MySQLAdapter.js';
7
+ export * from './adapters/MongoDBAdapter.js';
@@ -0,0 +1,27 @@
1
+ import { Document, type UpdateResult, type Filter, type WithId, type FindCursor, type IndexSpecification, type CreateIndexesOptions, type DeleteResult } from "mongodb";
2
+ export interface IdaeDbAdapter<T extends Document> {
3
+ createIndex(fieldOrSpec: IndexSpecification, options?: CreateIndexesOptions): Promise<string>;
4
+ findById(id: string): Promise<FindCursor<WithId<T>>>;
5
+ find(params: IdaeDbParams<T>): Promise<FindCursor<WithId<T>>>;
6
+ findOne(params: IdaeDbParams<T>): Promise<WithId<T> | null>;
7
+ update(id: string, updateData: Partial<T>): Promise<UpdateResult<T>>;
8
+ updateWhere(params: IdaeDbParams<T>, updateData: Partial<T>): Promise<UpdateResult<T>>;
9
+ deleteById(id: string): Promise<DeleteResult>;
10
+ deleteWhere(params: IdaeDbParams<T>): Promise<{
11
+ deletedCount?: number;
12
+ }>;
13
+ }
14
+ export interface IdaeDbParams<T extends object> {
15
+ id?: string;
16
+ query: Filter<T>;
17
+ sortBy?: string;
18
+ limit?: number;
19
+ skip?: number;
20
+ }
21
+ export interface IdaeDbParamsSortOptions {
22
+ [key: string]: 1 | -1;
23
+ }
24
+ export declare enum DbType {
25
+ MONGODB = "mongodb",
26
+ MYSQL = "mysql"
27
+ }
package/dist/types.js ADDED
@@ -0,0 +1,7 @@
1
+ // packages\idae-db\src\lib\adapters\types.ts
2
+ import { Document, } from "mongodb";
3
+ export var DbType;
4
+ (function (DbType) {
5
+ DbType["MONGODB"] = "mongodb";
6
+ DbType["MYSQL"] = "mysql";
7
+ })(DbType || (DbType = {}));
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "@medyll/idae-db",
3
+ "version": "0.0.1",
4
+ "scripts": {
5
+ "dev": "vite dev",
6
+ "build": "vite build && npm run package",
7
+ "preview": "vite preview",
8
+ "package": "svelte-kit sync && svelte-package && publint",
9
+ "prepublishOnly": "npm run package",
10
+ "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
11
+ "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
12
+ "test": "vitest",
13
+ "lint": "prettier --check . && eslint .",
14
+ "format": "prettier --write .",
15
+ "package:pre": "node scripts/package-pre.js"
16
+ },
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "svelte": "./dist/index.js",
21
+ "import": "./dist/index.js"
22
+ }
23
+ },
24
+ "files": [
25
+ "dist",
26
+ "!dist/**/*.test.*",
27
+ "!dist/**/*.spec.*"
28
+ ],
29
+ "peerDependencies": {
30
+ "svelte": "^5.0.0-next"
31
+ },
32
+ "devDependencies": {
33
+ "@sveltejs/adapter-auto": "^3.2.4",
34
+ "@sveltejs/kit": "^2.5.24",
35
+ "@sveltejs/package": "^2.3.4",
36
+ "@sveltejs/vite-plugin-svelte": "^3.1.1",
37
+ "@types/eslint": "^9.6.0",
38
+ "eslint": "^9.9.0",
39
+ "eslint-config-prettier": "^9.1.0",
40
+ "eslint-plugin-svelte": "^2.43.0",
41
+ "globals": "^15.9.0",
42
+ "prettier": "^3.3.3",
43
+ "prettier-plugin-svelte": "^3.2.6",
44
+ "publint": "^0.2.10",
45
+ "svelte": "^5.0.0-next.225",
46
+ "svelte-check": "^3.8.5",
47
+ "typescript": "^5.5.4",
48
+ "typescript-eslint": "^8.1.0",
49
+ "vite": "^5.4.1",
50
+ "vitest": "^2.0.5"
51
+ },
52
+ "svelte": "./dist/index.js",
53
+ "types": "./dist/index.d.ts",
54
+ "type": "module",
55
+ "scope": "@medyll"
56
+ }