-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
269 lines (221 loc) · 7.53 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
const os = require('os')
const readline = require('readline')
const mysql = require('mysql')
const pMap = require('p-map')
const file = require('./file.js')
let cpus = os.cpus().length
cpus = cpus > 2 ? cpus : 2
let ISDEV = process.env.NODE_ENV === 'development'
/* Capitalize string */
function capitalize(str) {
str = str.trim()
return str.trim().charAt(0).toUpperCase() + str.slice(1)
}
class MySQLSource {
static defaultOptions () {
return {
debug: false,
ignoreImages: false,
imageDirectory: 'sql_images',
regex: false,
queries: [],
connection: {
host: 'localhost',
port: 3306,
user: 'root',
password: 'secret',
database: 'my_db',
connectionLimit : 10
}
}
}
constructor (api, options = MySQLSource.defaultOptions()) {
const opts = {
...MySQLSource.defaultOptions(),
...options
}
this.pool = mysql.createPool({
...opts.connection
});
ISDEV = opts.debug
this.cTypes = {}
this.paths = {}
this.queries = opts.queries || []
if (!this.queries.length) throw new Error('No queries to load')
this.loadImages = false
this.regex = opts.regex
this.images = opts.ignoreImages ? false : {}
this.imageDirectory = opts.imageDirectory
api.loadSource(async (store) => {
this.store = store
this.checkQNames(this.queries)
await this.fetchQueries(this.queries)
this.pool.end(function(err) {
ISDEV && console.log('MySQL Connections Closed')
})
if (this.images && this.loadImages) await this.downloadImages()
})
}
checkQNames(queries) {
Array.isArray(queries) && queries.forEach((Q) => {
Q.name = capitalize(Q.name)
if (this.cTypes[Q.name]) console.warn(`You should not have two queries with the same name. ${Q.name}`)
else this.cTypes[Q.name] = true
if (Q.subs) this.checkQNames(Q.subs)
})
}
async fetchQueries(queries, parentQuery, parentRow) {
const { slugify, addContentType, makeUid, createReference } = this.store
await Promise.all(queries.map(async (Q) => {
const args = (typeof Q.args === 'function' ? Q.args(parentRow) : Q.args) || null
const sql = mysql.format(Q.sql, args)
const cType = this.cTypes[Q.name] = addContentType({
typeName: Q.name,
route: Q.route
})
const rels = []
const rows = await new Promise((resolve, reject) => {
this.pool.query(sql, (error, results, fields) => {
if (error) throw new Error(error)
/* Find relationship fields */
let hasIdField = false
for (const f in fields) {
const field = fields[f].name
hasIdField = field === 'id' || hasIdField
const matches = field.match(/^(.+)_(ids?$)/)
if (matches && matches.length > 2) {
const qname = matches[1]
const qtype = capitalize(qname)
if (this.cTypes[qtype]) {
rels.push({
type: qtype,
name: qname,
field,
isArray: matches[2] === 'ids'
})
} else {
console.warn(`No query with name "${qname}" exists. Not creating relation`)
}
}
}
if (!hasIdField) throw new Error('Rows must have id field')
resolve(results)
})
})
if (!Array.isArray(rows)) rows = []
console.log(`${Q.name}: retrieved ${rows.length} results`)
let PathFn = Q.path
if (typeof PathFn !== 'function') {
/* Default path function */
PathFn = (slugify, row, parent) => {
let slug = `/${Q.name}/${row.id}`
if (typeof Q.path === 'object') {
slug = Q.path.prefix || ''
slug += `/${row[Q.path.field] ? slugify(row[Q.path.field]) : row.id}`
slug += Q.path.suffix || ''
} else if (typeof Q.path === 'string' && row[Q.path]) {
slug = slugify(row[Q.path]) || slug
}
return slug
}
}
return Promise.all(rows.map(async (row, i) => {
row.mysqlId = row.id
row.id = makeUid(`${Q.name}–${row.id}`)
row.path = PathFn(slugify, row, parentRow)
if (this.paths[row.path]) {
row.path = `${row.path}-${this.paths[row.path]++}`
} else this.paths[row.path] = 1
if (parentQuery && parentRow)
row._parent = createReference(parentQuery.name, parentRow.id)
/* Parse JSON fields */
if (Array.isArray(Q.json)) {
Q.json.forEach(jsonField => {
try {
row[jsonField] = JSON.parse(row[jsonField])
} catch (e) {
row[jsonField] = null
}
})
}
/* Check for images */
if (this.images && Array.isArray(Q.images)) {
await pMap(Q.images, async imgField => {
if (typeof imgField === 'function') {
await imgField(row, (url) => this.addImage(url))
}
if (Array.isArray(imgField)) {
if (imgField.length !== 1) throw new Error('MySQL query image array should contain exactly 1 field')
row[imgField[0]] = String(row[imgField[0]]).split(',').map((url, i) => ({
index: i,
image: this.addImage(url)
})).filter(image => !!image)
} else {
row[imgField] = this.addImage(row[imgField])
}
})
}
/* Check for relationships */
rels.forEach(rel => {
if (rel.isArray) {
const ids = String(row[rel.field]).split(',')
row[rel.name] = ids.map(id => createReference(rel.type,
makeUid(`${rel.type}–${id}`)))
} else {
row[rel.name] = createReference(rel.type, makeUid(`${rel.type}–${row[rel.field]}`))
}
})
cType.addNode(row)
/* Check sub queries to execute with parent */
if (Array.isArray(Q.subs)) return this.fetchQueries(Q.subs, Q, row)
return row
}))
}))
}
addImage(url) {
if (url && String(url).match(/^https:\/\/.*\/.*\.(jpg|png|svg|jpeg)($|\?)/i)) {
const filename = file.getFilename(url, this.regex)
const id = this.store.makeUid(filename)
const filepath = file.getFullPath(this.imageDirectory, filename)
if (!this.images[id]) this.images[id] = {
filename,
url,
filepath
}
this.loadImages = true
return filepath
}
return null
}
async downloadImages() {
file.createDirectory(this.imageDirectory)
let exists = 0
const download = []
Object.keys(this.images).forEach(async (id) => {
const { filename, filepath } = this.images[id]
if (!file.exists(filepath)) {
download.push(this.images[id])
} else exists++
})
const total = download.length
let progress = 0
function status(msg) {
readline.clearLine(process.stdout, 0)
readline.cursorTo(process.stdout, 0, null)
process.stdout.write(msg)
}
console.log(`${exists} images already exists with ${total} images to download`)
if (total) {
await pMap(download, async ({ filename, url, filepath }) => {
await file.download(url, filepath)
status(`${Math.round((++progress)*100/total)}% – Downloaded ${filename}`)
}, {
concurrency: cpus * 2
})
status('100% – ')
console.log(`${total} images downloaded`)
}
this.loadImages = false
}
}
module.exports = MySQLSource