forked from findmentor-network/find-mentor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate.js
86 lines (78 loc) · 2.61 KB
/
generate.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
const fs = require('fs')
const got = require('got')
const spreadsheetId = '1x_W7Z2o_TGmEjL5cLTFbjO1R3KzQOqIhQKu9RQ4a_P4'
const apiKey = 'AIzaSyA5el9Fo8rMSYkcMjUqLfJi4tDB5_n0bzY'
const slugify = require('slugify')
const slugger = text =>
slugify(text, {
replacement: '-',
lower: true,
locale: 'tr'
})
const mapper = (posts) => {
const keys = posts.slice(0, 1)[0]
return posts.slice(1).map((row) => {
const rowData = {}
keys.map((key, index) => {
key = key.toLowerCase().replace(/\W/g, '_')
rowData[key] = row[index]
})
return rowData
})
}
const generateAvatar = ({ name, github }) => {
let avatar
if (github) {
const githubUsername = github.split('/')[3];
avatar = `https://avatars.githubusercontent.com/${githubUsername}`
} else {
avatar = `https://ui-avatars.com/api/?name=${name}`
}
return avatar
}
const fixProtocol = (url) => {
return url ? 'https://' + url.replace(/https?:\/\//gi, '').replace(/\/$/gi, '') : ''
}
const clearData = (posts) => {
return posts.map((post) => {
post.slug = slugger(post.name)
post.github = fixProtocol(post.github)
post.twitter_handle = fixProtocol(post.twitter_handle)
post.linkedin = fixProtocol(post.linkedin)
post.avatar = generateAvatar(post)
return post
})
}
async function getData () {
try {
const url = `https://sheets.googleapis.com/v4/spreadsheets/${spreadsheetId}/values:batchGet?key=${apiKey}&fields=valueRanges(range,values)&ranges=Mentees`
let response = await got(url)
response = JSON.parse(response.body)
let [persons] = response.valueRanges
persons = mapper(persons.values.slice(4).filter(r => r.length))
const mentors = persons.filter((person) => {
if (person.mentor === 'Mentor' || person.mentor === 'İkisi de') {
return person
}
})
const mentees = persons.filter((person) => {
if (person.mentor === 'Mentee' || person.mentor === 'İkisi de') {
return person
}
})
const data = { persons, mentees, mentors }
return { status: 200, data }
} catch (err) {
console.log(err)
return { status: 404 }
}
}
getData().then(({ status, data: { persons, mentees, mentors } }) => {
if (status !== 200) {
throw new Error('Error when fetching data from spreadsheet')
}
fs.writeFileSync('content/persons.json', JSON.stringify(clearData(persons), null, 2))
fs.writeFileSync('static/persons.json', JSON.stringify(clearData(persons), null, 2))
fs.writeFileSync('static/mentees.json', JSON.stringify(clearData(mentees), null, 2))
fs.writeFileSync('static/mentors.json', JSON.stringify(clearData(mentors), null, 2))
})