-
Notifications
You must be signed in to change notification settings - Fork 17
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #141 from jsjoeio/add-page-views
feat: add page views
- Loading branch information
Showing
18 changed files
with
2,328 additions
and
111 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
// required to get firebase-sdk imported into netlify functions | ||
// see: https://github.com/netlify/netlify-lambda/issues/112#issuecomment-488644361 | ||
const nodeExternals = require('webpack-node-externals') | ||
const dotEnv = require('dotenv-webpack') | ||
|
||
module.exports = { | ||
externals: [nodeExternals()], | ||
plugins: [new dotEnv()], | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
import { db } from '../src/lib/db-admin' | ||
|
||
exports.handler = async (event, context) => { | ||
const { id } = event.queryStringParameters | ||
if (!id) { | ||
return { | ||
statusCode: 400, | ||
body: JSON.stringify({ | ||
error: 'Missing "id" query parameter', | ||
}), | ||
} | ||
} | ||
|
||
const ref = db.ref('joeprevite-dot-com/views').child(id) | ||
const { snapshot } = await ref.transaction(currentViews => { | ||
if (currentViews === null) { | ||
return 1 | ||
} | ||
|
||
return currentViews + 1 | ||
}) | ||
|
||
return { | ||
statusCode: 200, | ||
body: JSON.stringify({ | ||
pageId: id, | ||
totalViews: snapshot.val(), | ||
}), | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
import { db } from '../src/lib/db-admin' | ||
|
||
exports.handler = async (event, context) => { | ||
const { id } = event.queryStringParameters | ||
|
||
if (!id) { | ||
let totalViews | ||
await db.ref('joeprevite-dot-com/views').once('value', snapshot => { | ||
const views = snapshot.val() | ||
// Grabs all the views for all posts | ||
const allViews = Object.values(views).reduce( | ||
(total, value) => total + value, | ||
) | ||
totalViews = allViews | ||
}) | ||
return { | ||
statusCode: 200, | ||
body: JSON.stringify({ | ||
totalViews: totalViews || 0, | ||
}), | ||
} | ||
} | ||
|
||
const ref = db.ref('joeprevite-dot-com/views').child(id) | ||
|
||
let totalViews | ||
await ref.once('value', snapshot => { | ||
const value = snapshot.val() | ||
totalViews = value | ||
}) | ||
|
||
return { | ||
statusCode: 200, | ||
body: JSON.stringify({ | ||
pageId: id, | ||
totalViews: totalViews !== null ? totalViews : 0, | ||
}), | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,6 @@ | ||
[build] | ||
command = "yarn build" | ||
functions = "functions-build" | ||
publish = "public" | ||
|
||
[[plugins]] | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,109 @@ | ||
import React from 'react' | ||
import useSWR from 'swr' | ||
import format from 'comma-number' | ||
|
||
import { css } from '@emotion/core' | ||
import { bpMaxSM } from '../lib/breakpoints' | ||
import Link from './Link' | ||
import fetcher from '../lib/fetcher' | ||
|
||
function Post({ post }) { | ||
const { data } = useSWR( | ||
`/.netlify/functions/page-views?id=${post.fields.slug}`, | ||
fetcher, | ||
) | ||
|
||
const views = data?.totalViews | ||
|
||
return ( | ||
<div | ||
css={css` | ||
:not(:first-of-type) { | ||
margin-top: 10px; | ||
} | ||
:first-of-type { | ||
margin-top: 10px; | ||
${bpMaxSM} { | ||
margin-top: 10px; | ||
} | ||
} | ||
.gatsby-image-wrapper { | ||
} | ||
${bpMaxSM} { | ||
padding: 20px; | ||
} | ||
display: flex; | ||
flex-direction: column; | ||
`} | ||
> | ||
{/* {post.frontmatter.banner && ( | ||
<div | ||
css={css` | ||
padding: 60px 60px 40px 60px; | ||
${bpMaxSM} { | ||
padding: 20px; | ||
} | ||
`} | ||
> | ||
<Link | ||
aria-label={`View ${post.frontmatter.title} article`} | ||
to={`/${post.fields.slug}`} | ||
> | ||
<Img sizes={post.frontmatter.banner.childImageSharp.fluid} /> | ||
</Link> | ||
</div> | ||
)} */} | ||
<div | ||
css={css` | ||
display: flex; | ||
flex-direction: row; | ||
align-items: center; | ||
justify-content: space-between; | ||
h2, | ||
small { | ||
margin-top: 30px; | ||
margin-bottom: 10px; | ||
} | ||
small { | ||
margin-left: 10px; | ||
white-space: nowrap; | ||
} | ||
${bpMaxSM} { | ||
flex-wrap: wrap; | ||
small { | ||
margin: 0; | ||
} | ||
} | ||
`} | ||
> | ||
<h2> | ||
<Link | ||
aria-label={`View ${post.frontmatter.title} article`} | ||
to={`/${post.fields.slug}`} | ||
> | ||
{post.frontmatter.title} | ||
</Link> | ||
</h2> | ||
<small>{`${ | ||
views !== null && views !== undefined ? format(views) : '–––' | ||
} views`}</small> | ||
</div> | ||
<p | ||
css={css` | ||
margin-top: 10px; | ||
`} | ||
> | ||
{post.excerpt} | ||
</p>{' '} | ||
<Link | ||
to={`/${post.fields.slug}`} | ||
aria-label={`view "${post.frontmatter.title}" article`} | ||
> | ||
Read Article → | ||
</Link> | ||
</div> | ||
) | ||
} | ||
|
||
export default Post |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
/** | ||
* credit to @leerob who wrote this | ||
* @see https://github.com/leerob/leerob.io/blob/master/components/ViewCounter.js | ||
*/ | ||
import React, { useState, useEffect } from 'react' | ||
import format from 'comma-number' | ||
|
||
import { loadDb } from '../lib/db' | ||
|
||
const ViewCounter = ({ id }) => { | ||
const [views, setViews] = useState('') | ||
|
||
useEffect(() => { | ||
const onViews = newViews => setViews(newViews.val()) | ||
|
||
let db | ||
|
||
const fetchData = async () => { | ||
db = await loadDb() | ||
db.child(id).on('value', onViews, error => { | ||
console.error('Error reading value', error) | ||
}) | ||
} | ||
|
||
fetchData() | ||
|
||
return () => { | ||
if (db) { | ||
db.child(id).off('value', onViews) | ||
} | ||
} | ||
}, [id]) | ||
|
||
useEffect(() => { | ||
const registerView = () => | ||
fetch(`/.netlify/functions/increment-views?id=${id}`) | ||
|
||
registerView() | ||
}, [id]) | ||
|
||
return <p>{`${views ? format(views) : '–––'} views`}</p> | ||
} | ||
|
||
export default ViewCounter |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
/** | ||
* credit to @leerob who wrote this | ||
* @see https://github.com/leerob/leerob.io/blob/master/lib/db-admin.js | ||
*/ | ||
const admin = require('firebase-admin') | ||
|
||
try { | ||
admin.initializeApp({ | ||
credential: admin.credential.cert({ | ||
client_email: process.env.FIREBASE_CLIENT_EMAIL, | ||
private_key: process.env.FIREBASE_PRIVATE_KEY, | ||
project_id: 'website-pageviews-c8d4d', | ||
}), | ||
databaseURL: 'https://website-pageviews-c8d4d.firebaseio.com/', | ||
}) | ||
} catch (error) { | ||
/* | ||
* We skip the "already exists" message which is | ||
* not an actual error when we're hot-reloading. | ||
*/ | ||
if (!/already exists/u.test(error.message)) { | ||
// eslint-disable-next-line no-console | ||
console.error('Firebase admin initialization error', error.stack) | ||
} | ||
} | ||
|
||
export const db = admin.database() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
/** | ||
* credit to @leerob who wrote this | ||
* @see https://github.com/leerob/leerob.io/blob/master/lib/db.js | ||
*/ | ||
export async function loadDb() { | ||
const firebase = await import('firebase/app') | ||
|
||
await import('firebase/database') | ||
|
||
try { | ||
firebase.initializeApp({ | ||
databaseURL: 'https://website-pageviews-c8d4d.firebaseio.com/', | ||
}) | ||
} catch (error) { | ||
/* | ||
* We skip the "already exists" message which is | ||
* not an actual error when we're hot-reloading. | ||
*/ | ||
if (!/already exists/u.test(error.message)) { | ||
// eslint-disable-next-line no-console | ||
console.error('Firebase initialization error', error.stack) | ||
} | ||
} | ||
|
||
return firebase.database().ref('joeprevite-dot-com/views') | ||
} |
Oops, something went wrong.