-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
95 lines (77 loc) · 2.07 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
const fetch = require('node-fetch')
const dotenv = require('dotenv')
const config = dotenv.load('./env').parsed
class Fontsy {
constructor() {
this.url = 'https://www.googleapis.com/webfonts/v1/webfonts'
this.key = config['API_KEY']
this.sorted = 'popularity'
this.fonts = []
}
endpoint() {
return `${this.url}?sort=${this.sorted}&key=${this.key}`
}
sort(sort) {
this.sorted = sort
return this
}
async font(query) {
if (query) {
this.fonts = Object.keys(query)
this.variant = this.fonts.map(item => {
return query[item].map(item => {
return item.toLowerCase().replace(/ /g, '').replace(/italic/g, 'i')
}).join(',')
})
}
this.result = await this.fetch()
return this
}
fetch() {
return new Promise(resolve => {
fetch(this.endpoint())
.then(res => res.json())
.then(res => {
resolve(res['items'].filter(item => {
if (this.fonts.length > 0) {
return this.fonts.indexOf(item['family']) > -1
}
return item
}))
})
})
}
link(tag) {
let apiUrl = []
let fontVariant = []
apiUrl.push('https://fonts.googleapis.com/css?family=')
this.fonts.map((item, index) => {
fontVariant.push(`${item.replace(/ /g, '+')}:${this.variant[index]}`)
})
apiUrl.push(fontVariant.join('|'))
if (tag) {
return `<link href="${apiUrl.join('').trim()}" rel="stylesheet">`
} else {
return apiUrl.join('').trim()
}
}
css() {
return this.result.map(item => {
return `
.font-${item['family'].replace(/ /g, '-').toLowerCase()} {
font-family: '${item['family']}', ${item['category']};
}
`.trim().replace(/ /g, '')
}).join('\n')
}
list() {
return this.result.map(item => {
const bracket = {}
bracket['family'] = item['family']
bracket['category'] = item['category']
bracket['variants'] = item['variants']
return bracket
})
}
}
module.exports = Fontsy