-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.mts
More file actions
89 lines (74 loc) · 2.41 KB
/
index.mts
File metadata and controls
89 lines (74 loc) · 2.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import { MongoClient, MongoServerError } from "mongodb";
import { mappings } from "./config/mapping.mjs";
import { parseQuery } from "./utils/parser.mjs";
import { connect } from "./utils/database.mjs";
import { SqlToNoSqlType } from "./types/index.mjs";
export class SqlToNoSql {
client: MongoClient | undefined;
constructor(private config: SqlToNoSqlType) {}
async run(query: string) {
if (!query) {
throw new Error("missing query!");
}
// // TODO: add better validation!
// if ([";", "(", ")"].some((char) => query.includes(char))) {
// throw new Error("Invalid query, your query contains invalid characters!");
// }
const q = parseQuery(query);
if (q.command === "select"){
const filters: {
[key: string]: {
[operator: string]: string | number;
};
} = {};
// Convert parsed filters to MongoDB query
q.filters?.forEach((filter) => {
const { column, operator, value } = filter;
if (!filters[column]) {
filters[column] = {
[mappings["mongodb"]["operators"][operator]]: value,
};
}
});
const mongoQuery = {
collection: q.table,
[q.command]: mappings["mongodb"]["commands"][q.command],
query: filters,
};
try {
if (!this.client) {
this.client = await connect(this.config.connection);
await this.client.connect();
}
const db = this.client.db();
const collection = db.collection(mongoQuery.collection);
const data = await collection[mongoQuery[q.command]](
mongoQuery.query,
).toArray();
return data;
} catch (err) {
console.error(err);
throw Error("Something went wrong!");
}
} else if (q.command === "create") {
try {
if (!this.client) {
this.client = await connect(this.config.connection);
await this.client.connect();
}
const db = this.client.db();
const result = await db.createCollection(q.table);
console.log("Mongo result", result);
return result;
} catch (err) {
if (err instanceof MongoServerError) {
if (err.codeName === 'NamespaceExists'){
console.error("Collection already exists: " + q.table)
}
} else {
throw Error("Something went wrong!");
}
}
}
}
}