-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
295 lines (264 loc) · 8.84 KB
/
index.js
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
import { nanoid } from "nanoid";
/**
@description
Simple ORM for working with DB on Cloudflare
db - an intances of DB in Cloudflare
tables - your tables in format key: value ie:
*/
export class SimpleORM {
constructor(db, tables) {
// Cloudflare context
this.db = db
this.tables = tables
}
prepare(s) {
return this.db.prepare(s)
}
async getByID(tableName, id, options) {
const results = await this.findAll(tableName, {
...options,
where: [
['id', '=', id]
]
})
if (results && results.length === 1) {
return results[0]
}
return null
}
async create(tableName, entity) {
if (!tableName) {
throw new Error('Please provide name of table')
}
if (!entity.id) {
entity.id = nanoid();
}
entity = stringifyNestedObject(entity)
const columns = Object.entries(entity)
.reduce((acc, curr) => {
return [...acc, curr[0]];
}, [])
.join(", ");
const values = Object.entries(entity).reduce((acc, curr) => {
return [...acc, curr[1]];
}, []);
console.log("values:", values);
const questionMarks = Array(Object.entries(entity).length).fill("?").join(", ");
const finalQuery = `INSERT INTO ${tableName} (${columns}) VALUES (${questionMarks})`;
console.log("finalQuery: ", finalQuery);
await this.db.prepare(finalQuery)
.bind(...values)
.run();
return entity
}
async update(tableName, id, entity) {
if (!tableName) {
throw new Error('Please provide name of table')
}
entity.updatedAt = new Date().getTime()
entity = stringifyNestedObject(entity)
const columns = Object.entries(entity).reduce((acc, curr) => {
return [...acc, `${[curr[0]]}=?`]
}, []).join(', ')
const values = Object.entries(entity).reduce((acc, curr) => {
return [...acc, curr[1]];
}, []);
const finalQuery = `UPDATE ${tableName} SET ${columns} WHERE id='${id}'`;
console.log("finalQuery: ", finalQuery);
await this.db.prepare(finalQuery)
.bind(...values)
.run();
return entity
}
async delete(tableName, id) {
return await this.db.prepare(`DELETE FROM ${tableName} WHERE id=?`)
.bind(id)
.run()
}
async drop(tableName) {
const dropped = await this.db.prepare(`DROP TABLE IF EXISTS ${tableName}`).run()
if (dropped?.success) {
return tableName
}
throw new Error(`Something wrong while dropping table ${table}`)
}
async deleteAll(tableName) {
return await this.db.prepare(`DELETE FROM ${tableName}`)
.run()
}
async count(tableName, orgID) {
const { totals } = await this.db.prepare(`SELECT COUNT(*) as totals FROM ${tableName} WHERE orgID=?`).bind(orgID).first()
return totals
}
async findAll(tableName, options = {}) {
console.log("tableName:", { tableName, options: JSON.stringify(options) });
const columns = this.tables[tableName]
let attributes = []
let whereQuery = ""
let orderBy = ""
let limit = ""
let joins = []
if (options) {
if (options.attributes && options.attributes.length > 0) {
attributes.push(options.attributes.map(c => `${tableName}.${c}`).join(', '))
} else {
// Select all table's columns
attributes.push(Object.keys(columns).map(c => `${tableName}.${c}`).join(', '))
}
if (options.include) {
options.include.forEach(include => {
const joinTable = include[0]
const column1 = include[1]
const column2 = include[2]
const joinQuery = `LEFT JOIN ${joinTable} as ${joinTable} ON ${column1}=${column2}`
joins.push(joinQuery)
const joinTableColumns = this.tables[joinTable]
const joinAttributes = Object.keys(joinTableColumns).map(c => `${joinTable}.${c} AS "${joinTable}.${c}"`).join(', ')
attributes.push(joinAttributes)
});
}
if (options.where && options.where.length > 0) {
let where = []
options.where.forEach(w => {
if (w.length === 2) {
// Advanced mode
// Logical combinations. The Op.and, Op.or, and Op.not operators can be used to combine multiple conditions.
// let combinationType = w[0]
// TODO: Figure out how to deal with other logication combination opearions
} else {
// Simple mode
let result = this.buildWhereQuery(tableName, w)
where.push(result)
}
});
where = where.join(' AND ')
whereQuery = `WHERE ${where}`
}
if (options.orderBy) {
orderBy = Object.entries(options.orderBy).reduce((acc, [column, direction]) => `ORDER BY ${tableName}.${column} ${direction}`, ``)
}
if (options.limit > 0) {
limit = `LIMIT ${options.limit}`
}
}
attributes = attributes.join(', ')
joins = joins.join('\n')
const query = String(`SELECT ${attributes} FROM ${tableName}
${joins}
${whereQuery}
${orderBy}
${limit}`).replace(/\s+/g, ' ').trim();
console.log("query:", query);
let { results } = await this.db.prepare(query).all();
return convertToNestedJSON(results)
}
/**
* Converts to where clause
*
* 1) ['orgID', '=', 'demo'] => "tableName.orgID='demo'"
* 2) ['orgID', 'LIKE', 'demo'] => "tableName.orgID LIKE '%demo%'"
* Also search in JSON
* 3) ['users.IDCard.iin', 'LIKE', '91'] => json_extract(users.IDCard, '$.iin') LIKE '%91%'
*/
buildWhereQuery(tableName, w) {
let column = w[0]
let operaion = w[1]
let value = w[2]
if (String(column).split('.').length === 3) {
// Searchin in JSON
const [t, jColumn, c] = String(column).split('.')
console.log("column:", [t, jColumn, c]);
const columns = this.tables[t]
const jsonColumn = columns[jColumn]
if (jsonColumn === "json") {
column = `json_extract(${t}.${jColumn}, '$.${c}')`
}
} else if (String(column).split('.').length === 1) {
column = `${tableName}.${column}`
}
if (operaion === "LIKE") {
operaion = " LIKE "
value = `%${value}%`
}
let whereQuery = `${column}${operaion}${value}`
if (typeof value === "string") {
whereQuery = `${column}${operaion}"${value}"`
}
return whereQuery
}
}
/**
* Converts plain object into nested Object: IE:
data.phone: "87014073428"
data.language: "English"
email:"[email protected]"
name: "Serik Shaikamalov"
to =>
data {
phone: "87014073428",
language: "English"
},
email: "[email protected]",
name: "Serik Shaikamalov"
*/
export const convertToNestedJSON = (input) => {
if (!input)
throw new Error('Please provide input data')
if (Array.isArray(input)) {
return input.map(i => convertToNestedJSON(i))
}
if (typeof input !== "object")
throw new Error('Input is not object')
return Object.entries(input).reduce((acc, [key, value]) => {
if (!value) return acc
if (key.includes('.')) {
let properties = key.split('.')
return Object.assign(acc, {
[properties[0]]: acc[properties[0]] ?
Object.assign({}, acc[properties[0]], { [properties[1]]: doParse(value) }) :
Object.assign({}, { [properties[1]]: value })
})
}
acc[key] = doParse(value)
return acc
}, {})
}
export function doParse(v) {
try {
return v = JSON.parse(v)
} catch (ex) {
return v
}
}
/**
* Converts:
*
* {
* name: 'Serik',
* age: 30,
* education: {
* id: 1
* }
* }
*
* ==>
*
* {
* name: "Serik",
* age: 30,
* education: "{id: 1}"
*
* }
*
*/
export const stringifyNestedObject = (obj) => {
return Object.entries(obj).reduce((acc, [k, v]) => {
if (typeof v === "object") {
v = JSON.stringify(v)
}
return {
...acc,
[k]: v
}
}, {})
}