forked from danielbayerlein/dashboard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
score.js
72 lines (62 loc) · 1.89 KB
/
score.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
import { Component } from 'react'
import fetch from 'isomorphic-unfetch'
import { object, string, number, boolean } from 'yup'
import CircleProgress from '../../circle-progress'
import Widget from '../../widget'
const schema = object().shape({
url: string().url().required(),
filterThirdPartyResources: boolean(),
interval: number(),
strategy: string(),
title: string()
})
export default class PageSpeedInsightsScore extends Component {
static defaultProps = {
filterThirdPartyResources: false,
interval: 1000 * 60 * 60 * 12,
strategy: 'desktop',
title: 'PageSpeed Score'
}
state = {
score: 0,
loading: true,
error: false
}
componentDidMount () {
schema.validate(this.props)
.then(() => this.fetchInformation())
.catch((err) => {
console.error(`${err.name} @ ${this.constructor.name}`, err.errors)
this.setState({ error: true, loading: false })
})
}
componentWillUnmount () {
clearTimeout(this.timeout)
}
async fetchInformation () {
const { url, filterThirdPartyResources, strategy } = this.props
const searchParams = [
`url=${url}`,
`filter_third_party_resources=${filterThirdPartyResources}`,
`strategy=${strategy}`
].join('&')
try {
const res = await fetch(`https://www.googleapis.com/pagespeedonline/v2/runPagespeed?${searchParams}`)
const json = await res.json()
this.setState({ error: false, loading: false, score: json.ruleGroups.SPEED.score })
} catch (error) {
this.setState({ error: true, loading: false })
} finally {
this.timeout = setTimeout(() => this.fetchInformation(), this.props.interval)
}
}
render () {
const { error, loading, score } = this.state
const { title } = this.props
return (
<Widget title={title} loading={loading} error={error}>
<CircleProgress value={score} />
</Widget>
)
}
}