|
1 | 1 | import { mappings } from "./config/mapping.js"; |
2 | 2 | import { parseQuery } from "./utils/parser.js"; |
| 3 | +import { connect } from "./utils/database.js"; |
| 4 | +import { SqlToNoSqlType } from "./types/index.js"; |
3 | 5 |
|
4 | | -export const SqlToNoSql = (query: string) => { |
5 | | - if (!query) { |
6 | | - throw new Error("missing query!"); |
| 6 | +export class SqlToNoSql { |
| 7 | + constructor(private config: SqlToNoSqlType) { |
| 8 | + connect(this.config.connection); |
7 | 9 | } |
8 | 10 |
|
9 | | - if ([";", "(", ")"].some((char) => query.includes(char))) { |
10 | | - throw new Error("Invalid query, your query contains invalid characters!"); |
11 | | - } |
12 | | - |
13 | | - const q = parseQuery(query); |
| 11 | + run(query: string) { |
| 12 | + if (!query) { |
| 13 | + throw new Error("missing query!"); |
| 14 | + } |
14 | 15 |
|
15 | | - const filters: { |
16 | | - [key: string]: { |
17 | | - [operator: string]: string | number; |
18 | | - }; |
19 | | - } = {}; |
| 16 | + // TODO: add better validation! |
| 17 | + if ([";", "(", ")"].some((char) => query.includes(char))) { |
| 18 | + throw new Error("Invalid query, your query contains invalid characters!"); |
| 19 | + } |
20 | 20 |
|
21 | | - q.filters?.forEach((filter) => { |
22 | | - const { column, operator, value } = filter; |
| 21 | + const q = parseQuery(query); |
23 | 22 |
|
24 | | - if (!filters[column]) { |
25 | | - filters[column] = { |
26 | | - [mappings["mongodb"]["operators"][operator]]: value, |
| 23 | + const filters: { |
| 24 | + [key: string]: { |
| 25 | + [operator: string]: string | number; |
27 | 26 | }; |
28 | | - } |
29 | | - }); |
| 27 | + } = {}; |
| 28 | + |
| 29 | + // Convert parsed filters to MongoDB query |
| 30 | + q.filters?.forEach((filter) => { |
| 31 | + const { column, operator, value } = filter; |
| 32 | + |
| 33 | + if (!filters[column]) { |
| 34 | + filters[column] = { |
| 35 | + [mappings["mongodb"]["operators"][operator]]: value, |
| 36 | + }; |
| 37 | + } |
| 38 | + }); |
| 39 | + |
| 40 | + const mongoQuery = { |
| 41 | + collection: q.table, |
| 42 | + [q.command]: mappings["mongodb"]["commands"][q.command], |
| 43 | + query: filters, |
| 44 | + }; |
30 | 45 |
|
31 | | - const mongoQuery = { |
32 | | - collection: q.table, |
33 | | - [q.command]: mappings["mongodb"]["commands"][q.command], |
34 | | - query: filters, |
35 | | - }; |
| 46 | + return mongoQuery; |
| 47 | + } |
| 48 | +} |
36 | 49 |
|
37 | | - return mongoQuery; |
38 | | -}; |
| 50 | +const runner = new SqlToNoSql({ |
| 51 | + srcDBtype: "postgresql", |
| 52 | + destDBtype: "mongodb", |
| 53 | + connection: "mongodb://localhost:27017", |
| 54 | +}); |
39 | 55 |
|
40 | | -console.log(SqlToNoSql("SELECT * FROM users")); |
41 | | -console.log(SqlToNoSql("select * from users where id = 1")); |
| 56 | +console.log(runner.run("SELECT * FROM users")); |
| 57 | +console.log(runner.run("select * from users where id = 1")); |
0 commit comments