-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
49 lines (37 loc) · 1.02 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
"use strict"
module.exports = function generate(data) {
return traverse([], data)
}
function getMode(val) {
if(Array.isArray(val)) return "REPEATED"
else return "NULLABLE"
}
function getType(val) {
if(typeof val === 'boolean') return "BOOLEAN"
if(!isNaN(val)){
if(Number.isInteger(parseFloat(val))) return "INTEGER"
return "FLOAT"
}
if(val instanceof Date) return "TIMESTAMP"
if(Array.isArray(val)) return getType(val[0])
if(typeof val === 'object') return "RECORD"
if(typeof val === 'string') {
if(val.match(/\d{4}-\d{2}-\d{2}/)) return "DATE"
if(val.length > 18 && !isNaN((new Date(val)).getTime())) return "TIMESTAMP"
}
return "STRING"
}
function traverse(arr, data) {
return Object.keys(data).map((key) => {
let val = data[key]
let meta = {
name: key,
type: getType(data[key]),
mode: getMode(data[key])
}
if(meta.type === 'RECORD') {
meta.fields = traverse([], (meta.mode === 'REPEATED') ? val[0] : val)
}
return meta
})
}