UNPKG

1.81 kBJavaScriptView Raw
1import React from 'react'
2import PropTypes from 'prop-types'
3import { createClient } from 'contentful'
4
5let client
6
7function initContentful () {
8 let host = 'cdn.contentful.com'
9 if (parseInt(process.env.REACT_APP_CONTENTFUL_PREVIEW, 10) === 1) {
10 host = 'preview.contentful.com'
11 }
12 client = createClient({
13 space: process.env.REACT_APP_CONTENTFUL_SPACE_KEY,
14 accessToken: process.env.REACT_APP_CONTENTFUL_ACCESS_TOKEN,
15 host: host
16 })
17 return client.getSpace()
18 .then((space) => {
19 return space
20 })
21}
22
23function getClient () {
24 return client
25}
26
27export const getUrl = (entry) => entry.fields.file.url
28export const getAlt = (entry) => entry.fields.description
29export const getContentType = (entry) => {
30 return entry.sys.contentType.sys.id
31}
32export const getAssetType = (entry) => /([a-z]*)\//.exec(entry.fields.file.contentType)[1]
33
34
35export { initContentful, getClient }
36
37initContentful()
38
39export default class Contentful extends React.Component {
40 constructor(props) {
41 super(props)
42
43 this.state = {
44 response: null
45 }
46 }
47 componentDidMount() {
48 const { operation: inOp, id, query } = this.props
49 const client = getClient()
50 try {
51 if (inOp !== 'getEntries') {
52 client[inOp](id).then((response) => {
53 this.setState({response: response})
54 })
55 } else {
56 client[inOp](query).then((response) => {
57 this.setState({response: response.items[0]})
58 })
59 }
60 } catch (err) {
61 console.warn(err)
62 }
63 }
64 render() {
65 const { children } = this.props
66 const { response } = this.state
67 if (response) {
68 return React.createElement(children.type, {...children.props, ...response,})
69 } else {
70 return null
71 }
72 }
73}
74
75
76
77Contentful.propTypes = {
78 operation: PropTypes.string
79}