Created
November 12, 2021 04:27
-
-
Save kmelve/574ea6af71804ce86f560e5414102808 to your computer and use it in GitHub Desktop.
Proof of concepts simple page views with Next.js middleware
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
// posts/_middleware.js | |
import { NextResponse } from 'next/server' | |
const config = { | |
dataset: process.env.NEXT_PUBLIC_SANITY_DATASET || 'production', | |
projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID, | |
apiVersion: '2021-10-21', | |
} | |
const baseUrl = cdn => `https://${config.projectId}.api${cdn ? 'cdn' : ''}.sanity.io/v${config.apiVersion}` | |
const queryUrl = baseUrl() + `/data/query/${config.dataset}/` | |
const mutateUrl = baseUrl() + `/data/mutate/${config.dataset}` | |
const query = `*[slug.current == $slug][0]{ | |
..., | |
"stats": *[_type == "stats" && post._ref == ^._id][0] | |
}` | |
export async function middleware(req, ev) { | |
const { href } = req.nextUrl | |
const getStats = new URL(queryUrl) | |
getStats.searchParams.append('query', query) | |
getStats.searchParams.append('$slug', `"${href.replace('/posts/', '')}"`) | |
const { result } = await fetch(getStats.href).then(res => res.json()) | |
const { _id } = result | |
const res = await fetch(mutateUrl, { | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/json', | |
'Authorization': 'Bearer ' + process.env.SANITY_API_TOKEN | |
}, | |
body: JSON.stringify({ | |
mutations: [ | |
_id ? { | |
createIfNotExists: { | |
_id: 'stats.' + _id, | |
_type: 'stats', | |
views: 1, | |
post: { | |
_type: 'reference', | |
_ref: _id | |
} | |
} | |
} : undefined, | |
{ | |
patch: { | |
id: 'stats.' + _id, | |
setIfMissing: { 'views': 1 }, | |
inc: { | |
views: 1 | |
}, | |
} | |
}] | |
}) | |
}).then(res => res.json()) | |
return NextResponse.next() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment